athena-ui-js 2.3.0 → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -3
- package/docs/styling.md +123 -103
- package/package.json +8 -1
- package/src/athena-ui.js +5 -1
- package/src/code.js +9 -0
- package/src/libs/config/config.js +1 -1
- package/src/libs/core/codeDiff.js +119 -0
- package/src/libs/core/codeLanguages.js +277 -0
- package/src/libs/core/i18n.js +56 -0
- package/src/libs/hephaestus/codeGenerator/codeEditor.js +1037 -0
- package/src/libs/hephaestus/codeGenerator/codeGenerator.js +286 -0
- package/src/libs/hephaestus/widgetGrid/widgetGrid.js +870 -0
- package/src/res/themes/default/style.css +471 -0
- package/src/res/themes/tokens.css +52 -0
- package/types/athena-ui.d.ts +103 -99
- package/types/code.d.ts +4 -0
- package/types/libs/config/config.d.ts +3 -3
- package/types/libs/core/codeDiff.d.ts +32 -0
- package/types/libs/core/codeLanguages.d.ts +58 -0
- package/types/libs/core/gridLayout.d.ts +45 -45
- package/types/libs/hephaestus/codeGenerator/codeEditor.d.ts +60 -0
- package/types/libs/hephaestus/codeGenerator/codeGenerator.d.ts +99 -0
- package/types/libs/hephaestus/widgetGrid/widgetGrid.d.ts +117 -117
- package/types/widgets.d.ts +2 -2
|
@@ -0,0 +1,1037 @@
|
|
|
1
|
+
//Code editor of Athena UI: a real <textarea> (native input, selection, mobile keyboards and IME keep working, screen readers read it) with the
|
|
2
|
+
//highlighted code behind it. The textarea shows nothing but the caret and the selection, the highlighted <pre> shows the text, and both sit in one scroller.
|
|
3
|
+
//LICENCE: MIT
|
|
4
|
+
//Repository: https://github.com/csabatibortoth/athena-ui
|
|
5
|
+
|
|
6
|
+
import { asHandle, cx, el, resolveElement, uid } from "../../core/dom.js";
|
|
7
|
+
import { translate } from "../../core/i18n.js";
|
|
8
|
+
import { getLanguage, tokenize } from "../../core/codeLanguages.js";
|
|
9
|
+
import { lineNodes, tokensToLines } from "./codeGenerator.js";
|
|
10
|
+
|
|
11
|
+
const HIGHLIGHTS = typeof CSS !== "undefined" && "highlights" in CSS && typeof Highlight === "function" ? CSS.highlights : null;
|
|
12
|
+
const IDENTIFIER = /[\w$]/;
|
|
13
|
+
const OPEN_TO_CLOSE = { "(": ")", "[": "]", "{": "}" };
|
|
14
|
+
const CLOSE_TO_OPEN = { ")": "(", "]": "[", "}": "{" };
|
|
15
|
+
const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A code editor.
|
|
19
|
+
*
|
|
20
|
+
* @param {object} options
|
|
21
|
+
* @param {string|HTMLElement} options.element the container
|
|
22
|
+
* @param {string} [options.value]
|
|
23
|
+
* @param {string|object} [options.language] "js", "json", ... or a language object (see registerLanguage)
|
|
24
|
+
* @param {boolean} [options.readOnly=false]
|
|
25
|
+
* @param {boolean} [options.lineNumbers=true]
|
|
26
|
+
* @param {boolean} [options.wrap=false] soft wrap
|
|
27
|
+
* @param {number} [options.tabSize=4]
|
|
28
|
+
* @param {boolean} [options.insertSpaces=true] Tab inserts spaces (false: a tab character)
|
|
29
|
+
* @param {boolean} [options.statusBar=true] line and column, and the message of a marker
|
|
30
|
+
* @param {string} [options.label] accessible name of the editor
|
|
31
|
+
* @param {number} [options.maxHighlightLength=300000] longer texts are shown without highlighting (and without line numbers) to stay fast
|
|
32
|
+
* @param {{line: number, message: string, level?: "error"|"warning"|"info"}[]} [options.markers] lint markers (lines count from 1)
|
|
33
|
+
* @param {{from: number, to: number}[]} [options.readOnlyRanges] lines (1-based, inclusive) that cannot be changed
|
|
34
|
+
* @param {(context: {value: string, position: number, line: number, lineText: string, prefix: string, explicit: boolean, language: string}) => (Array<{label: string, insert?: string, detail?: string}>|Promise<Array>)} [options.provideCompletions]
|
|
35
|
+
* @param {boolean} [options.autoComplete=true] with provideCompletions: suggest while typing (otherwise only with Ctrl+Space)
|
|
36
|
+
* @param {(value: string, reason: string) => void} [options.onChange] after every change made by typing, undo, redo, replace ... (not after setValue)
|
|
37
|
+
* @returns the handle: { element, textarea, getValue, setValue, focus, getSelection, setSelection, insertText, setLanguage, setReadOnly, setWrap, setMarkers,
|
|
38
|
+
* setReadOnlyRanges, undo, redo, canUndo, canRedo, openFind, closeFind, toggleComment, destroy }
|
|
39
|
+
*/
|
|
40
|
+
export function createCodeEditor(options = {}) {
|
|
41
|
+
const container = resolveElement(options.element);
|
|
42
|
+
if (!container) throw new TypeError("Athena UI: createCodeEditor needs an element");
|
|
43
|
+
let language = options.language;
|
|
44
|
+
let readOnly = Boolean(options.readOnly);
|
|
45
|
+
let wrap = Boolean(options.wrap);
|
|
46
|
+
const lineNumbers = options.lineNumbers !== false;
|
|
47
|
+
const tabSize = Math.min(Math.max(Math.round(options.tabSize) || 4, 1), 16);
|
|
48
|
+
const insertSpaces = options.insertSpaces !== false;
|
|
49
|
+
const maxHighlight = options.maxHighlightLength ?? 300000;
|
|
50
|
+
const indentUnit = insertSpaces ? " ".repeat(tabSize) : "\t";
|
|
51
|
+
const id = uid("code-editor");
|
|
52
|
+
let destroyed = false;
|
|
53
|
+
|
|
54
|
+
/* ---- DOM ---- */
|
|
55
|
+
|
|
56
|
+
const code = el("code", {});
|
|
57
|
+
const pre = el("pre", { class: "athena-code code-editor-highlight", attrs: { "aria-hidden": "true" } }, code);
|
|
58
|
+
const textarea = el("textarea", {
|
|
59
|
+
class: "code-editor-input",
|
|
60
|
+
attrs: {
|
|
61
|
+
spellcheck: "false", autocapitalize: "off", autocomplete: "off", autocorrect: "off", wrap: "off", "aria-label": options.label ?? translate("code.editorLabel"),
|
|
62
|
+
"aria-describedby": `${id}-hint`, "aria-multiline": "true"
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
const scroller = el("div", { class: "code-editor-scroll" }, pre, textarea);
|
|
66
|
+
const hint = el("span", { class: "athena-visually-hidden", attrs: { id: `${id}-hint` } }, translate("code.escapeHint"));
|
|
67
|
+
const position = el("span", { class: "code-editor-position" });
|
|
68
|
+
const note = el("span", { class: "code-editor-note", attrs: { role: "status", "aria-live": "polite" } });
|
|
69
|
+
const status = el("div", { class: "code-editor-status" }, position, note);
|
|
70
|
+
const root = container;
|
|
71
|
+
root.classList.add("code-editor", `code-tab-${tabSize}`);
|
|
72
|
+
root.replaceChildren(scroller, status, hint);
|
|
73
|
+
status.hidden = options.statusBar === false;
|
|
74
|
+
textarea.value = String(options.value ?? "").replace(/\r\n?/g, "\n");
|
|
75
|
+
|
|
76
|
+
/* ---- the text and its lines ---- */
|
|
77
|
+
|
|
78
|
+
let starts = [0]; // offset of the first character of every line (of the text now)
|
|
79
|
+
let nodes = []; // the span of every line
|
|
80
|
+
let lineTokens = []; // the tokens of every line, as last drawn
|
|
81
|
+
let insideAtStart = []; // does the line start inside a token that began on an earlier line (a block comment)?
|
|
82
|
+
let renderedText = ""; // the text that was drawn last
|
|
83
|
+
let renderedStarts = [0]; // and where its lines start
|
|
84
|
+
let renderedLanguage;
|
|
85
|
+
let renderTimer = 0;
|
|
86
|
+
let plain = false;
|
|
87
|
+
|
|
88
|
+
function measure() {
|
|
89
|
+
const text = textarea.value;
|
|
90
|
+
starts = [0];
|
|
91
|
+
for (let i = text.indexOf("\n"); i !== -1; i = text.indexOf("\n", i + 1)) starts.push(i + 1);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const lineIn = (table, offset) => {
|
|
95
|
+
let low = 0;
|
|
96
|
+
let high = table.length - 1;
|
|
97
|
+
while (low < high) {
|
|
98
|
+
const middle = (low + high + 1) >> 1;
|
|
99
|
+
if (table[middle] <= offset) low = middle;
|
|
100
|
+
else high = middle - 1;
|
|
101
|
+
}
|
|
102
|
+
return low;
|
|
103
|
+
};
|
|
104
|
+
const lineOf = offset => lineIn(starts, offset);
|
|
105
|
+
const lineText = index => textarea.value.slice(starts[index], index + 1 < starts.length ? starts[index + 1] - 1 : undefined);
|
|
106
|
+
|
|
107
|
+
/** The tokens of a text, line by line, and for every line whether it starts inside a token of an earlier line. */
|
|
108
|
+
function tokenLines(text) {
|
|
109
|
+
const lines = [[]];
|
|
110
|
+
const inside = [false];
|
|
111
|
+
for (const token of tokenize(text, language)) {
|
|
112
|
+
const parts = token.text.split("\n");
|
|
113
|
+
parts.forEach((part, index) => {
|
|
114
|
+
if (index > 0) {
|
|
115
|
+
lines.push([]);
|
|
116
|
+
inside.push(token.type !== null && (part.length > 0 || index < parts.length - 1));
|
|
117
|
+
}
|
|
118
|
+
if (part) lines.at(-1).push({ type: token.type, text: part });
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
return { lines, inside };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Replaces the lines [from, to) (as drawn) by new ones: the nodes and the tokens. */
|
|
125
|
+
function replaceLines(from, to, fresh) {
|
|
126
|
+
const before = nodes[to] ?? null;
|
|
127
|
+
for (let i = from; i < to; i++) nodes[i]?.remove();
|
|
128
|
+
const fragment = document.createDocumentFragment();
|
|
129
|
+
const created = fresh.lines.map(tokens => {
|
|
130
|
+
const line = el("span", { class: "code-line" });
|
|
131
|
+
line.append(...lineNodes(tokens));
|
|
132
|
+
fragment.append(line);
|
|
133
|
+
return line;
|
|
134
|
+
});
|
|
135
|
+
code.insertBefore(fragment, before);
|
|
136
|
+
const tail = { nodes: nodes.slice(to), tokens: lineTokens.slice(to), inside: insideAtStart.slice(to) };
|
|
137
|
+
nodes = [...nodes.slice(0, from), ...created, ...tail.nodes];
|
|
138
|
+
lineTokens = [...lineTokens.slice(0, from), ...fresh.lines, ...tail.tokens];
|
|
139
|
+
insideAtStart = [...insideAtStart.slice(0, from), ...fresh.inside, ...tail.inside];
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function render() {
|
|
143
|
+
clearTimeout(renderTimer);
|
|
144
|
+
renderTimer = 0;
|
|
145
|
+
const text = textarea.value;
|
|
146
|
+
measure();
|
|
147
|
+
plain = text.length > maxHighlight;
|
|
148
|
+
pre.classList.toggle("is-plain", plain);
|
|
149
|
+
pre.classList.toggle("has-line-numbers", lineNumbers && !plain);
|
|
150
|
+
pre.classList.toggle("code-wrap", wrap);
|
|
151
|
+
pre.className = pre.className.replace(/\bcode-digits-\d\b/g, "").trim();
|
|
152
|
+
pre.classList.add(`code-digits-${Math.min(7, String(starts.length).length)}`);
|
|
153
|
+
const found = getLanguage(language);
|
|
154
|
+
code.className = found ? `language-${found.name}` : "";
|
|
155
|
+
const before = { text: renderedText, starts: renderedStarts, language: renderedLanguage };
|
|
156
|
+
renderedText = text;
|
|
157
|
+
renderedStarts = starts;
|
|
158
|
+
renderedLanguage = language;
|
|
159
|
+
if (plain) {
|
|
160
|
+
nodes = [];
|
|
161
|
+
lineTokens = [];
|
|
162
|
+
insideAtStart = [];
|
|
163
|
+
renderedText = "";
|
|
164
|
+
code.replaceChildren(document.createTextNode(`${text}\n`));
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (!nodes.length || before.language !== language) {
|
|
168
|
+
// everything
|
|
169
|
+
code.replaceChildren();
|
|
170
|
+
const old = nodes.length;
|
|
171
|
+
nodes = [];
|
|
172
|
+
lineTokens = [];
|
|
173
|
+
insideAtStart = [];
|
|
174
|
+
void old;
|
|
175
|
+
replaceLines(0, 0, tokenLines(text));
|
|
176
|
+
decorate();
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
// Only the lines around the change are tokenized again: from the nearest line that does not start inside a block comment or a string
|
|
180
|
+
// before the change, to the nearest such line after it (and a comment or string that runs to the end of that part is followed further).
|
|
181
|
+
const limit = Math.min(before.text.length, text.length);
|
|
182
|
+
let head = 0;
|
|
183
|
+
while (head < limit && before.text.charCodeAt(head) === text.charCodeAt(head)) head++;
|
|
184
|
+
let tail = 0;
|
|
185
|
+
while (tail < limit - head && before.text.charCodeAt(before.text.length - 1 - tail) === text.charCodeAt(text.length - 1 - tail)) tail++;
|
|
186
|
+
const count = starts.length;
|
|
187
|
+
const delta = count - before.starts.length;
|
|
188
|
+
let first = lineOf(head);
|
|
189
|
+
while (first > 0 && insideAtStart[first]) first--;
|
|
190
|
+
let last = lineOf(text.length - tail) + 1;
|
|
191
|
+
let step = 1;
|
|
192
|
+
for (;;) {
|
|
193
|
+
while (last < count && insideAtStart[last - delta]) last++;
|
|
194
|
+
const end = last < count ? starts[last] - 1 : text.length;
|
|
195
|
+
const fresh = tokenLines(text.slice(starts[first], end));
|
|
196
|
+
const lastToken = fresh.lines.at(-1).at(-1);
|
|
197
|
+
if (last < count && lastToken && (lastToken.type === "comment" || lastToken.type === "string" || lastToken.type === "meta")) {
|
|
198
|
+
last = Math.min(count, last + step); // it may run on: look further (doubling, so a long comment does not cost much more)
|
|
199
|
+
step *= 2;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
replaceLines(first, last - delta, fresh);
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
decorate();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function scheduleRender() {
|
|
209
|
+
if (textarea.value.length <= 60000) return render();
|
|
210
|
+
if (!renderTimer) renderTimer = setTimeout(() => !destroyed && render(), 120);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/* ---- decorations: caret line, markers, locked lines ---- */
|
|
214
|
+
|
|
215
|
+
let markers = [];
|
|
216
|
+
let locked = [];
|
|
217
|
+
let currentNode = null;
|
|
218
|
+
let decorated = []; // [node, classes] of the lines that carry a marker or are locked
|
|
219
|
+
|
|
220
|
+
function decorate() {
|
|
221
|
+
if (plain) return;
|
|
222
|
+
for (const [node, classes] of decorated) node.classList.remove(...classes);
|
|
223
|
+
decorated = [];
|
|
224
|
+
const wanted = new Map();
|
|
225
|
+
const add = (index, ...classes) => wanted.set(index, [...(wanted.get(index) ?? []), ...classes]);
|
|
226
|
+
const seen = new Set();
|
|
227
|
+
for (const marker of [...markers.filter(item => item.level === "error"), ...markers.filter(item => item.level !== "error")]) {
|
|
228
|
+
if (seen.has(marker.line)) continue;
|
|
229
|
+
seen.add(marker.line);
|
|
230
|
+
add(marker.line - 1, "has-marker", `marker-${marker.level ?? "error"}`);
|
|
231
|
+
}
|
|
232
|
+
for (const range of locked) for (let line = Math.max(1, range.from); line <= Math.min(range.to, nodes.length); line++) add(line - 1, "is-locked-line");
|
|
233
|
+
for (const [index, classes] of wanted) {
|
|
234
|
+
const node = nodes[index];
|
|
235
|
+
if (!node) continue;
|
|
236
|
+
node.classList.add(...classes);
|
|
237
|
+
decorated.push([node, classes]);
|
|
238
|
+
}
|
|
239
|
+
markCurrentLine();
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function caretInfo() {
|
|
243
|
+
const offset = textarea.selectionStart;
|
|
244
|
+
const line = lineOf(offset);
|
|
245
|
+
return { offset, line, column: offset - starts[line] };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function markCurrentLine() {
|
|
249
|
+
const { line, column } = caretInfo();
|
|
250
|
+
currentNode?.classList.remove("is-current");
|
|
251
|
+
currentNode = textarea.selectionStart === textarea.selectionEnd ? (nodes[line] ?? null) : null;
|
|
252
|
+
currentNode?.classList.add("is-current");
|
|
253
|
+
position.textContent = translate("code.position", { line: line + 1, column: column + 1 });
|
|
254
|
+
const marker = markers.find(entry => entry.line === line + 1);
|
|
255
|
+
const message = marker ? translate("code.marker", { line: line + 1, message: marker.message }) : "";
|
|
256
|
+
if (note.textContent !== message) note.textContent = message;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/* ---- caret geometry, brackets, highlights ---- */
|
|
260
|
+
|
|
261
|
+
function locate(offset) {
|
|
262
|
+
const index = lineOf(offset);
|
|
263
|
+
let remaining = offset - starts[index];
|
|
264
|
+
const line = nodes[index];
|
|
265
|
+
if (!line) return null;
|
|
266
|
+
for (const child of line.childNodes) {
|
|
267
|
+
const text = child.nodeType === Node.TEXT_NODE ? child : child.firstChild;
|
|
268
|
+
const length = text?.length ?? 0;
|
|
269
|
+
if (remaining <= length) return { node: text ?? line, offset: remaining };
|
|
270
|
+
remaining -= length;
|
|
271
|
+
}
|
|
272
|
+
return { node: line, offset: line.childNodes.length };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function rangeBetween(from, to) {
|
|
276
|
+
const a = locate(from);
|
|
277
|
+
const b = locate(to);
|
|
278
|
+
if (!a || !b) return null;
|
|
279
|
+
const range = new Range();
|
|
280
|
+
range.setStart(a.node, a.offset);
|
|
281
|
+
range.setEnd(b.node, b.offset);
|
|
282
|
+
return range;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function caretRect(offset = textarea.selectionEnd) {
|
|
286
|
+
const range = rangeBetween(offset, offset);
|
|
287
|
+
let rect = range?.getBoundingClientRect();
|
|
288
|
+
if (!rect || (!rect.width && !rect.height)) rect = nodes[lineOf(offset)]?.getBoundingClientRect() ?? scroller.getBoundingClientRect();
|
|
289
|
+
return rect;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function revealCaret() {
|
|
293
|
+
if (plain) return;
|
|
294
|
+
const rect = caretRect();
|
|
295
|
+
const box = scroller.getBoundingClientRect();
|
|
296
|
+
const gutter = lineNumbers ? 64 : 12;
|
|
297
|
+
if (rect.bottom > box.bottom - 4) scroller.scrollTop += rect.bottom - box.bottom + 8;
|
|
298
|
+
else if (rect.top < box.top + 4) scroller.scrollTop -= box.top - rect.top + 8;
|
|
299
|
+
if (rect.right > box.right - 12) scroller.scrollLeft += rect.right - box.right + 24;
|
|
300
|
+
else if (rect.left < box.left + gutter) scroller.scrollLeft -= box.left + gutter - rect.left + 24;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function setHighlight(name, ranges) {
|
|
304
|
+
if (!HIGHLIGHTS) return;
|
|
305
|
+
if (ranges.length) HIGHLIGHTS.set(name, new Highlight(...ranges));
|
|
306
|
+
else HIGHLIGHTS.delete(name);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function matchBracket() {
|
|
310
|
+
const text = textarea.value;
|
|
311
|
+
const caret = textarea.selectionStart;
|
|
312
|
+
if (plain || caret !== textarea.selectionEnd) return setHighlight("athena-code-bracket", []);
|
|
313
|
+
for (const at of [caret - 1, caret]) {
|
|
314
|
+
const char = text[at];
|
|
315
|
+
const forward = OPEN_TO_CLOSE[char];
|
|
316
|
+
const backward = CLOSE_TO_OPEN[char];
|
|
317
|
+
if (!forward && !backward) continue;
|
|
318
|
+
let depth = 0;
|
|
319
|
+
for (let i = at; forward ? i < text.length : i >= 0; i += forward ? 1 : -1) {
|
|
320
|
+
if (text[i] === char) depth++;
|
|
321
|
+
else if (text[i] === (forward ?? backward)) depth--;
|
|
322
|
+
if (depth === 0) {
|
|
323
|
+
const ranges = [rangeBetween(at, at + 1), rangeBetween(i, i + 1)].filter(Boolean);
|
|
324
|
+
return setHighlight("athena-code-bracket", ranges);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
setHighlight("athena-code-bracket", []);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/* ---- history ---- */
|
|
332
|
+
|
|
333
|
+
const history = [];
|
|
334
|
+
let historyIndex = -1;
|
|
335
|
+
let lastType = null;
|
|
336
|
+
let lastTime = 0;
|
|
337
|
+
|
|
338
|
+
function snapshot() {
|
|
339
|
+
return { value: textarea.value, start: textarea.selectionStart, end: textarea.selectionEnd };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function remember(type) {
|
|
343
|
+
const now = performance.now();
|
|
344
|
+
const joins = (type === "insertText" || type === "deleteContentBackward" || type === "deleteContentForward") && type === lastType && now - lastTime < 700 && historyIndex === history.length - 1 && historyIndex > 0;
|
|
345
|
+
if (joins) history[historyIndex] = snapshot();
|
|
346
|
+
else {
|
|
347
|
+
history.length = historyIndex + 1;
|
|
348
|
+
history.push(snapshot());
|
|
349
|
+
if (history.length > 300) history.shift();
|
|
350
|
+
historyIndex = history.length - 1;
|
|
351
|
+
}
|
|
352
|
+
lastType = type;
|
|
353
|
+
lastTime = now;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function restore(entry, reason) {
|
|
357
|
+
textarea.value = entry.value;
|
|
358
|
+
textarea.setSelectionRange(entry.start, entry.end);
|
|
359
|
+
lastType = null;
|
|
360
|
+
afterChange(reason, { remembered: true });
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function undo() {
|
|
364
|
+
if (readOnly || historyIndex <= 0) return false;
|
|
365
|
+
historyIndex--;
|
|
366
|
+
restore(history[historyIndex], "undo");
|
|
367
|
+
return true;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function redo() {
|
|
371
|
+
if (readOnly || historyIndex >= history.length - 1) return false;
|
|
372
|
+
historyIndex++;
|
|
373
|
+
restore(history[historyIndex], "redo");
|
|
374
|
+
return true;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/* ---- changes ---- */
|
|
378
|
+
|
|
379
|
+
function lockedSpans() {
|
|
380
|
+
return locked.map(range => {
|
|
381
|
+
const first = Math.max(0, range.from - 1);
|
|
382
|
+
const last = Math.min(starts.length - 1, range.to - 1);
|
|
383
|
+
return first < starts.length ? [starts[first], starts[last] + lineText(last).length] : null;
|
|
384
|
+
}).filter(Boolean);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Would a change of [from, to) touch a locked line? An insertion is from === to. */
|
|
388
|
+
const blocked = (from, to) => lockedSpans().some(([start, end]) => from <= end && to >= start);
|
|
389
|
+
|
|
390
|
+
function afterChange(reason, { remembered = false, native = false } = {}) {
|
|
391
|
+
scheduleRender();
|
|
392
|
+
if (!remembered) remember(reason);
|
|
393
|
+
measure();
|
|
394
|
+
decorate();
|
|
395
|
+
refreshFind();
|
|
396
|
+
matchBracket();
|
|
397
|
+
// The browser scrolls to the caret by itself while the person types; our own edits (Tab, Enter, replace, undo ...) do it here, once per frame
|
|
398
|
+
// (measuring the caret makes the browser lay the whole text out, which is the expensive part of a big file)
|
|
399
|
+
if (!native) requestAnimationFrame(() => !destroyed && revealCaret());
|
|
400
|
+
options.onChange?.(textarea.value, reason);
|
|
401
|
+
maybeComplete(reason);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** Replaces [from, to) by text and puts the selection where it says (default: after the text). */
|
|
405
|
+
function applyEdit(from, to, text, { select = [from + text.length, from + text.length], reason = "edit" } = {}) {
|
|
406
|
+
if (readOnly || blocked(from, to)) return false;
|
|
407
|
+
const value = textarea.value;
|
|
408
|
+
textarea.value = value.slice(0, from) + text + value.slice(to);
|
|
409
|
+
textarea.setSelectionRange(select[0], select[1]);
|
|
410
|
+
afterChange(reason);
|
|
411
|
+
return true;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/* ---- editing helpers ---- */
|
|
415
|
+
|
|
416
|
+
const selectedLines = () => {
|
|
417
|
+
measure();
|
|
418
|
+
const first = lineOf(textarea.selectionStart);
|
|
419
|
+
let last = lineOf(textarea.selectionEnd);
|
|
420
|
+
if (last > first && textarea.selectionEnd === starts[last]) last--; // a selection that ends at the start of a line does not include it
|
|
421
|
+
return [first, last];
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
/** Applies f to every line of the selection (one edit, one undo step); keeps the selection on the same text. */
|
|
425
|
+
function changeLines(change, reason) {
|
|
426
|
+
const [first, last] = selectedLines();
|
|
427
|
+
const from = starts[first];
|
|
428
|
+
const to = starts[last] + lineText(last).length;
|
|
429
|
+
const original = textarea.value.slice(from, to).split("\n");
|
|
430
|
+
const changed = original.map((line, index) => change(line, index));
|
|
431
|
+
const text = changed.join("\n");
|
|
432
|
+
if (text === original.join("\n")) return false;
|
|
433
|
+
// where a position of the old block is in the new one: the line moved by the lengths of the lines before it, the column by what this line grew
|
|
434
|
+
const mapped = offset => {
|
|
435
|
+
const index = lineOf(offset) - first;
|
|
436
|
+
const column = offset - starts[index + first];
|
|
437
|
+
const before = changed.slice(0, index).reduce((sum, line) => sum + line.length + 1, 0);
|
|
438
|
+
const grown = changed[index].length - original[index].length;
|
|
439
|
+
return from + before + (column === 0 ? 0 : Math.max(0, Math.min(column + grown, changed[index].length)));
|
|
440
|
+
};
|
|
441
|
+
const start = mapped(textarea.selectionStart);
|
|
442
|
+
const end = mapped(textarea.selectionEnd);
|
|
443
|
+
return applyEdit(from, to, text, { select: [start, end], reason });
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function indentSelection() {
|
|
447
|
+
const [first, last] = selectedLines();
|
|
448
|
+
if (first === last && textarea.selectionStart === textarea.selectionEnd) {
|
|
449
|
+
const column = textarea.selectionStart - starts[first];
|
|
450
|
+
const text = insertSpaces ? " ".repeat(tabSize - (column % tabSize)) : "\t";
|
|
451
|
+
return applyEdit(textarea.selectionStart, textarea.selectionEnd, text, { reason: "indent" });
|
|
452
|
+
}
|
|
453
|
+
return changeLines(line => (line.length ? indentUnit + line : line), "indent");
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function outdentSelection() {
|
|
457
|
+
const strip = line => (line.startsWith("\t") ? line.slice(1) : line.replace(new RegExp(`^ {1,${tabSize}}`), ""));
|
|
458
|
+
return changeLines(strip, "outdent");
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function toggleComment() {
|
|
462
|
+
const found = getLanguage(language);
|
|
463
|
+
if (readOnly || !found) return false;
|
|
464
|
+
if (found.lineComment) {
|
|
465
|
+
const marker = found.lineComment;
|
|
466
|
+
const [first, last] = selectedLines();
|
|
467
|
+
const lines = [];
|
|
468
|
+
for (let i = first; i <= last; i++) lines.push(lineText(i));
|
|
469
|
+
const filled = lines.filter(line => line.trim());
|
|
470
|
+
const commented = filled.length > 0 && filled.every(line => line.trimStart().startsWith(marker));
|
|
471
|
+
const indent = Math.min(...filled.map(line => line.match(/^[ \t]*/)[0].length), Infinity);
|
|
472
|
+
return changeLines(line => {
|
|
473
|
+
if (!line.trim()) return line;
|
|
474
|
+
if (commented) return line.replace(new RegExp(`^([ \\t]*)${escapeRegExp(marker)} ?`), "$1");
|
|
475
|
+
return `${line.slice(0, indent)}${marker} ${line.slice(indent)}`;
|
|
476
|
+
}, "comment");
|
|
477
|
+
}
|
|
478
|
+
if (found.blockComment) {
|
|
479
|
+
const [open, close] = found.blockComment;
|
|
480
|
+
const [first, last] = selectedLines();
|
|
481
|
+
const from = starts[first];
|
|
482
|
+
const to = starts[last] + lineText(last).length;
|
|
483
|
+
const body = textarea.value.slice(from, to);
|
|
484
|
+
const text = body.trimStart().startsWith(open) && body.trimEnd().endsWith(close)
|
|
485
|
+
? body.replace(open, "").replace(new RegExp(`${escapeRegExp(close)}(?![\\s\\S]*${escapeRegExp(close)})`), "").replace(/^ /, "").replace(/ $/, "")
|
|
486
|
+
: `${open} ${body} ${close}`;
|
|
487
|
+
return applyEdit(from, to, text, { select: [from, from + text.length], reason: "comment" });
|
|
488
|
+
}
|
|
489
|
+
return false;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function moveLines(direction) {
|
|
493
|
+
const [first, last] = selectedLines();
|
|
494
|
+
if ((direction < 0 && first === 0) || (direction > 0 && last === starts.length - 1)) return false;
|
|
495
|
+
const block = [];
|
|
496
|
+
for (let i = first; i <= last; i++) block.push(lineText(i));
|
|
497
|
+
const neighbour = lineText(direction < 0 ? first - 1 : last + 1);
|
|
498
|
+
const from = starts[direction < 0 ? first - 1 : first];
|
|
499
|
+
const to = starts[direction < 0 ? last : last + 1] + lineText(direction < 0 ? last : last + 1).length;
|
|
500
|
+
const text = direction < 0 ? [...block, neighbour].join("\n") : [neighbour, ...block].join("\n");
|
|
501
|
+
const shift = direction < 0 ? -(neighbour.length + 1) : neighbour.length + 1;
|
|
502
|
+
return applyEdit(from, to, text, { select: [textarea.selectionStart + shift, textarea.selectionEnd + shift], reason: "move-lines" });
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function newLine() {
|
|
506
|
+
const caret = textarea.selectionStart;
|
|
507
|
+
const end = textarea.selectionEnd;
|
|
508
|
+
measure();
|
|
509
|
+
const index = lineOf(caret);
|
|
510
|
+
const before = textarea.value.slice(starts[index], caret);
|
|
511
|
+
const after = textarea.value.slice(end, end + 1);
|
|
512
|
+
const indent = before.match(/^[ \t]*/)[0];
|
|
513
|
+
const found = getLanguage(language);
|
|
514
|
+
const deeper = found?.indentAfter?.test(before) ? indentUnit : "";
|
|
515
|
+
const closes = Boolean(after) && OPEN_TO_CLOSE[before.trimEnd().slice(-1)] === after;
|
|
516
|
+
if (closes) {
|
|
517
|
+
const middle = `\n${indent}${deeper || indentUnit}`;
|
|
518
|
+
return applyEdit(caret, end, `${middle}\n${indent}`, { select: [caret + middle.length, caret + middle.length], reason: "newline" });
|
|
519
|
+
}
|
|
520
|
+
const text = `\n${indent}${deeper}`;
|
|
521
|
+
return applyEdit(caret, end, text, { reason: "newline" });
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** Typing an opening bracket or quote closes it; typing a closing one that is already there steps over it. Returns true when it handled the character. */
|
|
525
|
+
function typeCharacter(char) {
|
|
526
|
+
const found = getLanguage(language);
|
|
527
|
+
const pairs = found?.pairs ?? [];
|
|
528
|
+
const start = textarea.selectionStart;
|
|
529
|
+
const end = textarea.selectionEnd;
|
|
530
|
+
const text = textarea.value;
|
|
531
|
+
const pair = pairs.find(item => item[0] === char);
|
|
532
|
+
const closing = pairs.find(item => item[1] === char);
|
|
533
|
+
if (start === end && closing && text[start] === char) {
|
|
534
|
+
textarea.setSelectionRange(start + 1, start + 1);
|
|
535
|
+
afterSelection();
|
|
536
|
+
return true;
|
|
537
|
+
}
|
|
538
|
+
if (!pair) return false;
|
|
539
|
+
if (start !== end) return applyEdit(start, end, `${pair[0]}${text.slice(start, end)}${pair[1]}`, { select: [start + 1, end + 1], reason: "surround" });
|
|
540
|
+
const next = text[start] ?? "";
|
|
541
|
+
const previous = text[start - 1] ?? "";
|
|
542
|
+
const quote = pair[0] === pair[1];
|
|
543
|
+
if (quote && (IDENTIFIER.test(previous) || IDENTIFIER.test(next))) return false;
|
|
544
|
+
if (next && !/[\s)\]}>,;:]/.test(next)) return false;
|
|
545
|
+
return applyEdit(start, end, pair, { select: [start + 1, start + 1], reason: "pair" });
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function deletePair() {
|
|
549
|
+
const found = getLanguage(language);
|
|
550
|
+
const start = textarea.selectionStart;
|
|
551
|
+
if (start !== textarea.selectionEnd || !found?.pairs) return false;
|
|
552
|
+
const pair = textarea.value.slice(start - 1, start + 1);
|
|
553
|
+
if (!found.pairs.includes(pair)) return false;
|
|
554
|
+
return applyEdit(start - 1, start + 1, "", { reason: "deleteContentBackward" });
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/* ---- find and replace ---- */
|
|
558
|
+
|
|
559
|
+
const find = { open: false, query: "", replacement: "", matchCase: false, regex: false, matches: [], current: -1, invalid: false };
|
|
560
|
+
let findBar = null;
|
|
561
|
+
let findInput;
|
|
562
|
+
let replaceInput;
|
|
563
|
+
let findCount;
|
|
564
|
+
|
|
565
|
+
function computeMatches() {
|
|
566
|
+
find.matches = [];
|
|
567
|
+
find.invalid = false;
|
|
568
|
+
if (!find.query) return;
|
|
569
|
+
let expression;
|
|
570
|
+
try {
|
|
571
|
+
expression = new RegExp(find.regex ? find.query : escapeRegExp(find.query), `gm${find.matchCase ? "" : "i"}`);
|
|
572
|
+
} catch {
|
|
573
|
+
find.invalid = true;
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
const text = textarea.value;
|
|
577
|
+
for (let match = expression.exec(text); match && find.matches.length < 10000; match = expression.exec(text)) {
|
|
578
|
+
if (match[0] === "") {
|
|
579
|
+
expression.lastIndex++;
|
|
580
|
+
continue;
|
|
581
|
+
}
|
|
582
|
+
find.matches.push({ start: match.index, end: match.index + match[0].length, text: match[0] });
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function paintFind() {
|
|
587
|
+
if (!findBar) return;
|
|
588
|
+
const selected = find.matches.findIndex(match => match.start === textarea.selectionStart && match.end === textarea.selectionEnd);
|
|
589
|
+
if (selected !== -1) find.current = selected;
|
|
590
|
+
findCount.textContent = find.invalid ? translate("code.invalidPattern") : !find.query ? "" : !find.matches.length ? translate("code.noMatches") : translate("code.matches", { current: Math.max(find.current, -1) + 1 || "–", total: find.matches.length });
|
|
591
|
+
findInput.setAttribute("aria-invalid", String(find.invalid));
|
|
592
|
+
if (!plain) {
|
|
593
|
+
setHighlight("athena-code-find", find.matches.slice(0, 2000).map(match => rangeBetween(match.start, match.end)).filter(Boolean));
|
|
594
|
+
setHighlight("athena-code-find-current", find.current >= 0 && find.matches[find.current] ? [rangeBetween(find.matches[find.current].start, find.matches[find.current].end)].filter(Boolean) : []);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
function refreshFind() {
|
|
599
|
+
if (!find.open) return;
|
|
600
|
+
computeMatches();
|
|
601
|
+
find.current = Math.min(find.current, find.matches.length - 1);
|
|
602
|
+
paintFind();
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function goToMatch(step) {
|
|
606
|
+
computeMatches();
|
|
607
|
+
if (!find.matches.length) return paintFind();
|
|
608
|
+
const from = step > 0 ? textarea.selectionEnd : textarea.selectionStart;
|
|
609
|
+
let index = step > 0 ? find.matches.findIndex(match => match.start >= from) : find.matches.findLastIndex(match => match.end <= from);
|
|
610
|
+
if (index === -1) index = step > 0 ? 0 : find.matches.length - 1;
|
|
611
|
+
find.current = index;
|
|
612
|
+
const match = find.matches[index];
|
|
613
|
+
textarea.setSelectionRange(match.start, match.end);
|
|
614
|
+
markCurrentLine();
|
|
615
|
+
revealCaret();
|
|
616
|
+
paintFind();
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function replaceCurrent() {
|
|
620
|
+
if (readOnly) return;
|
|
621
|
+
computeMatches();
|
|
622
|
+
const selected = find.matches.find(match => match.start === textarea.selectionStart && match.end === textarea.selectionEnd);
|
|
623
|
+
if (!selected) return goToMatch(1);
|
|
624
|
+
const text = find.regex ? selected.text.replace(new RegExp(find.query, find.matchCase ? "" : "i"), find.replacement) : find.replacement;
|
|
625
|
+
if (applyEdit(selected.start, selected.end, text, { reason: "replace" })) goToMatch(1);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
function replaceAll() {
|
|
629
|
+
if (readOnly) return;
|
|
630
|
+
computeMatches();
|
|
631
|
+
if (!find.matches.length) return;
|
|
632
|
+
const value = textarea.value;
|
|
633
|
+
let result = "";
|
|
634
|
+
let at = 0;
|
|
635
|
+
for (const match of find.matches) {
|
|
636
|
+
if (blocked(match.start, match.end)) continue;
|
|
637
|
+
result += value.slice(at, match.start) + (find.regex ? match.text.replace(new RegExp(find.query, find.matchCase ? "" : "i"), find.replacement) : find.replacement);
|
|
638
|
+
at = match.end;
|
|
639
|
+
}
|
|
640
|
+
result += value.slice(at);
|
|
641
|
+
if (result !== value) applyEdit(0, value.length, result, { select: [0, 0], reason: "replace-all" });
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function buildFindBar() {
|
|
645
|
+
const field = (name, label, onInput) => {
|
|
646
|
+
const input = el("input", { class: "code-find-input", attrs: { type: "text", "aria-label": label, placeholder: label, spellcheck: "false", autocomplete: "off", name } });
|
|
647
|
+
input.addEventListener("input", () => onInput(input.value));
|
|
648
|
+
return input;
|
|
649
|
+
};
|
|
650
|
+
const button = (text, label, handler, pressed) => {
|
|
651
|
+
const node = el("button", { class: "code-find-button", attrs: { type: "button", "aria-label": label, title: label, ...(pressed === undefined ? {} : { "aria-pressed": String(pressed) }) } }, text);
|
|
652
|
+
node.addEventListener("click", handler);
|
|
653
|
+
return node;
|
|
654
|
+
};
|
|
655
|
+
findInput = field("find", translate("code.find"), value => { find.query = value; find.current = -1; computeMatches(); goToMatch(1); });
|
|
656
|
+
replaceInput = field("replace", translate("code.replaceWith"), value => { find.replacement = value; });
|
|
657
|
+
findCount = el("span", { class: "code-find-count", attrs: { role: "status", "aria-live": "polite" } });
|
|
658
|
+
const toggle = (key, node) => () => { find[key] = !find[key]; node.setAttribute("aria-pressed", String(find[key])); refreshFind(); goToMatch(1); };
|
|
659
|
+
const caseButton = button("Aa", translate("code.matchCase"), () => {}, false);
|
|
660
|
+
caseButton.addEventListener("click", toggle("matchCase", caseButton));
|
|
661
|
+
const regexButton = button(".*", translate("code.useRegex"), () => {}, false);
|
|
662
|
+
regexButton.addEventListener("click", toggle("regex", regexButton));
|
|
663
|
+
const row = el("div", { class: "code-find-row" }, findInput, button("↑", translate("code.previous"), () => goToMatch(-1)), button("↓", translate("code.next"), () => goToMatch(1)), caseButton, regexButton, findCount, button("✕", translate("code.close"), closeFind));
|
|
664
|
+
const replaceRow = el("div", { class: "code-find-row code-find-replace" }, replaceInput, button(translate("code.replaceOne"), translate("code.replaceOne"), replaceCurrent), button(translate("code.replaceAll"), translate("code.replaceAll"), replaceAll));
|
|
665
|
+
replaceRow.hidden = readOnly;
|
|
666
|
+
findBar = el("div", { class: "code-find", attrs: { role: "search" } }, row, replaceRow);
|
|
667
|
+
findBar.addEventListener("keydown", event => {
|
|
668
|
+
if (event.key === "Escape") {
|
|
669
|
+
event.preventDefault();
|
|
670
|
+
event.stopPropagation();
|
|
671
|
+
closeFind();
|
|
672
|
+
} else if (event.key === "Enter" && event.target === findInput) {
|
|
673
|
+
event.preventDefault();
|
|
674
|
+
goToMatch(event.shiftKey ? -1 : 1);
|
|
675
|
+
} else if (event.key === "Enter" && event.target === replaceInput) {
|
|
676
|
+
event.preventDefault();
|
|
677
|
+
replaceCurrent();
|
|
678
|
+
}
|
|
679
|
+
});
|
|
680
|
+
root.insertBefore(findBar, scroller);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function openFind({ replace = false } = {}) {
|
|
684
|
+
if (!findBar) buildFindBar();
|
|
685
|
+
find.open = true;
|
|
686
|
+
findBar.hidden = false;
|
|
687
|
+
findBar.querySelector(".code-find-replace").hidden = readOnly;
|
|
688
|
+
const selection = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
|
|
689
|
+
if (selection && !selection.includes("\n")) {
|
|
690
|
+
findInput.value = selection;
|
|
691
|
+
find.query = selection;
|
|
692
|
+
}
|
|
693
|
+
computeMatches();
|
|
694
|
+
paintFind();
|
|
695
|
+
(replace && !readOnly ? replaceInput : findInput).focus();
|
|
696
|
+
findInput.select?.();
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
function closeFind() {
|
|
700
|
+
if (!findBar) return;
|
|
701
|
+
find.open = false;
|
|
702
|
+
findBar.hidden = true;
|
|
703
|
+
setHighlight("athena-code-find", []);
|
|
704
|
+
setHighlight("athena-code-find-current", []);
|
|
705
|
+
textarea.focus();
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/* ---- completions ---- */
|
|
709
|
+
|
|
710
|
+
let list = null;
|
|
711
|
+
let items = [];
|
|
712
|
+
let activeItem = -1;
|
|
713
|
+
let completionToken = 0;
|
|
714
|
+
let completionTimer = 0;
|
|
715
|
+
|
|
716
|
+
function prefixAt(offset) {
|
|
717
|
+
let from = offset;
|
|
718
|
+
while (from > 0 && IDENTIFIER.test(textarea.value[from - 1])) from--;
|
|
719
|
+
return { from, prefix: textarea.value.slice(from, offset) };
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function closeCompletions() {
|
|
723
|
+
completionToken++;
|
|
724
|
+
clearTimeout(completionTimer);
|
|
725
|
+
if (list) list.hidden = true;
|
|
726
|
+
items = [];
|
|
727
|
+
activeItem = -1;
|
|
728
|
+
textarea.removeAttribute("aria-activedescendant");
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function paintCompletions() {
|
|
732
|
+
if (!list) {
|
|
733
|
+
list = el("ul", { class: "code-completions", attrs: { role: "listbox", id: `${id}-list`, "aria-label": translate("code.suggestions") } });
|
|
734
|
+
list.addEventListener("mousedown", event => event.preventDefault()); // the textarea keeps the focus
|
|
735
|
+
list.addEventListener("click", event => {
|
|
736
|
+
const option = event.target.closest("[role=option]");
|
|
737
|
+
if (option) acceptCompletion([...list.children].indexOf(option));
|
|
738
|
+
});
|
|
739
|
+
root.append(list);
|
|
740
|
+
textarea.setAttribute("aria-controls", list.id);
|
|
741
|
+
textarea.setAttribute("aria-autocomplete", "list");
|
|
742
|
+
}
|
|
743
|
+
list.replaceChildren(...items.map((item, index) => el("li", { class: cx("code-completion", index === activeItem && "is-active"), attrs: { role: "option", id: `${id}-option-${index}`, "aria-selected": String(index === activeItem) } },
|
|
744
|
+
el("span", { class: "code-completion-label" }, item.label), item.detail ? el("span", { class: "code-completion-detail" }, item.detail) : "")));
|
|
745
|
+
list.hidden = !items.length;
|
|
746
|
+
if (activeItem >= 0) textarea.setAttribute("aria-activedescendant", `${id}-option-${activeItem}`);
|
|
747
|
+
else textarea.removeAttribute("aria-activedescendant");
|
|
748
|
+
if (items.length) {
|
|
749
|
+
// under the caret, inside the editor: two CSS variables (set through the CSSOM, which a strict Content-Security-Policy allows)
|
|
750
|
+
const rect = caretRect();
|
|
751
|
+
const box = root.getBoundingClientRect();
|
|
752
|
+
list.style.setProperty("--code-completion-top", `${Math.round(rect.bottom - box.top + 2)}px`);
|
|
753
|
+
list.style.setProperty("--code-completion-left", `${Math.max(0, Math.round(rect.left - box.left))}px`);
|
|
754
|
+
list.children[activeItem]?.scrollIntoView?.({ block: "nearest" });
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
async function showCompletions(explicit) {
|
|
759
|
+
if (!options.provideCompletions || readOnly || destroyed) return;
|
|
760
|
+
const token = ++completionToken;
|
|
761
|
+
const offset = textarea.selectionStart;
|
|
762
|
+
if (offset !== textarea.selectionEnd) return closeCompletions();
|
|
763
|
+
const { prefix } = prefixAt(offset);
|
|
764
|
+
if (!explicit && !prefix) return closeCompletions();
|
|
765
|
+
const line = lineOf(offset);
|
|
766
|
+
let result;
|
|
767
|
+
try {
|
|
768
|
+
result = await options.provideCompletions({ value: textarea.value, position: offset, line: line + 1, lineText: lineText(line), prefix, explicit, language: getLanguage(language)?.name ?? "" });
|
|
769
|
+
} catch (error) {
|
|
770
|
+
console.error("Athena UI: provideCompletions failed", error);
|
|
771
|
+
return closeCompletions();
|
|
772
|
+
}
|
|
773
|
+
if (token !== completionToken || destroyed) return;
|
|
774
|
+
items = (Array.isArray(result) ? result : []).filter(item => item && typeof item.label === "string").slice(0, 50);
|
|
775
|
+
activeItem = items.length ? 0 : -1;
|
|
776
|
+
paintCompletions();
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
function maybeComplete(reason) {
|
|
780
|
+
if (!options.provideCompletions || options.autoComplete === false) return;
|
|
781
|
+
if (reason !== "insertText" && reason !== "deleteContentBackward") return closeCompletions();
|
|
782
|
+
clearTimeout(completionTimer);
|
|
783
|
+
completionTimer = setTimeout(() => showCompletions(false), 120);
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
function acceptCompletion(index = activeItem) {
|
|
787
|
+
const item = items[index];
|
|
788
|
+
if (!item) return false;
|
|
789
|
+
const offset = textarea.selectionStart;
|
|
790
|
+
const { from } = prefixAt(offset);
|
|
791
|
+
closeCompletions();
|
|
792
|
+
return applyEdit(from, offset, item.insert ?? item.label, { reason: "completion" });
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/* ---- events ---- */
|
|
796
|
+
|
|
797
|
+
let escaped = false;
|
|
798
|
+
const mod = event => event.ctrlKey || event.metaKey;
|
|
799
|
+
|
|
800
|
+
function onKeyDown(event) {
|
|
801
|
+
if (event.isComposing) return;
|
|
802
|
+
if (list && !list.hidden && items.length) {
|
|
803
|
+
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
804
|
+
event.preventDefault();
|
|
805
|
+
activeItem = (activeItem + (event.key === "ArrowDown" ? 1 : -1) + items.length) % items.length;
|
|
806
|
+
return paintCompletions();
|
|
807
|
+
}
|
|
808
|
+
if (event.key === "Enter" || event.key === "Tab") {
|
|
809
|
+
event.preventDefault();
|
|
810
|
+
return void acceptCompletion();
|
|
811
|
+
}
|
|
812
|
+
if (event.key === "Escape") {
|
|
813
|
+
event.preventDefault();
|
|
814
|
+
event.stopPropagation();
|
|
815
|
+
return closeCompletions();
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
if (event.key === "Escape") {
|
|
819
|
+
if (find.open) {
|
|
820
|
+
event.preventDefault();
|
|
821
|
+
return closeFind();
|
|
822
|
+
}
|
|
823
|
+
escaped = true;
|
|
824
|
+
note.textContent = translate("code.tabLeaves");
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
if (event.key === "Tab" && !mod(event) && !event.altKey) {
|
|
828
|
+
if (escaped) {
|
|
829
|
+
escaped = false;
|
|
830
|
+
return; // the browser moves the focus
|
|
831
|
+
}
|
|
832
|
+
event.preventDefault();
|
|
833
|
+
if (!readOnly) (event.shiftKey ? outdentSelection() : indentSelection());
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
escaped = false;
|
|
837
|
+
if (mod(event) && !event.altKey) {
|
|
838
|
+
const key = event.key.toLowerCase();
|
|
839
|
+
if (key === "z") {
|
|
840
|
+
event.preventDefault();
|
|
841
|
+
return void (event.shiftKey ? redo() : undo());
|
|
842
|
+
}
|
|
843
|
+
if (key === "y") {
|
|
844
|
+
event.preventDefault();
|
|
845
|
+
return void redo();
|
|
846
|
+
}
|
|
847
|
+
if (key === "/" || key === "÷") {
|
|
848
|
+
event.preventDefault();
|
|
849
|
+
return void toggleComment();
|
|
850
|
+
}
|
|
851
|
+
if (key === "f" || key === "h") {
|
|
852
|
+
event.preventDefault();
|
|
853
|
+
return openFind({ replace: key === "h" });
|
|
854
|
+
}
|
|
855
|
+
if (key === " ") {
|
|
856
|
+
event.preventDefault();
|
|
857
|
+
return void showCompletions(true);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
if (event.altKey && !mod(event) && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
|
|
861
|
+
event.preventDefault();
|
|
862
|
+
return void moveLines(event.key === "ArrowUp" ? -1 : 1);
|
|
863
|
+
}
|
|
864
|
+
if (event.key === "Enter" && !mod(event) && !event.altKey && !event.shiftKey) {
|
|
865
|
+
event.preventDefault();
|
|
866
|
+
if (!readOnly) newLine();
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
function onBeforeInput(event) {
|
|
871
|
+
if (event.isComposing) return;
|
|
872
|
+
const type = event.inputType;
|
|
873
|
+
if (type === "historyUndo" || type === "historyRedo") {
|
|
874
|
+
event.preventDefault();
|
|
875
|
+
return void (type === "historyUndo" ? undo() : redo());
|
|
876
|
+
}
|
|
877
|
+
if (readOnly) return;
|
|
878
|
+
if (type === "insertLineBreak" || type === "insertParagraph") {
|
|
879
|
+
event.preventDefault();
|
|
880
|
+
return void newLine();
|
|
881
|
+
}
|
|
882
|
+
const start = textarea.selectionStart;
|
|
883
|
+
const end = textarea.selectionEnd;
|
|
884
|
+
let from = start;
|
|
885
|
+
let to = end;
|
|
886
|
+
if (start === end) {
|
|
887
|
+
if (type === "deleteContentBackward") from = Math.max(0, start - 1);
|
|
888
|
+
else if (type === "deleteContentForward") to = Math.min(textarea.value.length, start + 1);
|
|
889
|
+
else if (/^delete/.test(type)) {
|
|
890
|
+
measure();
|
|
891
|
+
from = starts[lineOf(start)];
|
|
892
|
+
to = from + lineText(lineOf(start)).length + 1;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
if (blocked(from, to)) {
|
|
896
|
+
event.preventDefault();
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
if (type === "insertText" && event.data?.length === 1 && typeCharacter(event.data)) return void event.preventDefault();
|
|
900
|
+
if (type === "deleteContentBackward" && deletePair()) event.preventDefault();
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
function onInput(event) {
|
|
904
|
+
if (event.inputType === "historyUndo" || event.inputType === "historyRedo") return;
|
|
905
|
+
afterChange(event.inputType ?? "input", { native: true });
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
function afterSelection() {
|
|
909
|
+
if (destroyed) return;
|
|
910
|
+
markCurrentLine();
|
|
911
|
+
matchBracket();
|
|
912
|
+
if (find.open) paintFind();
|
|
913
|
+
const offset = textarea.selectionStart;
|
|
914
|
+
if (list && !list.hidden && (offset !== textarea.selectionEnd || (!prefixAt(offset).prefix && !items.length))) closeCompletions();
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
const onPointer = () => requestAnimationFrame(afterSelection);
|
|
918
|
+
const onSelectionChange = () => {
|
|
919
|
+
if (document.activeElement === textarea) afterSelection();
|
|
920
|
+
};
|
|
921
|
+
const onFocus = () => {
|
|
922
|
+
escaped = false;
|
|
923
|
+
afterSelection();
|
|
924
|
+
};
|
|
925
|
+
const onBlur = () => {
|
|
926
|
+
escaped = false;
|
|
927
|
+
setHighlight("athena-code-bracket", []);
|
|
928
|
+
setTimeout(() => !destroyed && document.activeElement !== textarea && !list?.contains(document.activeElement) && closeCompletions(), 0);
|
|
929
|
+
};
|
|
930
|
+
const onRootClick = event => {
|
|
931
|
+
// a click on the empty part under the text puts the caret at the end
|
|
932
|
+
if (event.target === scroller && !readOnly) {
|
|
933
|
+
textarea.focus();
|
|
934
|
+
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
|
|
935
|
+
afterSelection();
|
|
936
|
+
}
|
|
937
|
+
};
|
|
938
|
+
|
|
939
|
+
textarea.addEventListener("keydown", onKeyDown);
|
|
940
|
+
textarea.addEventListener("beforeinput", onBeforeInput);
|
|
941
|
+
textarea.addEventListener("input", onInput);
|
|
942
|
+
textarea.addEventListener("keyup", onPointer);
|
|
943
|
+
textarea.addEventListener("pointerup", onPointer);
|
|
944
|
+
textarea.addEventListener("focus", onFocus);
|
|
945
|
+
textarea.addEventListener("blur", onBlur);
|
|
946
|
+
scroller.addEventListener("click", onRootClick);
|
|
947
|
+
document.addEventListener("selectionchange", onSelectionChange);
|
|
948
|
+
|
|
949
|
+
/* ---- start and the handle ---- */
|
|
950
|
+
|
|
951
|
+
function applyModes() {
|
|
952
|
+
root.classList.toggle("is-readonly", readOnly);
|
|
953
|
+
root.classList.toggle("code-wrap", wrap);
|
|
954
|
+
textarea.readOnly = readOnly;
|
|
955
|
+
textarea.setAttribute("wrap", wrap ? "soft" : "off");
|
|
956
|
+
textarea.setAttribute("aria-readonly", String(readOnly));
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
applyModes();
|
|
960
|
+
markers = (options.markers ?? []).map(marker => ({ ...marker }));
|
|
961
|
+
locked = (options.readOnlyRanges ?? []).map(range => ({ ...range }));
|
|
962
|
+
render();
|
|
963
|
+
remember("initial");
|
|
964
|
+
|
|
965
|
+
const handle = asHandle({
|
|
966
|
+
element: root,
|
|
967
|
+
textarea,
|
|
968
|
+
getValue: () => textarea.value,
|
|
969
|
+
setValue(value) {
|
|
970
|
+
textarea.value = String(value ?? "").replace(/\r\n?/g, "\n");
|
|
971
|
+
textarea.setSelectionRange(0, 0);
|
|
972
|
+
history.length = 0;
|
|
973
|
+
historyIndex = -1;
|
|
974
|
+
render();
|
|
975
|
+
remember("initial");
|
|
976
|
+
refreshFind();
|
|
977
|
+
matchBracket();
|
|
978
|
+
return handle;
|
|
979
|
+
},
|
|
980
|
+
focus: () => textarea.focus(),
|
|
981
|
+
getSelection() {
|
|
982
|
+
measure();
|
|
983
|
+
const { line, column } = caretInfo();
|
|
984
|
+
return { start: textarea.selectionStart, end: textarea.selectionEnd, line: line + 1, column: column + 1 };
|
|
985
|
+
},
|
|
986
|
+
setSelection(start, end = start) {
|
|
987
|
+
textarea.setSelectionRange(start, end);
|
|
988
|
+
afterSelection();
|
|
989
|
+
revealCaret();
|
|
990
|
+
},
|
|
991
|
+
insertText: text => applyEdit(textarea.selectionStart, textarea.selectionEnd, String(text), { reason: "insertText" }),
|
|
992
|
+
setLanguage(next) {
|
|
993
|
+
language = next;
|
|
994
|
+
render();
|
|
995
|
+
return handle;
|
|
996
|
+
},
|
|
997
|
+
setReadOnly(flag = true) {
|
|
998
|
+
readOnly = Boolean(flag);
|
|
999
|
+
applyModes();
|
|
1000
|
+
if (findBar) findBar.querySelector(".code-find-replace").hidden = readOnly;
|
|
1001
|
+
return handle;
|
|
1002
|
+
},
|
|
1003
|
+
setWrap(flag = true) {
|
|
1004
|
+
wrap = Boolean(flag);
|
|
1005
|
+
applyModes();
|
|
1006
|
+
render();
|
|
1007
|
+
return handle;
|
|
1008
|
+
},
|
|
1009
|
+
setMarkers(next = []) {
|
|
1010
|
+
markers = next.filter(marker => Number.isInteger(marker?.line) && typeof marker.message === "string").map(marker => ({ level: "error", ...marker }));
|
|
1011
|
+
decorate();
|
|
1012
|
+
return handle;
|
|
1013
|
+
},
|
|
1014
|
+
setReadOnlyRanges(next = []) {
|
|
1015
|
+
locked = next.map(range => ({ ...range }));
|
|
1016
|
+
decorate();
|
|
1017
|
+
return handle;
|
|
1018
|
+
},
|
|
1019
|
+
undo, redo,
|
|
1020
|
+
canUndo: () => !readOnly && historyIndex > 0,
|
|
1021
|
+
canRedo: () => !readOnly && historyIndex < history.length - 1,
|
|
1022
|
+
openFind, closeFind, toggleComment,
|
|
1023
|
+
destroy() {
|
|
1024
|
+
if (destroyed) return;
|
|
1025
|
+
destroyed = true;
|
|
1026
|
+
clearTimeout(renderTimer);
|
|
1027
|
+
clearTimeout(completionTimer);
|
|
1028
|
+
document.removeEventListener("selectionchange", onSelectionChange);
|
|
1029
|
+
setHighlight("athena-code-bracket", []);
|
|
1030
|
+
setHighlight("athena-code-find", []);
|
|
1031
|
+
setHighlight("athena-code-find-current", []);
|
|
1032
|
+
root.classList.remove("code-editor", "is-readonly", "code-wrap", `code-tab-${tabSize}`);
|
|
1033
|
+
root.replaceChildren();
|
|
1034
|
+
}
|
|
1035
|
+
}, { element: root });
|
|
1036
|
+
return handle;
|
|
1037
|
+
}
|