athena-ui-js 2.4.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.
@@ -0,0 +1,286 @@
1
+ //Code display of Athena UI: highlightCode (a <pre><code> with tokens), generateCodeBlock (label, copy button) and createDiffView.
2
+ //Everything is built with el(): text stays text, nothing is parsed as markup.
3
+ //LICENCE: MIT
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+
6
+ import { asHandle, cx, el, resolveElement } from "../../core/dom.js";
7
+ import { translate } from "../../core/i18n.js";
8
+ import { getLanguage, tokenize } from "../../core/codeLanguages.js";
9
+ import { diffLines, hunksOf, splitLines } from "../../core/codeDiff.js";
10
+
11
+ /* ------------------TOKENS TO LINES------------------- */
12
+
13
+ /** Splits tokens at the line breaks: an array (one entry per line) of arrays of { type, text }. */
14
+ export function tokensToLines(tokens) {
15
+ const lines = [[]];
16
+ for (const token of tokens) {
17
+ const parts = token.text.split("\n");
18
+ parts.forEach((part, index) => {
19
+ if (index > 0) lines.push([]);
20
+ if (part) lines.at(-1).push({ type: token.type, text: part });
21
+ });
22
+ }
23
+ return lines;
24
+ }
25
+
26
+ /** The nodes of one line: text nodes and <span class="tok-..."> (a span has one class and one text node). */
27
+ export function lineNodes(tokens) {
28
+ return tokens.map(token => (token.type ? el("span", { class: `tok-${token.type}` }, token.text) : document.createTextNode(token.text)));
29
+ }
30
+
31
+ /** "3", 3 or "5-8" (and a list of them) to a Set of line numbers. */
32
+ function lineSet(spec) {
33
+ const set = new Set();
34
+ for (const item of [].concat(spec ?? [])) {
35
+ const range = /^(\d+)\s*-\s*(\d+)$/.exec(String(item));
36
+ if (range) for (let n = Number(range[1]); n <= Math.min(Number(range[2]), Number(range[1]) + 100000); n++) set.add(n);
37
+ else if (Number.isInteger(Number(item))) set.add(Number(item));
38
+ }
39
+ return set;
40
+ }
41
+
42
+ const digitsOf = count => Math.min(7, Math.max(1, String(count).length));
43
+
44
+ /**
45
+ * Writes the highlighted lines of a text into a <code> element (replacing what is there). The editor uses it too.
46
+ *
47
+ * @param {HTMLElement} code
48
+ * @param {string} text
49
+ * @param {string|object} [language] a name or alias ("js"), or a language object; unknown: plain text
50
+ * @param {object} [options]
51
+ * @param {Array<number|string>} [options.highlightLines] line numbers (1-based) or ranges ("5-8") that get a background
52
+ * @returns {number} the number of lines
53
+ */
54
+ export function renderCode(code, text, language, { highlightLines } = {}) {
55
+ const marked = lineSet(highlightLines);
56
+ const lines = tokensToLines(tokenize(text, language));
57
+ const fragment = document.createDocumentFragment();
58
+ lines.forEach((tokens, index) => {
59
+ const line = el("span", { class: cx("code-line", marked.has(index + 1) && "is-highlighted") });
60
+ line.append(...lineNodes(tokens));
61
+ fragment.append(line);
62
+ });
63
+ code.replaceChildren(fragment);
64
+ return lines.length;
65
+ }
66
+
67
+ /**
68
+ * Highlights read-only code: a `<pre class="athena-code"><code>` element.
69
+ *
70
+ * @param {string} text
71
+ * @param {string|object} [language] "js", "ts", "json", "html", "css", "sql", "sh", "yaml", "c#", "python" or a language you registered
72
+ * @param {object} [options]
73
+ * @param {boolean} [options.lineNumbers=false]
74
+ * @param {Array<number|string>} [options.highlightLines]
75
+ * @param {boolean} [options.wrap=false] long lines wrap instead of scrolling
76
+ * @param {string} [options.label] accessible name of the code
77
+ * @returns {HTMLPreElement}
78
+ */
79
+ export function highlightCode(text, language, { lineNumbers = false, highlightLines, wrap = false, label } = {}) {
80
+ const found = getLanguage(language);
81
+ const code = el("code", { class: found ? `language-${found.name}` : "" });
82
+ const count = renderCode(code, text, language, { highlightLines });
83
+ return el("pre", {
84
+ class: cx("athena-code", lineNumbers && "has-line-numbers", lineNumbers && `code-digits-${digitsOf(count)}`, wrap && "code-wrap"),
85
+ attrs: { tabindex: "0", ...(label ? { "aria-label": label, role: "region" } : {}) }
86
+ }, code);
87
+ }
88
+
89
+ /* ------------------CODE BLOCK------------------- */
90
+
91
+ async function copyText(text) {
92
+ try {
93
+ await navigator.clipboard.writeText(text);
94
+ return true;
95
+ } catch {
96
+ const area = el("textarea", { class: "athena-visually-hidden", attrs: { "aria-hidden": "true", tabindex: "-1", readonly: "" } });
97
+ area.value = text;
98
+ document.body.append(area);
99
+ area.select();
100
+ let done = false;
101
+ try {
102
+ done = document.execCommand("copy");
103
+ } catch {
104
+ done = false;
105
+ }
106
+ area.remove();
107
+ return done;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * A code block: a label with the language, a copy button and the highlighted code.
113
+ *
114
+ * @param {object} options
115
+ * @param {string|HTMLElement} [options.parent]
116
+ * @param {string} options.code
117
+ * @param {string|object} [options.language]
118
+ * @param {string} [options.title] shown in the header instead of the language
119
+ * @param {boolean} [options.lineNumbers=false]
120
+ * @param {Array<number|string>} [options.highlightLines]
121
+ * @param {boolean} [options.copy=true] the copy button
122
+ * @param {boolean} [options.wrap=false]
123
+ * @param {string} [options.id]
124
+ * @returns {{element: HTMLElement, getCode: () => string, setCode: (code: string, language?: string|object) => void, copy: () => Promise<boolean>, destroy: Function}}
125
+ */
126
+ export function generateCodeBlock({ parent, code = "", language, title, lineNumbers = false, highlightLines, copy = true, wrap = false, id } = {}) {
127
+ let text = String(code);
128
+ let current = language;
129
+ const label = () => title ?? getLanguage(current)?.label ?? getLanguage(current)?.name ?? "";
130
+ const status = el("span", { class: "athena-visually-hidden", attrs: { role: "status" } });
131
+ const name = el("span", { class: "code-block-language" }, label());
132
+ const header = el("figcaption", { class: "code-block-header" }, name);
133
+ const figure = el("figure", { class: "code-block", attrs: id ? { id } : {} }, header);
134
+ let pre = null;
135
+ let timer = 0;
136
+
137
+ const draw = () => {
138
+ const next = highlightCode(text, current, { lineNumbers, highlightLines, wrap, label: label() || undefined });
139
+ if (pre) pre.replaceWith(next);
140
+ else figure.append(next);
141
+ pre = next;
142
+ name.textContent = label();
143
+ };
144
+
145
+ const doCopy = async () => {
146
+ const done = await copyText(text);
147
+ status.textContent = translate(done ? "code.copied" : "code.copyFailed");
148
+ if (button) {
149
+ button.textContent = translate(done ? "code.copied" : "code.copyFailed");
150
+ clearTimeout(timer);
151
+ timer = setTimeout(() => { button.textContent = translate("code.copy"); status.textContent = ""; }, 1800);
152
+ }
153
+ return done;
154
+ };
155
+
156
+ let button = null;
157
+ if (copy) {
158
+ button = el("button", { class: "code-block-copy", attrs: { type: "button" } }, translate("code.copy"));
159
+ button.addEventListener("click", doCopy);
160
+ header.append(button);
161
+ }
162
+ figure.append(status);
163
+ draw();
164
+ resolveElement(parent)?.append(figure);
165
+
166
+ return asHandle({
167
+ element: figure,
168
+ getCode: () => text,
169
+ setCode(next, nextLanguage) {
170
+ text = String(next ?? "");
171
+ if (nextLanguage !== undefined) current = nextLanguage;
172
+ draw();
173
+ },
174
+ copy: doCopy,
175
+ destroy() {
176
+ clearTimeout(timer);
177
+ figure.remove();
178
+ }
179
+ });
180
+ }
181
+
182
+ /* ------------------DIFF VIEW------------------- */
183
+
184
+ /**
185
+ * A view of the difference between two texts, with highlighted code on both sides.
186
+ *
187
+ * @param {object} options
188
+ * @param {string|HTMLElement} [options.parent]
189
+ * @param {string} [options.original]
190
+ * @param {string} [options.modified]
191
+ * @param {string|object} [options.language]
192
+ * @param {"unified"|"split"} [options.mode="unified"]
193
+ * @param {number} [options.context=3] unchanged lines kept around a change (Infinity: all of them); a button shows the rest
194
+ * @param {string} [options.originalLabel]
195
+ * @param {string} [options.modifiedLabel]
196
+ * @returns {{element: HTMLElement, setTexts: (original: string, modified: string) => void, setMode: (mode: string) => void, getStats: () => {added: number, removed: number}}}
197
+ */
198
+ export function createDiffView({ parent, original = "", modified = "", language, mode = "unified", context = 3, originalLabel, modifiedLabel } = {}) {
199
+ const root = el("div", { class: "code-diff", attrs: { role: "group", "aria-label": translate("code.diff") } });
200
+ let texts = [String(original), String(modified)];
201
+ let view = mode === "split" ? "split" : "unified";
202
+ let expanded = false;
203
+ let stats = { added: 0, removed: 0 };
204
+
205
+ const mark = (symbol, word) => el("span", { class: "code-diff-mark" }, el("span", { class: "athena-visually-hidden" }, `${word} `), el("span", { attrs: { "aria-hidden": "true" } }, symbol));
206
+
207
+ const cell = (kind, tokens, symbol, word, number) => {
208
+ const line = el("span", { class: "code-line" });
209
+ if (tokens) line.append(...lineNodes(tokens));
210
+ return el("span", { class: cx("code-diff-cell", `is-${kind}`) },
211
+ el("span", { class: "code-diff-number", attrs: { "aria-hidden": "true" } }, number ?? ""), symbol ? mark(symbol, word) : el("span", { class: "code-diff-mark" }), line);
212
+ };
213
+
214
+ function draw() {
215
+ const oldLines = splitLines(texts[0]);
216
+ const newLines = splitLines(texts[1]);
217
+ const oldTokens = tokensToLines(tokenize(oldLines.join("\n"), language));
218
+ const newTokens = tokensToLines(tokenize(newLines.join("\n"), language));
219
+ const ops = diffLines(oldLines, newLines);
220
+ stats = { added: ops.filter(op => op.type === "add").length, removed: ops.filter(op => op.type === "remove").length };
221
+ const hunks = hunksOf(ops, expanded ? Infinity : context);
222
+ const body = el("div", { class: cx("code-diff-body", `is-${view}`) });
223
+ const header = el("div", { class: "code-diff-header" }, el("span", { class: "code-diff-stat is-removed" }, `−${stats.removed}`), el("span", { class: "code-diff-stat is-added" }, `+${stats.added}`));
224
+ if (view === "split") header.append(el("span", { class: "code-diff-side" }, originalLabel ?? translate("code.original")), el("span", { class: "code-diff-side" }, modifiedLabel ?? translate("code.modified")));
225
+ const tail = oldLines.length - hunks.reduce((sum, hunk) => sum + hunk.skippedBefore + hunk.ops.filter(op => op.type !== "add").length, 0);
226
+
227
+ const skipRow = count => {
228
+ const button = el("button", { class: "code-diff-skip", attrs: { type: "button" } }, translate("code.unchanged", { count }));
229
+ button.addEventListener("click", () => { expanded = true; draw(); });
230
+ return el("div", { class: "code-diff-row is-skip" }, button);
231
+ };
232
+
233
+ for (const hunk of hunks) {
234
+ if (hunk.skippedBefore) body.append(skipRow(hunk.skippedBefore));
235
+ const pending = { removed: [], added: [] };
236
+ const flush = () => {
237
+ if (view === "split") {
238
+ const rows = Math.max(pending.removed.length, pending.added.length);
239
+ for (let i = 0; i < rows; i++) {
240
+ const left = pending.removed[i];
241
+ const right = pending.added[i];
242
+ body.append(el("div", { class: "code-diff-row" },
243
+ left !== undefined ? cell("removed", oldTokens[left], "−", translate("code.removed"), left + 1) : cell("empty"),
244
+ right !== undefined ? cell("added", newTokens[right], "+", translate("code.added"), right + 1) : cell("empty")));
245
+ }
246
+ } else {
247
+ for (const index of pending.removed) body.append(el("div", { class: "code-diff-row" }, cell("removed", oldTokens[index], "−", translate("code.removed"), index + 1)));
248
+ for (const index of pending.added) body.append(el("div", { class: "code-diff-row" }, cell("added", newTokens[index], "+", translate("code.added"), index + 1)));
249
+ }
250
+ pending.removed = [];
251
+ pending.added = [];
252
+ };
253
+ for (const op of hunk.ops) {
254
+ if (op.type === "remove") pending.removed.push(op.a);
255
+ else if (op.type === "add") pending.added.push(op.b);
256
+ else {
257
+ flush();
258
+ body.append(el("div", { class: "code-diff-row" },
259
+ cell("equal", oldTokens[op.a], null, "", op.a + 1), ...(view === "split" ? [cell("equal", newTokens[op.b], null, "", op.b + 1)] : [])));
260
+ }
261
+ }
262
+ flush();
263
+ }
264
+ if (tail > 0 && hunks.length) body.append(skipRow(tail));
265
+ if (!hunks.length) body.append(el("p", { class: "code-diff-empty" }, translate("code.noChanges")));
266
+ root.replaceChildren(header, el("pre", { class: cx("athena-code", "code-diff-code"), attrs: { tabindex: "0" } }, el("code", {}, body)));
267
+ root.dataset.mode = view;
268
+ }
269
+
270
+ draw();
271
+ resolveElement(parent)?.append(root);
272
+ return asHandle({
273
+ element: root,
274
+ setTexts(a, b) {
275
+ texts = [String(a ?? ""), String(b ?? "")];
276
+ expanded = false;
277
+ draw();
278
+ },
279
+ setMode(next) {
280
+ view = next === "split" ? "split" : "unified";
281
+ draw();
282
+ },
283
+ getStats: () => ({ ...stats })
284
+ });
285
+ }
286
+