react-templates/playground/CodeMirrorViewer.js

46 lines
1.8 KiB
JavaScript
Raw Normal View History

2014-12-30 16:33:28 +01:00
define(['react', 'lodash', 'jquery', './libs/codemirror-4.8/lib/codemirror',
'./libs/codemirror-4.8/mode/javascript/javascript',
'./libs/codemirror-4.8/mode/xml/xml',
'./libs/codemirror-4.8/addon/runmode/runmode'
], function (React, _, $, CodeMirror) {
'use strict';
return React.createClass({
displayName: 'CodeMirrorViewer',
propTypes: {
id: React.PropTypes.string,
mode: React.PropTypes.string,
value: React.PropTypes.string,
valueLink: React.PropTypes.string
2014-12-30 16:33:28 +01:00
},
getDefaultProps: function () {
return {mode: 'html'};
2014-12-30 16:33:28 +01:00
},
getInitialState: function () {
return {editorId: _.uniqueId()};
2014-12-30 16:33:28 +01:00
},
render: function () {
var props = _.omit(this.props, ['ref', 'key', 'value', 'valueLink', 'onChange']);
props.id = this.props.id || this.state.editorId;
props.className = 'cm-s-default';
var value = this.props.valueLink ? this.props.valueLink() : this.props.value;
return React.DOM.pre(props, value);
},
componentWillUpdate: function (nextProps/*, nextState*/) {
var value = nextProps.valueLink ? nextProps.valueLink() : nextProps.value;
if (this.editor && this.editor.getValue() !== value) {
this.editor.setValue(value || '');
}
},
componentDidMount: function () {
var value = this.props.valueLink ? this.props.valueLink() : this.props.value;
2014-12-30 16:49:13 +01:00
var mode = this.props.mode;
2014-12-30 16:33:28 +01:00
if (this.props.mode === 'html') {
2014-12-30 16:49:13 +01:00
mode = 'text/html';
2014-12-30 16:33:28 +01:00
}
2014-12-30 16:49:13 +01:00
this.editor = CodeMirror.runMode(value, mode, this.getDOMNode());
2014-12-30 16:33:28 +01:00
},
componentWillUnmount: function () {
this.editor.toTextArea();
}
});
});