This repository has been archived by the owner on Jul 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
/
index.js
90 lines (77 loc) · 2.55 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
'use strict';
var React = require('react');
var CodeMirror;
// adapted from:
// https://github.com/facebook/react/blob/master/docs/_js/live_editor.js#L16
// also used as an example:
// https://github.com/facebook/react/blob/master/src/browser/ui/dom/components/ReactDOMInput.js
var IS_MOBILE = typeof navigator === 'undefined' || (
navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
);
if (!IS_MOBILE) {
CodeMirror = require('codemirror');
}
var CodeMirrorEditor = React.createClass({
getInitialState: function() {
return { isControlled: this.props.value != null };
},
propTypes: {
value: React.PropTypes.string,
defaultValue: React.PropTypes.string,
style: React.PropTypes.object,
className: React.PropTypes.string,
onChange: React.PropTypes.func
},
componentDidMount: function() {
var isTextArea = this.props.forceTextArea || IS_MOBILE;
if (!isTextArea) {
var editor = this.refs.editor;
if (!editor.getAttribute) editor = editor.getDOMNode();
this.editor = CodeMirror.fromTextArea(editor, this.props);
this.editor.on('change', this.handleChange);
}
},
componentDidUpdate: function() {
if (this.editor) {
if (this.props.value != null) {
if (this.editor.getValue() !== this.props.value) {
this.editor.setValue(this.props.value);
}
}
}
},
handleChange: function() {
if (this.editor) {
var value = this.editor.getValue();
if (value !== this.props.value) {
this.props.onChange && this.props.onChange({target: {value: value}});
if (this.editor.getValue() !== this.props.value) {
if (this.state.isControlled) {
this.editor.setValue(this.props.value);
} else {
this.props.value = value;
}
}
}
}
},
render: function() {
var editor = React.createElement('textarea', {
ref: 'editor',
value: this.props.value,
readOnly: this.props.readOnly,
defaultValue: this.props.defaultValue,
onChange: this.props.onChange,
style: this.props.textAreaStyle,
className: this.props.textAreaClassName || this.props.textAreaClass
});
return React.createElement('div', {style: this.props.style, className: this.props.className}, editor);
}
});
module.exports = CodeMirrorEditor;