forked from videni/rjsf-antd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSource.tsx
102 lines (85 loc) · 2.08 KB
/
Source.tsx
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
102
import React from 'react';
import classNames from 'classnames';
import { Icon } from 'antd';
import { Controlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
import 'codemirror/mode/javascript/javascript';
import styles from './Source.less';
const cmOptions = {
readOnly: false,
viewportMargin: Infinity,
mode: {
name: 'javascript',
json: true,
statementIndent: 2
},
lineNumbers: true,
lineWrapping: true,
indentWithTabs: false,
tabSize: 2
};
const isValid = value => {
let obj;
try {
obj = JSON.parse(value);
} catch (e) {
return false;
}
return obj;
};
class Source extends React.Component<any, any> {
constructor(props) {
super(props);
const source = JSON.stringify(this.props.source, null, 2);
this.state = {
source,
valid: isValid(source)
};
}
componentWillReceiveProps = nextProps => {
const source = JSON.stringify(nextProps.source, null, 2);
this.setState({
source,
valid: isValid(source)
});
};
onChange = (editor, data, value) => {
this.setState({ source: value });
};
onBeforeChange = (editor, data, value) => {
const { onChange } = this.props;
const parsed = isValid(value);
this.setState({
valid: parsed,
source: value
});
if (parsed && onChange) {
onChange(parsed);
}
};
render() {
const { source, valid } = this.state;
const { title } = this.props;
return (
<div className={styles.root}>
<div className={classNames(styles.ctr, { [styles.invalid]: !valid })}>
<div>
<Icon type={valid ? 'smile' : 'warning'} />
<span>{title}</span>
</div>
<div className={styles.source}>
<CodeMirror
value={source}
onChange={this.onChange}
onBeforeChange={this.onBeforeChange}
autoCursor={true}
options={cmOptions}
/>
</div>
</div>
</div>
);
}
}
export default Source;