forked from hull-ships/hull-processor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact-codemirror.js
More file actions
89 lines (85 loc) · 2.69 KB
/
react-codemirror.js
File metadata and controls
89 lines (85 loc) · 2.69 KB
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
import React from 'react';
import className from 'classnames';
const CodeMirror = React.createClass({
propTypes: {
onChange: React.PropTypes.func,
onFocusChange: React.PropTypes.func,
onScroll: React.PropTypes.func,
options: React.PropTypes.object,
path: React.PropTypes.string,
value: React.PropTypes.string,
className: React.PropTypes.any,
codeMirrorInstance: React.PropTypes.object,
},
getCodeMirrorInstance () {
return this.props.codeMirrorInstance || require('codemirror');
},
getInitialState () {
return {
isFocused: false,
};
},
componentDidMount () {
const textareaNode = this.refs.textarea;
const codeMirrorInstance = this.getCodeMirrorInstance();
this.codeMirror = codeMirrorInstance.fromTextArea(textareaNode, this.props.options);
this.codeMirror.on('change', this.codemirrorValueChanged);
this.codeMirror.on('focus', this.focusChanged.bind(this, true));
this.codeMirror.on('blur', this.focusChanged.bind(this, false));
this.codeMirror.on('scroll', this.scrollChanged);
this.codeMirror.setValue(this.props.defaultValue || this.props.value || '');
},
componentWillUnmount () {
// is there a lighter-weight way to remove the cm instance?
if (this.codeMirror) {
this.codeMirror.toTextArea();
}
},
componentWillReceiveProps: function (nextProps) {
if (this.codeMirror && nextProps.value !== undefined && this.codeMirror.getValue() != nextProps.value) {
this.codeMirror.setValue(nextProps.value);
}
if (typeof nextProps.options === 'object') {
for (let optionName in nextProps.options) {
if (nextProps.options.hasOwnProperty(optionName)) {
this.codeMirror.setOption(optionName, nextProps.options[optionName]);
}
}
}
},
getCodeMirror () {
return this.codeMirror;
},
focus () {
if (this.codeMirror) {
this.codeMirror.focus();
}
},
focusChanged (focused) {
this.setState({
isFocused: focused,
});
this.props.onFocusChange && this.props.onFocusChange(focused);
},
scrollChanged (cm) {
this.props.onScroll && this.props.onScroll(cm.getScrollInfo());
},
codemirrorValueChanged (doc, change) {
if (this.props.onChange && change.origin != 'setValue') {
this.props.onChange(doc.getValue());
}
},
render () {
const editorClassName = className(
'ReactCodeMirror',
this.state.isFocused ? 'ReactCodeMirror--focused' : null,
this.props.className
);
return (
<div className={editorClassName}>
<textarea ref="textarea" name={this.props.path} defaultValue={this.props.value} autoComplete="off" />
</div>
);
},
});
module.exports = CodeMirror;