-
-
Notifications
You must be signed in to change notification settings - Fork 86
/
index.js
101 lines (91 loc) · 2.34 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
91
92
93
94
95
96
97
98
99
100
101
import React from 'react';
import Runtime from './runtime';
import compile from 'idyll-compiler';
const defaultAST = {
id: 0,
type: 'component',
name: 'root'
};
export const hashCode = str => {
var hash = 0,
i,
chr;
if (str.length === 0) return hash;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
class IdyllDocument extends React.Component {
constructor(props) {
super(props);
this.state = {
ast: props.ast || defaultAST,
previousAST: props.ast || defaultAST,
hash: '',
error: null
};
}
componentDidMount() {
if (!this.props.ast && this.props.markup) {
compile(this.props.markup, this.props.compilerOptions).then(ast => {
this.setState({ ast, hash: hashCode(this.props.markup), error: null });
});
}
}
componentDidCatch(error, info) {
this.props.onError && this.props.onError(error);
this.setState({ error: error.message });
}
componentWillReceiveProps(newProps) {
if (newProps.ast) {
return;
}
const hash = hashCode(newProps.markup);
if (hash !== this.state.hash) {
this.setState({ previousAST: this.state.ast });
compile(newProps.markup, newProps.compilerOptions)
.then(ast => {
this.setState({ previousAST: ast, ast, hash, error: null });
})
.catch(this.componentDidCatch.bind(this));
}
}
getErrorComponent() {
if (!this.state.error) {
return null;
}
return React.createElement(
this.props.errorComponent || 'pre',
{
className: 'idyll-document-error'
},
this.state.error
);
}
render() {
return (
<div>
<Runtime
{...this.props}
key={this.state.hash}
context={context => {
this.idyllContext = context;
typeof this.props.context === 'function' &&
this.props.context(context);
}}
initialState={
this.props.initialState ||
(this.idyllContext ? this.idyllContext.data() : {})
}
ast={this.props.ast || this.state.ast}
userViewComponent={this.props.userViewComponent}
/>
{this.getErrorComponent()}
</div>
);
}
}
export default IdyllDocument;