-
Notifications
You must be signed in to change notification settings - Fork 399
Expand file tree
/
Copy pathCodeMirror.svelte
More file actions
436 lines (394 loc) · 12.3 KB
/
CodeMirror.svelte
File metadata and controls
436 lines (394 loc) · 12.3 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
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
<script module>
// once initialized, references the codemirror instance
let instance;
// saved and session code vars are used to track unsaved changes
let savedCode = null;
let sessionCode = null;
export function cmChanged() {
if (sessionCode === null || sessionCode.localeCompare(savedCode) === 0) {
return false;
}
return true;
}
export function cmSetSavedCode(code) {
savedCode = code;
}
export function cmSetSessionCode(code) {
sessionCode = code;
}
export function cmGetInstance() {
return instance;
}
</script>
<script>
import CodeMirror from "../../codemirror.js";
import "../../codemirror.css";
import { settings, v4state } from "../../store.js";
import EditorSearch from "./EditorSearch.svelte";
import { parseMetadata, validGrants, validMetaKeys } from "@ext/utils.js";
// the function to be called when save keybind is pressed
export let saveHandler;
// message handler
export let handleMessage;
// indicates whether the codemirror instance has completed initialization
let initialized = false;
// save ref to textarea element for codemirror initialization
let textarea;
// used to determine whether or not to auto hint
let keysPressed = [];
// , 10, 10store cursor location on save, when re-enabling restore cursor position
let cursor;
// bound to the search component
let search;
// tracks whether search is open
let searchActive = false;
// linter options - https://jshint.com/docs/options/
const lintOptions = {
async: true,
getAnnotations: linter,
};
// svelte-ignore reactive_declaration_module_script_dependency
// update settings when changed
$: if (instance) {
instance.setOption("autoCloseBrackets", $settings["editor_close_brackets"]);
instance.setOption("showInvisibles", $settings["editor_show_whitespace"]);
instance.setOption("tabSize", parseInt($settings["editor_tab_size"], 10));
instance.setOption(
"indentUnit",
parseInt($settings["editor_tab_size"], 10),
);
}
// svelte-ignore reactive_declaration_module_script_dependency
// store cursor position and disable on save
$: if ($v4state.includes("saving")) {
cursor = instance.getCursor();
disable();
}
// svelte-ignore reactive_declaration_module_script_dependency
// re-enable after, focus and set cursor back save completes
$: if (
$v4state.includes("ready") &&
v4state.getOldState().includes("saving")
) {
enable();
instance.focus();
instance.setCursor(cursor);
}
// disable when trashing or updating file
$: if ($v4state.includes("trashing") || $v4state.includes("updating")) {
disable();
}
// svelte-ignore reactive_declaration_module_script_dependency
// reset saved and session code & re-enable after trashing completes
$: if ($v4state && v4state.getOldState().includes("trashing")) {
savedCode = null;
sessionCode = null;
enable();
}
// update session code and re-enable after updating completes
// svelte-ignore reactive_declaration_module_script_dependency
$: if ($v4state && v4state.getOldState().includes("updating")) {
sessionCode = instance.getValue();
enable();
}
// svelte-ignore reactive_declaration_module_script_dependency
// track lint settings and update accordingly
$: if (instance && $settings["editor_javascript_lint"]) {
toggleLint("enable");
} else if (instance && !$settings["editor_javascript_lint"]) {
toggleLint("disable");
}
export function init() {
// do lint settings check
const lint = $settings["editor_javascript_lint"] ? lintOptions : false;
// create codemirror instance
instance = CodeMirror.fromTextArea(textarea, {
mode: "javascript",
autoCloseBrackets: $settings["editor_close_brackets"],
continueComments: true,
foldGutter: true,
lineNumbers: true,
lineWrapping: true,
matchBrackets: true,
smartIndent: true,
styleActiveLine: true,
indentUnit: parseInt($settings["editor_tab_size"], 10),
showInvisibles: $settings["editor_show_whitespace"],
tabSize: parseInt($settings["editor_tab_size"], 10),
highlightSelectionMatches: false,
lint,
hintOptions: {
useGlobalScope: true,
},
gutters: [
"CodeMirror-lint-markers",
"CodeMirror-linenumbers",
"CodeMirror-foldgutter",
],
extraKeys: {
"Ctrl-Space": "autocomplete",
"Cmd-/": "toggleComment",
"Cmd-S": () => saveHandler(),
"Cmd-F": () => activateSearch(),
Esc: () => (searchActive = false),
},
});
// when a user hits a key, save key to keysPressed array
// the keys in the keysPressed array will help determine whether or not to show hints
// if it is a backspace key, empty array
instance.on("keydown", (cm, e) => {
if (e.code === "Backspace") return (keysPressed = []);
keysPressed.push(e.code);
autoHint(cm);
});
// on key up empty the keysPressed array
// this allows tracking of multiple key pressed (i.e. keybinds)
instance.on("keyup", (cm, e) =>
keysPressed.splice(keysPressed.indexOf(e.code), 1),
);
// if codemirror editor loses focus, empty keysPressed array
instance.on("blur", () => (keysPressed = []));
instance.on("change", onChange);
instance.on("beforeChange", preventAutoFullStops);
// update indicator
initialized = true;
}
function activateSearch() {
if (searchActive) {
search.focusInput();
} else {
searchActive = true;
}
}
function autoHint(cm) {
// check for valid key combinations
const validKeys = keysPressed.every((v) => {
// if a single key press, only show hint if letter/number
if (keysPressed.length === 1) {
return v.startsWith("Digit") || v.startsWith("Key");
// if 2 key combo, show hints with shift as well
} else if (keysPressed.length === 2) {
return (
v.startsWith("Digit") || v.startsWith("Key") || v.startsWith("Shift")
);
}
});
if (
// check if setting is enabled
$settings["editor_auto_hint"] &&
// ensure hinting not active already
!cm.state.completionActive &&
// not first position on the line
cm.getCursor().ch !== 0 &&
// only hint when 1-2 key combos
keysPressed.length < 3 &&
// valid keys combo
validKeys
)
cm.showHint({ completeSingle: false });
}
function onChange(cm, e) {
const inputAction = e.origin;
// if search is active, update count on change
if (searchActive) search.getMatches();
// setValue occurs when programmatically changing codemirror values
// below is all other input actions
if (inputAction !== "setValue") {
sessionCode = cm.getValue();
if (cmChanged()) handleMessage({ name: "enableButtons" });
}
if ((inputAction === "undo" || inputAction === "redo") && !cmChanged()) {
// back to the point where session and saved code are equal, and buttons enabled
handleMessage({ name: "disableButtons" });
}
}
function preventAutoFullStops(cm, changeObj) {
if (
changeObj.origin === "+input" &&
changeObj.text.length === 1 &&
changeObj.text[0] === ". "
) {
changeObj.update(changeObj.from, changeObj.to, [" "]);
}
}
// disables the editor
function disable() {
instance.setOption("readOnly", "nocursor");
instance.display.wrapper.style.opacity = "0.30";
}
// enables the editor
function enable() {
instance.setOption("readOnly", false);
instance.display.wrapper.removeAttribute("style");
}
function toggleLint(disableOrEnable) {
const lint = disableOrEnable === "enable" ? lintOptions : false;
instance.setOption("lint", lint);
instance.refresh();
}
/**
* @param {{set: Set<string>, setName: string, message: string}}
* @returns {{from: {line: number, ch: number},
* to: {line: number, ch: number}, message: string, severity: string}}
*/
function makeErrors({ set, setName, message }) {
const errors = [];
// for (let i = 0; i < array.length; i++) {
set.forEach((el) => {
// const el = array[i];
let regex = new RegExp(`^${el}$`);
if (setName === "invalidKeys") {
regex = new RegExp(`^// @${el}.*?$`);
}
const instanceCursor = instance.getSearchCursor(regex);
const ranges = [];
while (instanceCursor.findNext()) {
ranges.push({
anchor: instanceCursor.from(),
head: instanceCursor.to(),
});
}
for (let j = 0; j < ranges.length; j++) {
const range = ranges[j];
const err = {
from: range?.anchor,
to: range?.head,
severity: "warning",
message,
};
errors.push(err);
}
});
return errors;
}
function linter(text, updateLinting) {
// toggle for custom metadata linting
const customLinter = true;
// only lint in javascript mode
if (instance?.options.mode !== "javascript") return;
// normal javascript linting through CodeMirror addon and jshint
let errors = CodeMirror.lint.javascript(text, {
asi: true,
esversion: 9,
});
// errors from custom checks & metadata parser will populate this array
let customErrors = [];
if (customLinter) {
// check if whitespace characters precede userscript tags
if (/^\s/.test(text)) {
customErrors.push({
from: { line: 0, ch: 0 },
to: { line: 0, ch: 0 },
severity: "warning",
message: "Userscript starts with whitespace characters.",
});
}
// parse the code metadata
const parsedMetadata = parseMetadata(text);
// check parser result for initial errors
if (parsedMetadata.match === false) {
customErrors.push({
from: { line: 0, ch: 0 },
to: { line: 0, ch: 0 },
severity: "error",
message: "Userscript metadata missing or improperly formatted.",
});
} else if (parsedMetadata.meta === false) {
customErrors.push({
from: { line: 0, ch: 0 },
to: { line: 0, ch: 0 },
severity: "error",
message: "Userscript metadata missing.",
});
}
// run additional checks
const invalidKeys = new Set();
let invalidKeysErrors = [];
const invalidGrants = new Set();
let invalidGrantsErrors = [];
const emptyKeyValues = new Set();
let emptyKeyValuesErrors = [];
// if metadata fails initial check, it won't be array
// don't run the additional checks if initial checks failed
if (Array.isArray(parsedMetadata)) {
// find invalid keys or empty key values
for (let i = 0; i < parsedMetadata.length; i++) {
const { key, value: val, text: metaText } = parsedMetadata[i];
if (!validMetaKeys.has(key)) {
invalidKeys.add(key);
}
if (key !== "noframes" && !invalidKeys.has(key) && !val) {
emptyKeyValues.add(metaText);
}
}
// find unsupported @grant methods
const grants = parsedMetadata.filter((a) => a.key === "grant");
for (let i = 0; i < grants.length; i++) {
const { value: val, text: grantText } = grants[i];
if (!validGrants.has(val)) {
invalidGrants.add(grantText);
}
}
}
invalidKeysErrors = makeErrors({
set: invalidKeys,
setName: "invalidKeys",
message: "Unsupported metadata key.",
});
emptyKeyValuesErrors = makeErrors({
set: emptyKeyValues,
setName: "emptyKeyValues",
message: "Key requires a value.",
});
invalidGrantsErrors = makeErrors({
set: invalidGrants,
setName: "invalidGrants",
message: "@grant method not supported.",
});
// combine all custom error arrays
customErrors = [
...customErrors,
...invalidKeysErrors,
...emptyKeyValuesErrors,
...invalidGrantsErrors,
];
}
// if the custom linter returned errors, add them to errors array
if (customErrors.length) errors = [...errors, ...customErrors];
updateLinting(errors);
}
// function that is called for editor component when clicking discard button
export function discardChanges() {
if ($v4state.includes("ready")) {
instance.setValue(savedCode);
sessionCode = null;
instance.focus();
handleMessage({ name: "disableButtons" });
}
}
// allow editor component to get direct access to codemirror instance value
export function getValue() {
return instance.getValue();
}
</script>
<textarea bind:this={textarea}></textarea>
<!--
dynamically add search component, since it requires instance to function
if instance is passed to component before instance is set (init is called in Editor component)
instance will remain undefined, which would require importing cmGetInstance in search component
and creating circular dependency
-->
{#if initialized}
<svelte:component
this={EditorSearch}
active={searchActive}
bind:this={search}
closeHandler={() => (searchActive = false)}
{instance}
/>
{/if}
<style>
:global(.CodeMirror-scroll) {
overscroll-behavior: none;
}
</style>