-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathcodemirror.js
282 lines (257 loc) · 8.71 KB
/
codemirror.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import { useRef, useEffect } from 'react';
import CodeMirror from 'codemirror';
import 'codemirror/mode/css/css';
import 'codemirror/mode/clike/clike';
import 'codemirror/addon/selection/active-line';
import 'codemirror/addon/lint/lint';
import 'codemirror/addon/lint/javascript-lint';
import 'codemirror/addon/lint/css-lint';
import 'codemirror/addon/lint/html-lint';
import 'codemirror/addon/fold/brace-fold';
import 'codemirror/addon/fold/comment-fold';
import 'codemirror/addon/fold/foldcode';
import 'codemirror/addon/fold/foldgutter';
import 'codemirror/addon/fold/indent-fold';
import 'codemirror/addon/fold/xml-fold';
import 'codemirror/addon/comment/comment';
import 'codemirror/keymap/sublime';
import 'codemirror/addon/search/searchcursor';
import 'codemirror/addon/search/matchesonscrollbar';
import 'codemirror/addon/search/match-highlighter';
import 'codemirror/addon/search/jump-to-line';
import 'codemirror/addon/edit/matchbrackets';
import 'codemirror/addon/edit/closebrackets';
import 'codemirror/addon/selection/mark-selection';
import 'codemirror-colorpicker';
import { debounce } from 'lodash';
import emmet from '@emmetio/codemirror-plugin';
import { useEffectWithComparison } from '../../hooks/custom-hooks';
import { metaKey } from '../../../../utils/metaKey';
import { showHint } from './hinter';
import tidyCode from './tidier';
import getFileMode from './utils';
const INDENTATION_AMOUNT = 2;
emmet(CodeMirror);
/**
* This is a custom React hook that manages CodeMirror state.
* TODO(Connie Ye): Revisit the linting on file switch.
*/
export default function useCodeMirror({
theme,
lineNumbers,
linewrap,
autocloseBracketsQuotes,
setUnsavedChanges,
setCurrentLine,
hideRuntimeErrorWarning,
updateFileContent,
file,
files,
autorefresh,
isPlaying,
clearConsole,
startSketch,
autocompleteHinter,
fontSize,
onUpdateLinting
}) {
// The codemirror instance.
const cmInstance = useRef();
// The current codemirror files.
const docs = useRef();
function onKeyUp() {
const lineNumber = parseInt(cmInstance.current.getCursor().line + 1, 10);
setCurrentLine(lineNumber);
}
function onKeyDown(_cm, e) {
// Show hint
const mode = cmInstance.current.getOption('mode');
if (/^[a-z]$/i.test(e.key) && (mode === 'css' || mode === 'javascript')) {
showHint(_cm, autocompleteHinter, fontSize);
}
if (e.key === 'Escape') {
e.preventDefault();
const selections = cmInstance.current.listSelections();
if (selections.length > 1) {
const firstPos = selections[0].head || selections[0].anchor;
cmInstance.current.setSelection(firstPos);
cmInstance.current.scrollIntoView(firstPos);
} else {
cmInstance.current.getInputField().blur();
}
}
}
// We have to create a ref for the file ID, or else the debouncer
// will old onto an old version of the fileId and just overrwrite the initial file.
const fileId = useRef();
fileId.current = file.id;
// When the file changes, update the file content and save status.
function onChange() {
setUnsavedChanges(true);
hideRuntimeErrorWarning();
updateFileContent(fileId.current, cmInstance.current.getValue());
if (autorefresh && isPlaying) {
clearConsole();
startSketch();
}
}
const debouncedOnChange = debounce(onChange, 1000);
// When the container component enters the DOM, we want this function
// to be called so we can setup the CodeMirror instance with the container.
function setupCodeMirrorOnContainerMounted(container) {
cmInstance.current = CodeMirror(container, {
theme: `p5-${theme}`,
lineNumbers,
styleActiveLine: true,
inputStyle: 'contenteditable',
lineWrapping: linewrap,
fixedGutter: false,
foldGutter: true,
foldOptions: { widget: '\u2026' },
gutters: ['CodeMirror-foldgutter', 'CodeMirror-lint-markers'],
keyMap: 'sublime',
highlightSelectionMatches: true, // highlight current search match
matchBrackets: true,
emmet: {
preview: ['html'],
markTagPairs: true,
autoRenameTags: true
},
autoCloseBrackets: autocloseBracketsQuotes,
styleSelectedText: true,
lint: {
onUpdateLinting,
options: {
asi: true,
eqeqeq: false,
'-W041': false,
esversion: 11
}
},
colorpicker: {
type: 'sketch',
mode: 'edit'
}
});
delete cmInstance.current.options.lint.options.errors;
const replaceCommand =
metaKey === 'Ctrl' ? `${metaKey}-H` : `${metaKey}-Option-F`;
cmInstance.current.setOption('extraKeys', {
Tab: (tabCm) => {
if (!tabCm.execCommand('emmetExpandAbbreviation')) return;
// might need to specify and indent more?
const selection = tabCm.doc.getSelection();
if (selection.length > 0) {
tabCm.execCommand('indentMore');
} else {
tabCm.replaceSelection(' '.repeat(INDENTATION_AMOUNT));
}
},
Enter: 'emmetInsertLineBreak',
Esc: 'emmetResetAbbreviation',
[`Shift-Tab`]: false,
[`${metaKey}-Enter`]: () => null,
[`Shift-${metaKey}-Enter`]: () => null,
[`${metaKey}-F`]: 'findPersistent',
[`Shift-${metaKey}-F`]: () => tidyCode(cmInstance.current),
[`${metaKey}-G`]: 'findPersistentNext',
[`Shift-${metaKey}-G`]: 'findPersistentPrev',
[replaceCommand]: 'replace',
// Cassie Tarakajian: If you don't set a default color, then when you
// choose a color, it deletes characters inline. This is a
// hack to prevent that.
[`${metaKey}-K`]: (metaCm, event) =>
metaCm.state.colorpicker.popup_color_picker({ length: 0 }),
[`${metaKey}-.`]: 'toggleComment' // Note: most adblockers use the shortcut ctrl+.
});
// Setup the event listeners on the CodeMirror instance.
cmInstance.current.on('change', debouncedOnChange);
cmInstance.current.on('keyup', onKeyUp);
cmInstance.current.on('keydown', onKeyDown);
cmInstance.current.getWrapperElement().style['font-size'] = `${fontSize}px`;
}
// When settings change, we pass those changes into CodeMirror.
useEffect(() => {
cmInstance.current.getWrapperElement().style['font-size'] = `${fontSize}px`;
}, [fontSize]);
useEffect(() => {
cmInstance.current.setOption('lineWrapping', linewrap);
}, [linewrap]);
useEffect(() => {
cmInstance.current.setOption('theme', `p5-${theme}`);
}, [theme]);
useEffect(() => {
cmInstance.current.setOption('lineNumbers', lineNumbers);
}, [lineNumbers]);
useEffect(() => {
cmInstance.current.setOption('autoCloseBrackets', autocloseBracketsQuotes);
}, [autocloseBracketsQuotes]);
// Initializes the files as CodeMirror documents.
function initializeDocuments() {
docs.current = {};
files.forEach((currentFile) => {
if (currentFile.name !== 'root') {
docs.current[currentFile.id] = CodeMirror.Doc(
currentFile.content,
getFileMode(currentFile.name)
);
}
});
}
// When the files change, reinitialize the documents.
useEffect(initializeDocuments, [files]);
// When the file changes, we change the file mode and
// make the CodeMirror call to swap out the document.
useEffectWithComparison(
(_, prevProps) => {
const fileMode = getFileMode(file.name);
if (fileMode === 'javascript') {
// Define the new Emmet configuration based on the file mode
const emmetConfig = {
preview: ['html'],
markTagPairs: false,
autoRenameTags: true
};
cmInstance.current.setOption('emmet', emmetConfig);
}
const oldDoc = cmInstance.current.swapDoc(docs.current[file.id]);
if (prevProps?.file) {
docs.current[prevProps.file.id] = oldDoc;
}
cmInstance.current.focus();
for (let i = 0; i < cmInstance.current.lineCount(); i += 1) {
cmInstance.current.removeLineClass(
i,
'background',
'line-runtime-error'
);
}
},
[file.id]
);
// Remove the CM listeners on component teardown.
function teardownCodeMirror() {
cmInstance.current.off('keyup', onKeyUp);
cmInstance.current.off('change', debouncedOnChange);
cmInstance.current.off('keydown', onKeyDown);
}
const getContent = () => {
const content = cmInstance.current.getValue();
const updatedFile = Object.assign({}, file, { content });
return updatedFile;
};
const showFind = () => {
cmInstance.current.execCommand('findPersistent');
};
const showReplace = () => {
cmInstance.current.execCommand('replace');
};
return {
setupCodeMirrorOnContainerMounted,
teardownCodeMirror,
cmInstance,
getContent,
showFind,
showReplace
};
}