-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetupEditor.js
More file actions
97 lines (80 loc) · 2.27 KB
/
setupEditor.js
File metadata and controls
97 lines (80 loc) · 2.27 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
const completions = [
{ label: "circle", type: "keyword" },
{
label: "windowHeight",
type: "constant",
info: "Height of the sketch window.",
},
{
label: "windowWidth",
type: "constant",
info: "Width of the sketch window.",
},
{ label: "password", type: "variable" },
];
const lintOptions = {
esversion: 6,
};
function makeMarker(msg) {
const marker = document.createElement("div");
marker.classList.add("error-marker");
marker.innerHTML = " ";
const error = document.createElement("div");
error.innerHTML = msg;
error.classList.add("error-message");
marker.appendChild(error);
return marker;
}
async function fetchDefault() {
let response = await fetch(`examples/cones.js`);
return await response.text();
}
export async function setupEditor(state, editorRoot) {
if (state.useLocalStorage) {
state.sketch = localStorage.getItem("sketch") ?? (await fetchDefault());
} else {
state.sketch = await fetchDefault();
}
let editor = CodeMirror(editorRoot, {
lineNumbers: true,
tabSize: 2,
value: state.sketch,
mode: "javascript",
theme: "nord",
viewportMargin: Infinity,
scrollbarStyle: "simple",
gutters: ["error"],
});
editor.on("changes", handleChange);
state.editor = editor;
runLinter();
function runLinter() {
let sketchCode = editor.getValue();
JSHINT(sketchCode, lintOptions);
const errors = Array.isArray(JSHINT.errors) ? JSHINT.errors : [];
editor.clearGutter("error");
for (const error of errors) {
editor.setGutterMarker(error.line - 1, "error", makeMarker(error.reason));
}
}
function doChanges() {
timeoutID = null;
console.debug("Running linter");
runLinter();
state.sketch = editor.getValue();
if (state.useLocalStorage) localStorage.setItem("sketch", state.sketch);
state.evalSketch();
}
let timeoutID = null;
function handleChange(e) {
if (e.doc.history.lastOrigin === "setValue") {
// Don't want to use a timeout if the change came from setValue
doChanges();
return;
}
// To prevent constant sketch eval when typing, restart a timeout whenever
// there are changes
if (timeoutID) clearTimeout(timeoutID);
timeoutID = setTimeout(doChanges, state.editorTimeout);
}
}