lexxy_math_symbols 0.1.0

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,1069 @@
1
+ import { renderMath } from "lexxy-math";
2
+ import { CARET, ITEMS } from "lexxy_math_symbols/catalog";
3
+ import {
4
+ DEFAULT_LOCALE,
5
+ categoryLabel,
6
+ itemKeywords,
7
+ itemLabel,
8
+ localeData,
9
+ localeOf,
10
+ t,
11
+ } from "lexxy_math_symbols/i18n";
12
+ import { FULL_SET, editorSymbolSet } from "lexxy_math_symbols/sets";
13
+ import { MATH_BLOCK_ICON } from "lexxy_math_symbols/icons";
14
+
15
+ const RECENT_KEY = "lexxy-math-symbols:recent";
16
+ const RECENT_LIMIT = 30;
17
+ const SEARCH_LIMIT = 150;
18
+ const RECENT = { key: "recent", icon: r`\circlearrowleft` };
19
+ // A set's symbols outside its categories (see sets.js).
20
+ const SELECTED = { key: "selected", icon: r`\checkmark` };
21
+
22
+ function r(strings) {
23
+ return strings.raw[0];
24
+ }
25
+
26
+ // Puts a catalog entry's LaTeX into a text input at its caret. A template's
27
+ // slot (‸, else the first empty {}) takes the selected text and the caret;
28
+ // a command never runs into the letter after it (\alpha + x → \alpha x).
29
+ export function insertLatex(input, insert) {
30
+ const { selectionStart: start, selectionEnd: end, value } = input;
31
+ const selected = value.slice(start, end);
32
+ let text = insert;
33
+ let caret;
34
+
35
+ const mark = text.indexOf(CARET);
36
+ const slot = mark >= 0 ? mark : text.indexOf("{}") >= 0 ? text.indexOf("{}") + 1 : -1;
37
+ if (mark >= 0) text = text.replace(CARET, "");
38
+ if (slot >= 0) {
39
+ text = text.slice(0, slot) + selected + text.slice(slot);
40
+ caret = slot + selected.length;
41
+ } else {
42
+ caret = text.length;
43
+ }
44
+
45
+ if (/\\[a-zA-Z]+$/.test(text) && /^[a-zA-Z]/.test(value.slice(end))) text += " ";
46
+ if (/\\[a-zA-Z]+$/.test(value.slice(0, start)) && /^[a-zA-Z]/.test(text)) {
47
+ text = ` ${text}`;
48
+ caret += 1;
49
+ }
50
+ if (slot < 0) caret = text.length;
51
+
52
+ // insertText goes through the browser's own editing, so Cmd/Ctrl+Z and
53
+ // Shift+Cmd+Z (or Ctrl+Y) undo and redo an insertion as they do typing,
54
+ // and it fires the input event that redraws lexxy-math's preview.
55
+ // setRangeText, which leaves no undo step, only where insertText fails.
56
+ input.focus();
57
+ input.setSelectionRange(start, end);
58
+ if (!document.execCommand("insertText", false, text)) {
59
+ input.setRangeText(text, start, end, "end");
60
+ input.dispatchEvent(new Event("input", { bubbles: true }));
61
+ }
62
+ input.setSelectionRange(start + caret, start + caret);
63
+ }
64
+
65
+ // The empty places a template leaves to be filled: an empty {} or [], an
66
+ // empty cell of an environment (between \begin{…}, &, \\, \end{…}), an
67
+ // empty side of \over and its kin. Each is { start, end, at }: the place
68
+ // spans start to end (blanks only), the caret goes to `at`.
69
+ const INFIX = String.raw`\\(?:over|choose|atop|brace|brack)(?![a-zA-Z])|\\above\{[^}]*\}`;
70
+ const OPENS = String.raw`\\begin\{[a-zA-Z*]+\}(?:\[[^\]]*\]|\{[^}]*\})*|(?<!\\)&=?|\\\\|(?<!\\)\{|${INFIX}`;
71
+ const CLOSES = String.raw`(?<!\\)&|\\\\|\\end\{|(?<!\\)\}|${INFIX}`;
72
+ const CELL = new RegExp(String.raw`(${OPENS})(\s*)(?=${CLOSES})|(?<!\\)(\[)(\s*)(?=\])`, "g");
73
+
74
+ export function slotsOf(value) {
75
+ const slots = new Map();
76
+ for (const match of value.matchAll(CELL)) {
77
+ const opening = match[1] ?? match[3];
78
+ const blank = match[2] ?? match[4];
79
+ const start = match.index + opening.length;
80
+ const at = blank ? start + 1 : start;
81
+ slots.set(at, { start, end: start + blank.length, at });
82
+ }
83
+ return [...slots.values()].sort((a, b) => a.at - b.at);
84
+ }
85
+
86
+ // The preview with its empty places shown: lexxy-math draws `\frac{}{}` as
87
+ // a bare line, which looks as if nothing went in. Each empty place (see
88
+ // slotsOf; not an empty [], an optional argument such as \sqrt[]{}'s index)
89
+ // gets a square in a colour of its own, which `markSlots` turns into a class.
90
+ // Inside \text{} the square needs math mode ($…$); where it breaks the formula
91
+ // (a colour's or an environment's name, a dimension) the place stays empty.
92
+ // Null where there is no empty place or the formula fails anyway: the preview
93
+ // stays lexxy-math's. Only the preview: the input's text never changes.
94
+ const SLOT_COLOR = "#0a0b0c";
95
+ const SLOT_MARK = String.raw`\textcolor{${SLOT_COLOR}}{\square}`;
96
+ const SLOT_MARKS = [SLOT_MARK, `$${SLOT_MARK}$`];
97
+
98
+ export function previewLatex(value, render = renderMath, options = {}) {
99
+ const slots = slotsOf(value).filter((slot) => value[slot.start - 1] !== "[");
100
+ if (!slots.length) return null;
101
+ // KaTeX's red for what it cannot read (a command unknown in text mode), and
102
+ // the squares it draws: an argument it ignores (\genfrac's delimiter) has none.
103
+ const read = (latex) => {
104
+ const html = render(latex, options);
105
+ if (html.includes("katex-error")) return null;
106
+ return {
107
+ failed: html.split("#cc0000").length,
108
+ shown: html.split(`color:${SLOT_COLOR}`).length - 1,
109
+ };
110
+ };
111
+ const plain = read(value);
112
+ if (!plain) return null;
113
+ const fill = (marks) => {
114
+ let text = value;
115
+ for (let at = slots.length - 1; at >= 0; at--) {
116
+ const { start, end } = slots[at];
117
+ if (marks[at]) text = `${text.slice(0, start)}${marks[at]}${text.slice(end)}`;
118
+ }
119
+ return text;
120
+ };
121
+ const fits = (marks) => {
122
+ const marked = read(fill(marks));
123
+ return marked && marked.failed <= plain.failed && marked.shown === marks.filter(Boolean).length;
124
+ };
125
+ const marks = slots.map(() => SLOT_MARK);
126
+ if (fits(marks)) return fill(marks);
127
+ // One place at a time: the first mark that keeps the formula whole and
128
+ // shows, else none.
129
+ marks.fill(null);
130
+ slots.forEach((slot, at) => {
131
+ marks[at] = SLOT_MARKS.find((mark) => {
132
+ marks[at] = mark;
133
+ return fits(marks);
134
+ });
135
+ });
136
+ return marks.some(Boolean) ? fill(marks) : null;
137
+ }
138
+
139
+ // KaTeX's squares (by their colour) become `.lexxy-math-symbols__slot`, to be
140
+ // coloured by the stylesheet; MathML reads them as an empty place.
141
+ function markSlots(preview) {
142
+ for (const element of preview.querySelectorAll(`[style*="${SLOT_COLOR}"]`)) {
143
+ element.style.removeProperty("color");
144
+ element.classList.add("lexxy-math-symbols__slot");
145
+ }
146
+ for (const element of preview.querySelectorAll(`[mathcolor="${SLOT_COLOR}"]`)) {
147
+ element.removeAttribute("mathcolor");
148
+ }
149
+ }
150
+
151
+ // Draws lexxy-math's preview again with the empty places shown, after
152
+ // lexxy-math has drawn it (its listener on the input runs first). Untouched
153
+ // where there is no empty place.
154
+ export function drawPreview(panel) {
155
+ const input = panel?.querySelector(".lexxy-math-editor__input");
156
+ const preview = panel?.querySelector(".lexxy-math-editor__preview");
157
+ if (!input || !preview) return;
158
+ const options = { displayMode: panel.dataset.mode === "block" };
159
+ const latex = previewLatex(input.value, renderMath, options);
160
+ if (!latex?.trim()) return;
161
+ preview.innerHTML = renderMath(latex.trim(), options);
162
+ markSlots(preview);
163
+ }
164
+
165
+ // The toolbar's block formula button by name, in the language's quotes.
166
+ function quotedButton(locale) {
167
+ return t("quote", { text: t("insertBlock", {}, locale) }, locale);
168
+ }
169
+
170
+ // Moves the caret to the next empty place after it (`back`: before it),
171
+ // round to the first (last) one at the end. The caret only moves, the text
172
+ // and the undo history stay as they are. False where no other place is empty.
173
+ export function moveToSlot(input, back = false) {
174
+ const next = nextSlot(input, back);
175
+ if (!next) return false;
176
+ input.setSelectionRange(next.at, next.at);
177
+ return true;
178
+ }
179
+
180
+ // The empty place moveToSlot would go to, null where there is none but the
181
+ // one the caret is in.
182
+ function nextSlot(input, back = false) {
183
+ const { selectionStart: from, selectionEnd: to, value } = input;
184
+ const slots = slotsOf(value);
185
+ const inside = (slot) => slot.start <= from && to <= slot.end;
186
+ return back
187
+ ? slots.findLast((slot) => slot.end < from && !inside(slot)) ||
188
+ slots.findLast((slot) => !inside(slot)) ||
189
+ null
190
+ : slots.find((slot) => slot.start > to && !inside(slot)) ||
191
+ slots.find((slot) => !inside(slot)) ||
192
+ null;
193
+ }
194
+
195
+ // Ctrl+] (with Shift, back): the key that moves between the empty places.
196
+ // Ctrl, not Cmd: Cmd+] is the browser's Forward on a Mac. By `key`, not
197
+ // `code`: on other layouts that physical key is something else (+ on German
198
+ // QWERTZ, where Ctrl++ zooms).
199
+ export function isSlotKey(event) {
200
+ return (
201
+ event.ctrlKey && !event.metaKey && !event.altKey && (event.key === "]" || event.key === "}")
202
+ );
203
+ }
204
+
205
+ // Inputs that already answer the slot key: one set for every palette, so two
206
+ // palettes on one input never move the caret twice.
207
+ const WATCHED = new WeakSet();
208
+
209
+ // In text style KaTeX sets a fraction's (or binomial's) parts at 70%, so
210
+ // a/b looked thin next to x² in the grid. Display style keeps them the size
211
+ // of every other symbol; \tfrac and \tbinom stay small, as that is their point.
212
+ const STACKED =
213
+ /\\(frac|dfrac|cfrac|binom|dbinom|genfrac|over|choose|atop|above|brace|brack)(?![a-zA-Z])/;
214
+ function evenSize(latex) {
215
+ return STACKED.test(latex) ? `\\displaystyle ${latex}` : latex;
216
+ }
217
+
218
+ function normalize(text) {
219
+ return text.toLowerCase().replace(/ł/g, "l").normalize("NFD").replace(/[̀-ͯ]/g, "");
220
+ }
221
+
222
+ const SPLIT = /[\s\\{}[\]^_*]+/;
223
+ // Per locale (its object, which registerLocale replaces when it changes),
224
+ // the words of each entry.
225
+ let fields = new WeakMap();
226
+
227
+ // The search keeps each entry's words (see `fieldsOf`); after an entry's
228
+ // keywords or label change, this makes it read them again.
229
+ export function forgetSearchFields() {
230
+ fields = new WeakMap();
231
+ }
232
+
233
+ // An entry's words in a locale, by what the search ranks them as: `commands`
234
+ // the words of its LaTeX and aliases (as written, and normalized), the same
235
+ // in every language; `keywords` its words in the locale, `named` the words of
236
+ // its label there (what it is called), `labels` its category's name there.
237
+ function fieldsOf(item, locale) {
238
+ const data = localeData(locale);
239
+ if (!fields.has(data)) fields.set(data, new Map());
240
+ const cache = fields.get(data);
241
+ if (!cache.has(item)) {
242
+ const raw = [item.insert.replace(CARET, ""), ...item.aliases].join(" ").split(SPLIT);
243
+ const split = (text) => normalize(text).split(SPLIT).filter(Boolean);
244
+ cache.set(item, {
245
+ raw: raw.filter(Boolean),
246
+ commands: split(raw.join(" ")),
247
+ keywords: split(itemKeywords(item, locale)),
248
+ named: split(itemLabel(item, locale)),
249
+ // By its words alone: "Ułamki, potęgi" is "ulamki" and "potegi".
250
+ labels: normalize(categoryLabel(item.category, locale))
251
+ .split(/[^\p{L}\p{N}]+/u)
252
+ .filter(Boolean),
253
+ });
254
+ }
255
+ return cache.get(item);
256
+ }
257
+
258
+ // How well one word of the query fits an entry, lower is better:
259
+ // 0 its command or alias exactly (\in, pi), 1 the same in another case (\Pi
260
+ // for pi) or a keyword exactly, 2 the start of a command or a keyword, 3 a word
261
+ // of its category's name (its start only: `partial`, see `search`); null not
262
+ // at all. A word typed with
263
+ // a backslash is looked for among the commands only. A word of the entry's
264
+ // `label` counts as a keyword. `at` is the word's place among the entry's
265
+ // keywords or in its label, whichever is earlier: the first ones say what it
266
+ // is.
267
+ function rank(item, term, locale) {
268
+ const { raw, commands, keywords, named, labels } = fieldsOf(item, locale);
269
+ const keyword = (test) => {
270
+ if (term.command) return null;
271
+ const at = [keywords.findIndex(test), named.findIndex(test)].filter((each) => each >= 0);
272
+ return at.length ? Math.min(...at) : null;
273
+ };
274
+ if (raw.includes(term.raw)) return { tier: 0, at: 0 };
275
+ if (commands.includes(term.text)) return { tier: 1, at: 0 };
276
+ let at = keyword((word) => word === term.text);
277
+ if (at !== null) return { tier: 1, at };
278
+ if (commands.some((word) => word.startsWith(term.text))) return { tier: 2, at: 0 };
279
+ at = keyword((word) => word.startsWith(term.text));
280
+ if (at !== null) return { tier: 2, at };
281
+ if (!term.command && labels.includes(term.text)) return { tier: 3, at: 0 };
282
+ if (!term.command && labels.some((word) => word.startsWith(term.text)))
283
+ return { tier: 3, at: 0, partial: true };
284
+ return null;
285
+ }
286
+
287
+ function termsOf(query) {
288
+ return query
289
+ .split(/\s+|(?=\\)/)
290
+ .map((token) => ({
291
+ command: token.startsWith("\\"),
292
+ raw: token.replace(/[\\{}[\]^_*]/g, ""),
293
+ text: normalize(token).replace(/[\\{}[\]^_*]/g, ""),
294
+ }))
295
+ .filter((term) => term.text);
296
+ }
297
+
298
+ // A Polish ending may differ from the catalog's ("strzałka", "Strzałki"):
299
+ // a longer word that finds nothing is looked for without its last letter.
300
+ function stemmed(term, locale, pool) {
301
+ if (term.text.length < 5 || pool.some((item) => rank(item, term, locale))) return term;
302
+ return { ...term, raw: term.raw.slice(0, -1), text: term.text.slice(0, -1) };
303
+ }
304
+
305
+ // An entry that is a bare character beyond ASCII (∫ for \int, ∑ for \sum):
306
+ // on a tie it comes after the commands, whatever its number of keywords.
307
+ const UNICODE = /^[^\u0000-\u007f]+$/;
308
+
309
+ // Every word of the query must fit an entry ("całka ozn" finds only
310
+ // \int_{}^{}). The best fits come first (see `rank`), then those whose
311
+ // keyword comes earlier among theirs ("potęga" is the first word of ^{}, the
312
+ // second of _{}^{}), then the entries with fewer keywords, which are about
313
+ // the word more than the others ("suma" is \sum's one word, one of \cup's
314
+ // three), then the catalog's order. An entry found only by its category's
315
+ // name ("ułamki", "sumy") is not about the word at all: there the number of
316
+ // keywords says nothing, those entries come after the others in the
317
+ // catalog's order. A bare Unicode character comes after the commands (see
318
+ // UNICODE) before the number of keywords counts. The words are those of
319
+ // `locale` (Polish by default); the commands are found in every language.
320
+ // Only the entries of `pool` (a symbol set's, in catalog order) are looked at,
321
+ // before the results are cut to SEARCH_LIMIT.
322
+ export function search(query, locale = DEFAULT_LOCALE, pool = ITEMS) {
323
+ const terms = termsOf(query).map((term) => stemmed(term, locale, pool));
324
+ if (!terms.length) return [];
325
+ const found = [];
326
+ pool.forEach((item, index) => {
327
+ let tier = 0;
328
+ let at = 0;
329
+ let byCategory = 0;
330
+ let partial = 0;
331
+ for (const term of terms) {
332
+ const fit = rank(item, term, locale);
333
+ if (!fit) return;
334
+ tier += fit.tier;
335
+ at += fit.at;
336
+ if (fit.tier === 3) byCategory = 1;
337
+ if (fit.partial) partial = 1;
338
+ }
339
+ const { keywords, named } = fieldsOf(item, locale);
340
+ const size = byCategory ? 0 : keywords.length || named.length;
341
+ const unicode = UNICODE.test(item.insert) ? 1 : 0;
342
+ found.push({ item, index, tier, at, byCategory, partial, unicode, size });
343
+ });
344
+ // Found only by the start of a word of a category's name ("nawias" in
345
+ // "Nawiasy"): kept only where nothing fits any other way.
346
+ const whole = found.some((each) => !each.partial);
347
+ return found
348
+ .filter((each) => !whole || !each.partial)
349
+ .sort(
350
+ (a, b) =>
351
+ a.tier - b.tier ||
352
+ a.at - b.at ||
353
+ a.byCategory - b.byCategory ||
354
+ a.unicode - b.unicode ||
355
+ a.size - b.size ||
356
+ a.index - b.index,
357
+ )
358
+ .slice(0, SEARCH_LIMIT)
359
+ .map(({ item }) => item);
360
+ }
361
+
362
+ // Where a set's recent list is stored: one list per preset that has a set,
363
+ // so a pupil's palette never shows what the admin's used; without a set the
364
+ // list every palette shared before there were sets.
365
+ function recentKey(set) {
366
+ return set.name === null ? RECENT_KEY : `${RECENT_KEY}:${set.name}`;
367
+ }
368
+
369
+ // The recent inserts as stored: a list of strings, whatever else the
370
+ // storage holds (another version's format, a hand edit, no storage at all).
371
+ function recentInserts(key = RECENT_KEY) {
372
+ try {
373
+ const recent = JSON.parse(localStorage.getItem(key));
374
+ return Array.isArray(recent) ? recent.filter((each) => typeof each === "string") : [];
375
+ } catch {
376
+ return [];
377
+ }
378
+ }
379
+
380
+ const BY_INSERT = new Map(ITEMS.map((item) => [item.insert, item]));
381
+
382
+ function remember(insert, key = RECENT_KEY) {
383
+ try {
384
+ const recent = [insert, ...recentInserts(key).filter((each) => each !== insert)];
385
+ localStorage.setItem(key, JSON.stringify(recent.slice(0, RECENT_LIMIT)));
386
+ } catch {
387
+ // Private mode: the palette works without a recent list.
388
+ }
389
+ }
390
+
391
+ // The help line is for someone who has not put in a symbol yet: one with a
392
+ // recent list has (the set's: a pupil who has used only the admin's palette
393
+ // on this browser still gets it). Without storage it shows until the first
394
+ // insert of the page's life.
395
+ let helped = false;
396
+
397
+ function needsHelp(set) {
398
+ return !helped && !recentInserts(recentKey(set)).length;
399
+ }
400
+
401
+ // What a screen reader says for an entry: what it is in the locale's
402
+ // language, then its LaTeX ("square root, \sqrt{}"). The words are the
403
+ // entry's label there if it has one, else its first three keywords there (the
404
+ // first keywords say what it is), else none: never another language's.
405
+ export function labelOf(item, locale = DEFAULT_LOCALE) {
406
+ const command = item.insert.replace(CARET, "").replace(/\s+/g, " ").trim();
407
+ const label = itemLabel(item, locale);
408
+ const words = (label || itemKeywords(item, locale)).split(/\s+/).filter(Boolean);
409
+ return [words.slice(0, label ? undefined : 3).join(" "), command].filter(Boolean).join(", ");
410
+ }
411
+
412
+ // Every palette's ids start with its own number, so two editors on a page
413
+ // never share one.
414
+ let palettes = 0;
415
+
416
+ // Keys that move the focus among the tabs or the tiles.
417
+ const MOVES = new Set(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"]);
418
+
419
+ // <lexxy-math-symbols>: the palette under the LaTeX input of lexxy-math's
420
+ // editor. It writes into `input`, by default the editor's textarea.
421
+ export class MathSymbolsPalette extends HTMLElement {
422
+ #buttons = new Map();
423
+ #current = null;
424
+ #input = null;
425
+ #mode = null;
426
+ #shown = [];
427
+ #stop = null;
428
+ #id = null;
429
+ #locale = null;
430
+ // The input whose caret and text the buttons above follow, and its text
431
+ // when the panel opened: Undo goes no further back than that.
432
+ #followed = null;
433
+ #opened = null;
434
+ // What it shows: the Lexxy editor's symbol set (see sets.js), read again
435
+ // at each reset; the whole catalog where there is none.
436
+ #set = FULL_SET;
437
+
438
+ connectedCallback() {
439
+ if (!this.firstChild) this.#build();
440
+ }
441
+
442
+ get input() {
443
+ return (
444
+ this.#input || this.closest("lexxy-math-editor")?.querySelector(".lexxy-math-editor__input")
445
+ );
446
+ }
447
+
448
+ set input(element) {
449
+ this.#input = element;
450
+ this.#watch();
451
+ }
452
+
453
+ // "inline" or "block": inline, the block-only entries (environments such as
454
+ // align) are shown but not inserted. By default the math editor's mode.
455
+ // The language it speaks: the nearest `lang` up from it (see localeOf),
456
+ // read again at each reset.
457
+ get locale() {
458
+ return this.#locale || localeOf(this);
459
+ }
460
+
461
+ get mode() {
462
+ return this.#mode || this.closest("lexxy-math-editor")?.dataset.mode || "block";
463
+ }
464
+
465
+ set mode(value) {
466
+ this.#mode = value;
467
+ this.#markDisabled();
468
+ }
469
+
470
+ // Back to the start each time the math editor opens: no query, the recent
471
+ // symbols if there are any, else the tab shown last (at first the set's
472
+ // first one, the basic one without a set). The set is read again: the
473
+ // editor's preset or attribute may have changed (a Turbo morph).
474
+ reset() {
475
+ this.#watch();
476
+ this.#applySet(editorSymbolSet(this.closest("lexxy-editor")));
477
+ this.#translate();
478
+ this.#search.value = "";
479
+ this.#opened = this.input?.value ?? null;
480
+ this.#help.hidden = !needsHelp(this.#set);
481
+ this.show(this.#startKey());
482
+ this.#revealTab();
483
+ this.#update();
484
+ this.#prepareInput();
485
+ }
486
+
487
+ // lexxy-math's own input, as the panel opens: a placeholder in the
488
+ // palette's language (lexxy-math's says "Type LaTeX..."), and the preview
489
+ // with its empty places shown (lexxy-math has just drawn it).
490
+ #prepareInput() {
491
+ const panel = this.closest("lexxy-math-editor");
492
+ const input = this.input;
493
+ if (!panel || !input?.matches(".lexxy-math-editor__input")) return;
494
+ input.placeholder = t("inputPlaceholder", {}, this.locale);
495
+ drawPreview(panel);
496
+ }
497
+
498
+ // The keys of the tabs the set has, in their order.
499
+ get #keys() {
500
+ return [
501
+ ...(this.#set.recent ? [RECENT.key] : []),
502
+ ...this.#set.categories.map((category) => category.key),
503
+ ...(this.#set.selected.length ? [SELECTED.key] : []),
504
+ ];
505
+ }
506
+
507
+ show(key) {
508
+ if (!this.#keys.includes(key)) key = this.#firstKey();
509
+ this.#current = key;
510
+ for (const tab of this.#tabs) {
511
+ const selected = tab.dataset.category === key;
512
+ tab.setAttribute("aria-selected", selected);
513
+ tab.tabIndex = selected ? 0 : -1;
514
+ }
515
+ this.#grid.removeAttribute("aria-label");
516
+ this.#grid.setAttribute("aria-labelledby", this.#tabId(key));
517
+ this.#heading.textContent = this.#tabLabel(key, this.locale);
518
+ let items;
519
+ if (key === RECENT.key) items = this.#recentItems();
520
+ // Listed by hand: shown even where the catalog keeps them for the search.
521
+ else if (key === SELECTED.key) items = this.#set.selected;
522
+ else {
523
+ const category = this.#set.categories.find((each) => each.key === key);
524
+ items = category.items.filter((item) => !item.searchOnly);
525
+ }
526
+ this.#render(items, key !== RECENT.key);
527
+ }
528
+
529
+ get #search() {
530
+ return this.querySelector(".lexxy-math-symbols__search");
531
+ }
532
+
533
+ get #tabs() {
534
+ return this.querySelectorAll(".lexxy-math-symbols__tab");
535
+ }
536
+
537
+ get #tabList() {
538
+ return this.querySelector(".lexxy-math-symbols__tabs");
539
+ }
540
+
541
+ get #heading() {
542
+ return this.querySelector(".lexxy-math-symbols__heading");
543
+ }
544
+
545
+ get #grid() {
546
+ return this.querySelector(".lexxy-math-symbols__grid");
547
+ }
548
+
549
+ get #help() {
550
+ return this.querySelector(".lexxy-math-symbols__help");
551
+ }
552
+
553
+ #action(name) {
554
+ return this.querySelector(`.lexxy-math-symbols__${name}`);
555
+ }
556
+
557
+ // Ctrl+] in the LaTeX input moves its caret between a template's empty
558
+ // places (see moveToSlot); every other key stays lexxy-math's and the
559
+ // browser's (Tab still leads to the palette).
560
+ #watch() {
561
+ const input = this.input;
562
+ if (input && input !== this.#followed) {
563
+ this.#followed = input;
564
+ const update = () => this.#update();
565
+ for (const type of ["input", "keyup", "click", "select", "selectionchange", "focus"]) {
566
+ input.addEventListener(type, update);
567
+ }
568
+ // After lexxy-math's own listener, added when its panel was built.
569
+ input.addEventListener("input", () => {
570
+ const panel = this.closest("lexxy-math-editor");
571
+ if (panel && input.matches(".lexxy-math-editor__input")) drawPreview(panel);
572
+ });
573
+ }
574
+ if (!input || WATCHED.has(input)) return;
575
+ WATCHED.add(input);
576
+ input.setAttribute("aria-keyshortcuts", "Control+] Control+Shift+]");
577
+ input.addEventListener("keydown", (event) => {
578
+ if (event.isComposing || !isSlotKey(event)) return;
579
+ event.preventDefault();
580
+ moveToSlot(input, event.shiftKey);
581
+ });
582
+ }
583
+
584
+ #startKey() {
585
+ if (this.#set.recent && this.#recentItems().length) return RECENT.key;
586
+ const keys = this.#keys;
587
+ return this.#current && this.#current !== RECENT.key && keys.includes(this.#current)
588
+ ? this.#current
589
+ : this.#firstKey();
590
+ }
591
+
592
+ // The set's first tab after the recent one (the recent one if it has no other).
593
+ #firstKey() {
594
+ const keys = this.#keys;
595
+ return keys.find((key) => key !== RECENT.key) || keys[0];
596
+ }
597
+
598
+ // On a touch screen the tabs are one row that scrolls sideways: the tab the
599
+ // palette picks itself (as it opens) is scrolled into the bar's view. Not
600
+ // scrollIntoView, which may move the page (iOS Safari). The bar has no
601
+ // position of its own, so it and its tabs share an offsetParent.
602
+ #revealTab() {
603
+ const bar = this.#tabList;
604
+ const tab = bar?.querySelector(".lexxy-math-symbols__tab[aria-selected='true']");
605
+ if (!tab || bar.hidden || bar.scrollWidth <= bar.clientWidth) return;
606
+ const left = tab.offsetLeft - bar.offsetLeft;
607
+ if (left < bar.scrollLeft || left + tab.offsetWidth > bar.scrollLeft + bar.clientWidth) {
608
+ bar.scrollLeft = left;
609
+ }
610
+ }
611
+
612
+ #tabLabel(key, locale) {
613
+ if (key === SELECTED.key && this.#set.label) return this.#set.label;
614
+ return categoryLabel(key, locale);
615
+ }
616
+
617
+ // Takes a new set: its tabs, its search, and the start afresh (the tab shown
618
+ // last and the grid's Tab stop were another set's). The tiles are kept.
619
+ #applySet(set) {
620
+ if (set.signature === this.#set?.signature) return;
621
+ this.#set = set;
622
+ this.#setStop(null);
623
+ this.#current = null;
624
+ this.#shown = [];
625
+ this.#buildTabs();
626
+ this.#search.hidden = !set.search;
627
+ }
628
+
629
+ #buildTabs() {
630
+ const tabs = this.#tabList;
631
+ const categories = [
632
+ ...(this.#set.recent ? [RECENT] : []),
633
+ ...this.#set.categories,
634
+ ...(this.#set.selected.length ? [SELECTED] : []),
635
+ ];
636
+ tabs.replaceChildren(
637
+ ...categories.map((category) => {
638
+ const tab = this.#button("lexxy-math-symbols__tab", category.icon);
639
+ tab.dataset.category = category.key;
640
+ tab.id = this.#tabId(category.key);
641
+ tab.tabIndex = -1;
642
+ tab.setAttribute("role", "tab");
643
+ tab.setAttribute("aria-controls", `${this.#id}-panel`);
644
+ tab.addEventListener("click", () => {
645
+ this.#search.value = "";
646
+ this.show(category.key);
647
+ });
648
+ return tab;
649
+ }),
650
+ );
651
+ // A single tab says nothing the heading does not: the bar goes (the
652
+ // stylesheet hides .lexxy-math-symbols__tabs[hidden]).
653
+ tabs.hidden = categories.length < 2;
654
+ if (this.#locale) this.#labelTabs(this.#locale);
655
+ }
656
+
657
+ #labelTabs(locale) {
658
+ for (const tab of this.#tabs) {
659
+ const label = this.#tabLabel(tab.dataset.category, locale);
660
+ tab.title = label;
661
+ tab.setAttribute("aria-label", label);
662
+ }
663
+ }
664
+
665
+ #tabId(key) {
666
+ return `${this.#id}-tab-${key}`;
667
+ }
668
+
669
+ #build() {
670
+ this.#id = `lexxy-math-symbols-${++palettes}`;
671
+ const search = Object.assign(document.createElement("input"), {
672
+ type: "search",
673
+ className: "lexxy-math-symbols__search",
674
+ autocomplete: "off",
675
+ spellcheck: false,
676
+ });
677
+ search.setAttribute("aria-controls", `${this.#id}-panel`);
678
+ search.addEventListener("input", () => this.#filter());
679
+
680
+ const tabs = document.createElement("div");
681
+ tabs.className = "lexxy-math-symbols__tabs";
682
+ tabs.setAttribute("role", "tablist");
683
+
684
+ // The tab's name, the number of results, or why an entry did not go in.
685
+ // One Tab stop among the tabs (the selected one, or the last selected
686
+ // while a search shows its results); the arrows move between them.
687
+ const heading = document.createElement("div");
688
+ heading.className = "lexxy-math-symbols__heading";
689
+ heading.setAttribute("aria-live", "polite");
690
+
691
+ const grid = document.createElement("div");
692
+ grid.className = "lexxy-math-symbols__grid";
693
+ grid.id = `${this.#id}-panel`;
694
+ grid.setAttribute("role", "tabpanel");
695
+
696
+ // A click on the palette must not take the caret out of the LaTeX input
697
+ // (the search box is the one thing here that takes focus).
698
+ this.addEventListener("mousedown", (event) => {
699
+ if (event.target !== search) event.preventDefault();
700
+ });
701
+ this.addEventListener("keydown", (event) => this.#keydown(event));
702
+
703
+ // Above the search: on a phone the keyboard covers the panel's bottom.
704
+ const actions = document.createElement("div");
705
+ actions.className = "lexxy-math-symbols__actions";
706
+ const undo = this.#actionButton("undo", () => this.#undo());
707
+ const next = this.#actionButton("next", () => {
708
+ const input = this.input;
709
+ if (!input) return;
710
+ input.focus();
711
+ moveToSlot(input);
712
+ this.#update();
713
+ });
714
+ next.setAttribute("aria-keyshortcuts", "Control+]");
715
+ const done = this.#actionButton("done", () => this.#close());
716
+ actions.append(undo, next, done);
717
+
718
+ const help = document.createElement("p");
719
+ help.className = "lexxy-math-symbols__help";
720
+
721
+ this.append(actions, help, search, tabs, heading, grid);
722
+ this.#set = null;
723
+ this.#applySet(editorSymbolSet(this.closest("lexxy-editor")));
724
+ help.hidden = !needsHelp(this.#set);
725
+ this.#translate();
726
+ this.show(this.#startKey());
727
+ this.#revealTab();
728
+ this.#update();
729
+ }
730
+
731
+ #actionButton(name, action) {
732
+ const button = document.createElement("button");
733
+ button.type = "button";
734
+ button.className = `lexxy-math-symbols__${name}`;
735
+ button.addEventListener("click", () => {
736
+ if (button.getAttribute("aria-disabled") !== "true") action();
737
+ });
738
+ return button;
739
+ }
740
+
741
+ // Undo is there while the text differs from what the panel opened with
742
+ // (the browser does not say reliably what it would undo, and before the
743
+ // panel opened its steps are another formula's or the editor's); Next
744
+ // place while an empty place other than the caret's is left.
745
+ #update() {
746
+ const input = this.input;
747
+ const undo = this.#action("undo");
748
+ const next = this.#action("next");
749
+ if (!undo || !next) return;
750
+ const changed = !!input && this.#opened !== null && input.value !== this.#opened;
751
+ if (changed) undo.removeAttribute("aria-disabled");
752
+ else undo.setAttribute("aria-disabled", "true");
753
+ next.hidden = !input || !nextSlot(input);
754
+ }
755
+
756
+ // The browser's own undo, as Cmd/Ctrl+Z in the input: insertLatex leaves
757
+ // one step per insert. No further back than the panel's opening. Chrome
758
+ // and Safari keep one undo history for the page, so a word typed in the
759
+ // search since is undone first: it is put back, and undo goes on to the
760
+ // input's step. Any other element's step stops it (Firefox keeps a history
761
+ // per field and never gets there).
762
+ #undo() {
763
+ const input = this.input;
764
+ if (!input || input.value === this.#opened) return this.#update();
765
+ const search = this.#search;
766
+ const query = search.value;
767
+ input.focus();
768
+ for (let tries = 0; tries < 20; tries++) {
769
+ const before = input.value;
770
+ const searched = search.value;
771
+ if (!document.execCommand("undo") || input.value !== before) break;
772
+ if (search.value === searched) break;
773
+ input.focus();
774
+ }
775
+ if (search.value !== query) {
776
+ search.value = query;
777
+ this.#filter();
778
+ }
779
+ input.focus();
780
+ this.#update();
781
+ }
782
+
783
+ // Done: Escape in the input, which lexxy-math takes as "store and close"
784
+ // (an empty formula it removes, as it does on Escape).
785
+ #close() {
786
+ const input = this.input;
787
+ if (!input) return;
788
+ input.dispatchEvent(
789
+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }),
790
+ );
791
+ }
792
+
793
+ // Puts the texts in the language of the moment: the editor's `lang` may
794
+ // have changed since the last time. The tiles, named in the old language,
795
+ // are made again as they are shown.
796
+ #translate() {
797
+ const locale = localeOf(this);
798
+ if (locale === this.#locale) return;
799
+ this.#locale = locale;
800
+ this.#buttons.clear();
801
+ this.#shown = [];
802
+ this.#stop = null;
803
+ for (const [name, text, title] of [
804
+ ["undo", "undo", "undoTitle"],
805
+ ["next", "nextSlot", "nextSlotTitle"],
806
+ ["done", "done", "doneTitle"],
807
+ ]) {
808
+ const button = this.#action(name);
809
+ button.textContent = t(text, {}, locale);
810
+ button.title = t(title, {}, locale);
811
+ }
812
+ this.#help.textContent = t("help", {}, locale);
813
+ this.#search.placeholder = t("searchPlaceholder", {}, locale);
814
+ this.#search.setAttribute("aria-label", t("searchLabel", {}, locale));
815
+ this.#labelTabs(locale);
816
+ }
817
+
818
+ #button(className, latex, options) {
819
+ const button = document.createElement("button");
820
+ button.type = "button";
821
+ button.className = className;
822
+ button.innerHTML = renderMath(latex, options);
823
+ // The button's aria-label names it; KaTeX's MathML would say it again.
824
+ for (const child of button.children) child.setAttribute("aria-hidden", "true");
825
+ return button;
826
+ }
827
+
828
+ // An entry's button, made once and kept: KaTeX renders each symbol only
829
+ // the first time its category (or a search) shows it.
830
+ #itemButton(item) {
831
+ if (!this.#buttons.has(item)) {
832
+ const button = this.#button("lexxy-math-symbols__item", evenSize(item.preview), {
833
+ displayMode: item.display,
834
+ });
835
+ const width = item.preview.length;
836
+ if (item.preview !== item.insert && width > 12)
837
+ button.classList.add("lexxy-math-symbols__item--wide");
838
+ if (width > 40) button.classList.add("lexxy-math-symbols__item--wider");
839
+ if (item.display) button.classList.add("lexxy-math-symbols__item--display");
840
+ button.dataset.insert = item.insert;
841
+ button.tabIndex = -1;
842
+ const locale = this.locale;
843
+ button.setAttribute("aria-label", labelOf(item, locale));
844
+ button.title = [
845
+ itemLabel(item, locale),
846
+ [item.insert.replace(CARET, ""), ...item.aliases].join(" "),
847
+ item.display ? t("blockOnly", { button: quotedButton(locale) }, locale) : "",
848
+ ]
849
+ .filter(Boolean)
850
+ .join("\n");
851
+ button.addEventListener("click", () => {
852
+ this.#setStop(item);
853
+ this.#choose(item);
854
+ });
855
+ this.#buttons.set(item, button);
856
+ }
857
+ return this.#buttons.get(item);
858
+ }
859
+
860
+ #allowed(item) {
861
+ return !item.display || this.mode === "block";
862
+ }
863
+
864
+ // Block-only entries stay visible (and focusable) inline, marked
865
+ // aria-disabled; the stylesheet dims them.
866
+ #markDisabled() {
867
+ for (const item of this.#shown) {
868
+ const button = this.#buttons.get(item);
869
+ if (this.#allowed(item)) button.removeAttribute("aria-disabled");
870
+ else button.setAttribute("aria-disabled", "true");
871
+ }
872
+ }
873
+
874
+ // The one tile the Tab key stops at in the grid: the first one each time
875
+ // the grid changes, then the one last moved to or chosen.
876
+ #setStop(item) {
877
+ if (this.#stop && this.#stop !== item) this.#buttons.get(this.#stop).tabIndex = -1;
878
+ this.#stop = item;
879
+ if (item) this.#buttons.get(item).tabIndex = 0;
880
+ }
881
+
882
+ #render(items, sorted) {
883
+ this.#setStop(null);
884
+ this.#shown = items;
885
+ if (!items.length) {
886
+ const empty = document.createElement("p");
887
+ empty.className = "lexxy-math-symbols__empty";
888
+ empty.textContent = t(sorted ? "nothingFound" : "recentEmpty", {}, this.locale);
889
+ this.#grid.replaceChildren(empty);
890
+ } else {
891
+ this.#grid.replaceChildren(...items.map((item) => this.#itemButton(item)));
892
+ this.#markDisabled();
893
+ this.#setStop(items[0]);
894
+ }
895
+ this.#grid.scrollTop = 0;
896
+ }
897
+
898
+ // Only what the set has: a list stored under its preset may hold what an
899
+ // earlier set of that preset had.
900
+ #recentItems() {
901
+ const pool = this.#set.pool === ITEMS ? null : new Set(this.#set.pool);
902
+ return recentInserts(recentKey(this.#set))
903
+ .map((insert) => BY_INSERT.get(insert))
904
+ .filter((item) => item && (!pool || pool.has(item)));
905
+ }
906
+
907
+ #filter() {
908
+ const query = this.#search.value.trim();
909
+ if (!query) return this.show(this.#current);
910
+ for (const tab of this.#tabs) {
911
+ tab.setAttribute("aria-selected", false);
912
+ }
913
+ this.#grid.removeAttribute("aria-labelledby");
914
+ this.#grid.setAttribute("aria-label", t("searchResults", {}, this.locale));
915
+ const results = search(query, this.locale, this.#set.pool);
916
+ this.#heading.textContent = t("resultCount", { count: results.length }, this.locale);
917
+ this.#render(results, true);
918
+ }
919
+
920
+ // Keys anywhere in the palette. lexxy-math closes its panel (Escape) and
921
+ // stores the formula (Escape, Ctrl/Cmd+Enter) on its textarea's keydown
922
+ // only, so those keys are handed to the textarea from here.
923
+ #keydown(event) {
924
+ if (event.isComposing) return;
925
+ const inSearch = event.target === this.#search;
926
+ if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {
927
+ this.#forward(event);
928
+ } else if (event.key === "Escape") {
929
+ if (inSearch && this.#search.value) {
930
+ event.preventDefault();
931
+ event.stopPropagation();
932
+ this.#search.value = "";
933
+ this.show(this.#current);
934
+ this.input?.focus();
935
+ } else {
936
+ this.#forward(event);
937
+ }
938
+ } else if (event.key === "Enter" && inSearch) {
939
+ event.preventDefault();
940
+ const item = this.#shown.find((each) => this.#allowed(each));
941
+ if (item) this.#choose(item);
942
+ else if (this.#shown.length) this.#sayBlockOnly();
943
+ } else if (event.key === "ArrowDown" && inSearch) {
944
+ if (this.#shown.length) {
945
+ event.preventDefault();
946
+ this.#focusItem(this.#shown[0]).focus();
947
+ }
948
+ } else if (MOVES.has(event.key) && !event.altKey && !event.metaKey) {
949
+ const target = event.target.closest?.(".lexxy-math-symbols__tab, .lexxy-math-symbols__item");
950
+ const next = target?.matches(".lexxy-math-symbols__tab")
951
+ ? this.#nextTab(target, event.key)
952
+ : target && this.#nextItem(target, event.key, event.ctrlKey);
953
+ if (next) {
954
+ event.preventDefault();
955
+ next.focus();
956
+ }
957
+ }
958
+ }
959
+
960
+ // ←/→ with wrapping, Home/End. A tab is selected as the focus reaches it
961
+ // (automatic activation): a category shows at once, KaTeX renders each
962
+ // one only the first time.
963
+ #nextTab(tab, key) {
964
+ if (key === "ArrowUp" || key === "ArrowDown") return null;
965
+ const tabs = [...this.#tabs];
966
+ const at = tabs.indexOf(tab);
967
+ const next = {
968
+ ArrowLeft: tabs[(at - 1 + tabs.length) % tabs.length],
969
+ ArrowRight: tabs[(at + 1) % tabs.length],
970
+ Home: tabs[0],
971
+ End: tabs.at(-1),
972
+ }[key];
973
+ this.#search.value = "";
974
+ this.show(next.dataset.category);
975
+ return next;
976
+ }
977
+
978
+ // ←/→ the tile before or after in reading order; ↑/↓ the tile in the row
979
+ // above or below whose middle is nearest (tiles span 1 to 3 columns, so
980
+ // the rows are read from the layout, not counted); ↑ from the first row
981
+ // goes to the search. Home/End the row's first or last tile, with Ctrl
982
+ // the grid's.
983
+ #nextItem(button, key, ctrl) {
984
+ const buttons = this.#shown.map((item) => this.#buttons.get(item));
985
+ const at = buttons.indexOf(button);
986
+ if (at < 0) return null;
987
+ if (key === "ArrowLeft") return this.#focusItem(this.#shown[at - 1]);
988
+ if (key === "ArrowRight") return this.#focusItem(this.#shown[at + 1]);
989
+ if (ctrl && key === "Home") return this.#focusItem(this.#shown[0]);
990
+ if (ctrl && key === "End") return this.#focusItem(this.#shown.at(-1));
991
+
992
+ const rows = [];
993
+ let top = -Infinity;
994
+ for (const each of buttons) {
995
+ const box = each.getBoundingClientRect();
996
+ if (box.top > top + 1) rows.push([]);
997
+ top = Math.max(top, box.top);
998
+ rows.at(-1).push({ button: each, middle: box.left + box.width / 2 });
999
+ }
1000
+ const row = rows.findIndex((tiles) => tiles.some((tile) => tile.button === button));
1001
+ if (key === "Home") return this.#focusButton(rows[row][0].button);
1002
+ if (key === "End") return this.#focusButton(rows[row].at(-1).button);
1003
+
1004
+ const other = rows[row + (key === "ArrowDown" ? 1 : -1)];
1005
+ if (!other) return key === "ArrowUp" && !this.#search.hidden ? this.#search : null;
1006
+ const box = button.getBoundingClientRect();
1007
+ const middle = box.left + box.width / 2;
1008
+ const nearest = other.reduce((best, tile) =>
1009
+ Math.abs(tile.middle - middle) < Math.abs(best.middle - middle) ? tile : best,
1010
+ );
1011
+ return this.#focusButton(nearest.button);
1012
+ }
1013
+
1014
+ // Makes an entry's tile the grid's Tab stop and returns it, to be focused.
1015
+ #focusItem(item) {
1016
+ if (!item) return null;
1017
+ this.#setStop(item);
1018
+ return this.#buttons.get(item);
1019
+ }
1020
+
1021
+ #focusButton(button) {
1022
+ return this.#focusItem(this.#shown.find((item) => this.#buttons.get(item) === button));
1023
+ }
1024
+
1025
+ #forward(event) {
1026
+ const input = this.input;
1027
+ if (!input) return;
1028
+ event.preventDefault();
1029
+ event.stopPropagation();
1030
+ const { key, ctrlKey, metaKey, shiftKey, altKey } = event;
1031
+ input.dispatchEvent(
1032
+ new KeyboardEvent("keydown", {
1033
+ key,
1034
+ ctrlKey,
1035
+ metaKey,
1036
+ shiftKey,
1037
+ altKey,
1038
+ bubbles: true,
1039
+ cancelable: true,
1040
+ }),
1041
+ );
1042
+ }
1043
+
1044
+ // Why a block-only entry did not go in, in the heading (read out as it
1045
+ // changes): with the toolbar's block formula button drawn where the text
1046
+ // names it, so it can be found on the toolbar. Read as the button's name.
1047
+ #sayBlockOnly() {
1048
+ const locale = this.locale;
1049
+ const [before, after] = t("blockOnly", {}, locale).split("{button}");
1050
+ if (after === undefined) return (this.#heading.textContent = before);
1051
+ const icon = document.createElement("span");
1052
+ icon.className = "lexxy-math-symbols__button-icon";
1053
+ icon.setAttribute("role", "img");
1054
+ icon.setAttribute("aria-label", quotedButton(locale));
1055
+ icon.innerHTML = MATH_BLOCK_ICON;
1056
+ this.#heading.replaceChildren(before, icon, after);
1057
+ }
1058
+
1059
+ #choose(item) {
1060
+ if (!this.#allowed(item)) return this.#sayBlockOnly();
1061
+ const input = this.input;
1062
+ if (!input) return;
1063
+ insertLatex(input, item.insert);
1064
+ remember(item.insert, recentKey(this.#set));
1065
+ helped = true;
1066
+ this.#help.hidden = true;
1067
+ this.#update();
1068
+ }
1069
+ }