react-templates/playground/CodeMirrorViewer.js

47 lines
1.8 KiB
JavaScript
Raw Normal View History

2016-07-06 09:33:48 +02:00
define(['react', 'react-dom', 'lodash', 'jquery', './libs/codemirror-4.8/lib/codemirror',
2017-01-01 16:19:35 +01:00
'./libs/codemirror-4.8/mode/javascript/javascript',
'./libs/codemirror-4.8/mode/xml/xml',
'./libs/codemirror-4.8/addon/runmode/runmode'
2016-07-06 09:33:48 +02:00
], function (React, ReactDOM, _, $, CodeMirror) {
2017-06-29 09:35:15 +02:00
'use strict'
2014-12-30 16:33:28 +01:00
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 () {
2017-06-29 09:35:15 +02:00
return {mode: 'html'}
2014-12-30 16:33:28 +01:00
},
getInitialState: function () {
2017-06-29 09:35:15 +02:00
return {editorId: _.uniqueId()}
2014-12-30 16:33:28 +01:00
},
render: function () {
2017-06-29 09:35:15 +02:00
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)
2014-12-30 16:33:28 +01:00
},
componentWillUpdate: function (nextProps/*, nextState*/) {
2017-06-29 09:35:15 +02:00
var value = nextProps.valueLink ? nextProps.valueLink() : nextProps.value
2014-12-30 16:33:28 +01:00
if (this.editor && this.editor.getValue() !== value) {
2017-06-29 09:35:15 +02:00
this.editor.setValue(value || '')
2014-12-30 16:33:28 +01:00
}
},
componentDidMount: function () {
2017-06-29 09:35:15 +02:00
var value = this.props.valueLink ? this.props.valueLink() : this.props.value
var mode = this.props.mode
2014-12-30 16:33:28 +01:00
if (this.props.mode === 'html') {
2017-06-29 09:35:15 +02:00
mode = 'text/html'
2014-12-30 16:33:28 +01:00
}
2017-06-29 09:35:15 +02:00
this.editor = CodeMirror.runMode(value, mode, ReactDOM.findDOMNode(this))
2014-12-30 16:33:28 +01:00
},
componentWillUnmount: function () {
2017-06-29 09:35:15 +02:00
this.editor.toTextArea()
2014-12-30 16:33:28 +01:00
}
2017-06-29 09:35:15 +02:00
})
})