-
Notifications
You must be signed in to change notification settings - Fork 28
/
live-compile.js
74 lines (62 loc) · 1.67 KB
/
live-compile.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
var React = require("react");
var ReactDOM = require("react-dom");
var babel = require('babel-core');
var selfCleaningTimeout = {
componentDidUpdate: function() {
clearTimeout(this.timeoutID);
},
setTimeout: function() {
clearTimeout(this.timeoutID);
this.timeoutID = setTimeout.apply(null, arguments);
}
};
var ComponentPreview = React.createClass({
propTypes: {
code: React.PropTypes.string.isRequired
},
mixins: [selfCleaningTimeout],
render: function() {
return <div ref="mount" />;
},
componentDidMount: function() {
this.executeCode();
},
componentDidUpdate: function(prevProps) {
// execute code only when the state's not being updated by switching tab
// this avoids re-displaying the error, which comes after a certain delay
if (this.props.code !== prevProps.code) {
this.executeCode();
}
},
compileCode: function() {
return babel.transform(
this.props.code,
{ presets:
[ require('babel-preset-es2015')
, require('babel-preset-react')
]
}
).code;
},
executeCode: function() {
var mountNode = this.refs.mount;
try {
ReactDOM.unmountComponentAtNode(mountNode);
} catch (e) { }
try {
var compiledCode = this.compileCode();
ReactDOM.render(
eval(compiledCode),
mountNode
);
} catch (err) {
this.setTimeout(function() {
ReactDOM.render(
<div className="playgroundError">{err.toString()}</div>,
mountNode
);
}, 500);
}
}
});
module.exports = ComponentPreview;