-
-
Notifications
You must be signed in to change notification settings - Fork 522
Expand file tree
/
Copy pathindex.jsx
More file actions
99 lines (86 loc) Β· 2.47 KB
/
Copy pathindex.jsx
File metadata and controls
99 lines (86 loc) Β· 2.47 KB
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
import { Component, render } from 'preact';
import codemirror from 'codemirror';
import cx from '../../lib/cx';
import 'codemirror/mode/jsx/jsx';
import 'codemirror/addon/comment/comment';
import 'codemirror/lib/codemirror.css';
import style from './style.module.css';
import './code-mirror.css';
export default class CodeEditor extends Component {
scratch = document.createElement('div');
showError(error) {
clearTimeout(this.showErrorTimer);
if (this.errors) {
this.editor.operation(() => {
this.errors.forEach(e => e.clear());
});
this.errors.length = 0;
}
if (!error || !error.loc) return;
this.showErrorTimer = setTimeout(() => {
this.editor.operation(() => {
let { left } = this.editor.cursorCoords(
{ line: error.loc.line - 1, ch: error.loc.column - 1 },
'local'
);
let ref;
const errorLine = (
<div ref={r => (ref = r)} class={style.lintError}>
<pre style={`padding-left:${left}px;`}>β²</pre>
<div>π₯ {error.message.split('\n')[0]}</div>
</div>
);
render(errorLine, this.scratch);
this.errors = [this.editor.addLineWidget(error.loc.line - 1, ref)];
});
}, 1000);
}
componentDidMount() {
let { spaces, value, tabSize } = this.props;
this.editor = codemirror(this.base, {
value: String(value || ''),
mode: 'jsx',
theme: 'one-dark',
lineNumbers: true,
indentWithTabs: !spaces,
tabSize: tabSize || 2,
indentUnit: spaces ? Math.round(spaces) || 2 : false,
showCursorWhenSelecting: true,
extraKeys: {
'Cmd-/': 'toggleComment'
}
});
this.editor.on('change', () => {
if (this.events === false) return;
this.value = this.editor.getValue();
let { onInput } = this.props;
if (onInput) onInput(this.value);
});
}
componentWillReceiveProps({ value, error }) {
let current = this.hasOwnProperty('value') ? this.value : this.props.value;
if (value !== current) {
let e = this.events;
this.events = false;
this.value = value;
this.editor.setValue(value);
this.showError(null);
setTimeout(() => this.editor.refresh(), 1);
this.events = e;
}
if (error !== this.props.error) {
this.showError(error);
}
}
shouldComponentUpdate() {
return false;
}
componentWillUnmount() {
let wrapper = this.editor && this.editor.getWrapperElement();
if (wrapper) this.base.removeChild(wrapper);
this.editor = null;
}
render({ value, onInput, children, ...props }) {
return <div {...props} class={cx(style.codeEditor, props.class)} />;
}
}