-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.editor.js
More file actions
279 lines (254 loc) · 9.16 KB
/
app.editor.js
File metadata and controls
279 lines (254 loc) · 9.16 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
// JSON editor layer: CodeMirror init, dirty-state, error highlight, json-nav
function setOutputDirty(isDirty) {
outputDirty = isDirty;
const formatBtn = el("formatJsonBtn");
const regenBtn = el("regenerateJsonBtn");
if (formatBtn) formatBtn.hidden = !isDirty;
if (regenBtn) regenBtn.hidden = !isDirty;
const statusEl = el("editorStatus");
if (statusEl) {
statusEl.textContent = "";
statusEl.classList.toggle("isError", false);
}
const nav = el("jsonNav");
if (nav) nav.classList.toggle("jsonNav--manual", isDirty);
// Dim left panel when user edits JSON manually
const panelLeft = document.querySelector(".panelLeft");
if (panelLeft) {
panelLeft.classList.toggle("dimmed", isDirty);
}
}
function setEditorStatus(text, { error = false } = {}) {
const node = el("editorStatus");
if (!node) return;
node.textContent = String(text || "");
node.classList.toggle("isError", !!error);
}
// Highlight the line containing a JSON parse error.
// Uses both CodeMirror API and direct DOM manipulation because
// addLineClass() alone doesn't reliably style lines in all CM scenarios.
function highlightJsonError(error, text) {
if (!cmEditor) return;
// Remove previous error marker
if (errorMarker !== null) {
cmEditor.removeLineClass(errorMarker, "background", "jsonErrorLine");
const scroller = cmEditor.getScrollerElement();
if (scroller) {
const lineWrappers = scroller.querySelectorAll(".CodeMirror-line-wrapper");
if (lineWrappers[errorMarker]) {
lineWrappers[errorMarker].classList.remove("jsonErrorLine");
const lineEl = lineWrappers[errorMarker].querySelector(".CodeMirror-line");
if (lineEl) {
lineEl.style.backgroundColor = "";
}
}
const preLines = scroller.querySelectorAll("pre.CodeMirror-line");
if (preLines[errorMarker]) {
preLines[errorMarker].classList.remove("jsonErrorLine");
preLines[errorMarker].style.backgroundColor = "";
}
}
const gutter = cmEditor.getGutterElement();
if (gutter) {
const allLineNums = gutter.querySelectorAll(".CodeMirror-linenumber");
if (allLineNums[errorMarker]) {
allLineNums[errorMarker].style.color = "";
}
}
errorMarker = null;
}
if (!error || !text) return;
// Extract error position from message (e.g., "at position 123")
const posMatch = error.message?.match(/position\s+(\d+)/i);
let targetLine = -1;
if (posMatch) {
const pos = parseInt(posMatch[1], 10);
if (pos >= 0 && pos < text.length) {
targetLine = text.substring(0, pos).split("\n").length - 1;
}
} else {
// Fallback: highlight last line
targetLine = Math.max(0, text.split("\n").length - 1);
}
if (targetLine >= 0 && targetLine < cmEditor.lineCount()) {
errorMarker = targetLine;
cmEditor.addLineClass(targetLine, "background", "jsonErrorLine");
// Direct DOM styling for reliability (CM API can be inconsistent)
requestAnimationFrame(() => {
const scroller = cmEditor.getScrollerElement();
if (scroller) {
const lineWrappers = scroller.querySelectorAll(".CodeMirror-line-wrapper");
if (lineWrappers[targetLine]) {
lineWrappers[targetLine].classList.add("jsonErrorLine");
const lineEl = lineWrappers[targetLine].querySelector(".CodeMirror-line");
if (lineEl) {
lineEl.style.backgroundColor = "rgba(255,154,162,0.12)";
}
}
const preLines = scroller.querySelectorAll("pre.CodeMirror-line");
if (preLines[targetLine]) {
preLines[targetLine].classList.add("jsonErrorLine");
preLines[targetLine].style.backgroundColor = "rgba(255,154,162,0.12)";
}
}
const gutter = cmEditor.getGutterElement();
if (gutter) {
const allLineNums = gutter.querySelectorAll(".CodeMirror-linenumber");
if (allLineNums[targetLine]) {
allLineNums[targetLine].style.color = "#ff9aa2";
}
}
});
// IMPORTANT: do not auto-scroll to the error line.
// Highlight only — the editor should not "jump" while user types.
}
}
function getOutputText() {
if (cmEditor) return cmEditor.getValue();
return el("output")?.textContent || "";
}
function setOutputText(text, { preserveView = true } = {}) {
if (cmEditor) {
const next = String(text ?? "");
if (cmEditor.getValue() === next) return;
const wrap = el("output");
if (wrap) wrap.classList.add("isUpdating");
if (preserveView) {
// replaceRange preserves scroll position (unlike setValue which resets to top)
cmEditor.operation(() => {
const lastLine = cmEditor.lastLine();
const lastCh = cmEditor.getLine(lastLine).length;
cmEditor.replaceRange(next,
{ line: cmEditor.firstLine(), ch: 0 },
{ line: lastLine, ch: lastCh },
"+setValue"
);
});
requestAnimationFrame(() => {
if (wrap) wrap.classList.remove("isUpdating");
});
} else {
cmEditor.setValue(next);
requestAnimationFrame(() => {
if (wrap) wrap.classList.remove("isUpdating");
});
}
return;
}
const node = el("output");
if (node) node.textContent = String(text ?? "");
}
// Clear undo history so first Cmd+Z doesn't revert to empty editor
function primeEditorHistoryToCurrent() {
if (editorHistoryPrimed) return;
if (!cmEditor) return;
try {
const doc = cmEditor.getDoc ? cmEditor.getDoc() : null;
if (doc && doc.clearHistory) doc.clearHistory();
else if (cmEditor.clearHistory) cmEditor.clearHistory();
editorHistoryPrimed = true;
} catch {
// If CM internals differ, do nothing
}
}
function showEditorError(text) {
const node = el("errors");
if (!node) return;
const msg = text ? String(text) : "";
node.textContent = msg;
const wasActive = node.classList.contains("isActive");
const nextActive = !!msg;
node.classList.toggle("isActive", nextActive);
// Preserve scroll position when errors panel expands/collapses
if (cmEditor && wasActive !== nextActive) {
const scroller = cmEditor.getScrollerElement ? cmEditor.getScrollerElement() : null;
const top = scroller ? scroller.scrollTop : 0;
const left = scroller ? scroller.scrollLeft : 0;
requestAnimationFrame(() => {
if (cmEditor.refresh) cmEditor.refresh();
requestAnimationFrame(() => {
if (scroller) {
scroller.scrollTop = top;
scroller.scrollLeft = left;
} else if (cmEditor.scrollTo) {
cmEditor.scrollTo(left, top);
}
});
});
}
}
function updateJsonNav() {
const host = el("jsonNav");
if (!host || !cmEditor) return;
const tagHost = host.querySelector(".jsonNavTags");
if (!tagHost) return;
const text = getOutputText() || "";
let parsed;
try {
parsed = JSON.parse(text);
} catch {
tagHost.innerHTML = "";
return;
}
const findLineByRegex = (re) => {
if (!cmEditor.getSearchCursor) return -1;
const cur = cmEditor.getSearchCursor(re, { line: 0, ch: 0 });
if (cur.findNext()) return cur.from().line;
return -1;
};
const findLineByString = (s) => {
if (!cmEditor.getSearchCursor) return -1;
const cur = cmEditor.getSearchCursor(s, { line: 0, ch: 0 });
if (cur.findNext()) return cur.from().line;
return -1;
};
const items = [];
const settingsLine = findLineByRegex(/"settings"\s*:/);
if (settingsLine >= 0) items.push({ label: "settings", line: settingsLine });
const ids = Array.isArray(parsed?.inapps) ? parsed.inapps.map((x) => String(x?.id ?? "")).filter(Boolean) : [];
ids.forEach((id) => {
const needle = `"id": "${id}"`;
const line = findLineByString(needle);
if (line >= 0) items.push({ label: `ID ${id}`, line });
});
tagHost.innerHTML = "";
if (!items.length) return;
items.forEach((it) => {
const b = document.createElement("button");
b.type = "button";
b.className = "ghost";
b.textContent = it.label;
b.addEventListener("click", (e) => {
e.preventDefault();
const line = Math.max(0, it.line);
cmEditor.focus();
cmEditor.operation(() => {
cmEditor.setCursor({ line, ch: 0 });
});
requestAnimationFrame(() => {
if (cmEditor.refresh) cmEditor.refresh();
const lineH = (cmEditor.defaultTextHeight && cmEditor.defaultTextHeight()) || 16;
const contextLines = 7;
const marginPx = Math.max(0, contextLines * lineH);
const coords = cmEditor.charCoords ? cmEditor.charCoords({ line, ch: 0 }, "local") : { top: line * 16 };
const desiredTop = Math.max(0, coords.top - marginPx);
if (cmEditor.scrollTo) cmEditor.scrollTo(null, desiredTop);
if (cmEditor.scrollIntoView) cmEditor.scrollIntoView({ line, ch: 0 }, marginPx);
requestAnimationFrame(() => {
if (cmEditor.refresh) cmEditor.refresh();
updateScrollShadows();
});
});
});
tagHost.appendChild(b);
});
}
function scheduleJsonNavUpdate() {
if (jsonNavTimer) window.clearTimeout(jsonNavTimer);
jsonNavTimer = window.setTimeout(() => {
jsonNavTimer = null;
updateJsonNav();
}, 140);
}
// Scroll edge shadows were removed from UI; kept as no-op for compatibility
function updateScrollShadows() {}