trebol 0.1.0 → 0.1.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.
Files changed (106) hide show
  1. package/README.md +8 -2
  2. package/dist/cli.js +55 -20
  3. package/dist/lib/core/access.d.ts +10 -0
  4. package/dist/lib/core/access.js +210 -0
  5. package/dist/lib/core/base.d.ts +4 -0
  6. package/dist/lib/core/base.js +50 -0
  7. package/dist/lib/core/bitset.d.ts +9 -0
  8. package/dist/lib/core/bitset.js +75 -0
  9. package/dist/lib/core/boot.d.ts +18 -0
  10. package/dist/lib/core/boot.js +72 -0
  11. package/dist/lib/core/compare.d.ts +9 -0
  12. package/dist/lib/core/compare.js +156 -0
  13. package/dist/lib/core/ctx.d.ts +36 -0
  14. package/dist/lib/core/ctx.js +251 -0
  15. package/dist/lib/core/dec.d.ts +28 -0
  16. package/dist/lib/core/dec.js +158 -0
  17. package/dist/lib/core/errors.d.ts +15 -0
  18. package/dist/lib/core/errors.js +44 -0
  19. package/dist/lib/core/escapes.d.ts +14 -0
  20. package/dist/lib/core/escapes.js +80 -0
  21. package/dist/lib/core/eval.d.ts +220 -0
  22. package/dist/lib/core/eval.js +666 -0
  23. package/dist/lib/core/func.d.ts +64 -0
  24. package/dist/lib/core/func.js +129 -0
  25. package/dist/lib/core/hash.d.ts +5 -0
  26. package/dist/lib/core/hash.js +155 -0
  27. package/dist/lib/core/index.d.ts +18 -0
  28. package/dist/lib/core/index.js +20 -0
  29. package/dist/lib/core/int64.d.ts +22 -0
  30. package/dist/lib/core/int64.js +113 -0
  31. package/dist/lib/core/kinds.d.ts +67 -0
  32. package/dist/lib/core/kinds.js +134 -0
  33. package/dist/lib/core/lexer.d.ts +13 -0
  34. package/dist/lib/core/lexer.js +702 -0
  35. package/dist/lib/core/mezz.d.ts +1 -0
  36. package/dist/lib/core/mezz.js +360 -0
  37. package/dist/lib/core/mold.d.ts +20 -0
  38. package/dist/lib/core/mold.js +434 -0
  39. package/dist/lib/core/natives/control.d.ts +1 -0
  40. package/dist/lib/core/natives/control.js +374 -0
  41. package/dist/lib/core/natives/csv.d.ts +15 -0
  42. package/dist/lib/core/natives/csv.js +315 -0
  43. package/dist/lib/core/natives/data.d.ts +11 -0
  44. package/dist/lib/core/natives/data.js +367 -0
  45. package/dist/lib/core/natives/define.d.ts +17 -0
  46. package/dist/lib/core/natives/define.js +47 -0
  47. package/dist/lib/core/natives/encode.d.ts +3 -0
  48. package/dist/lib/core/natives/encode.js +187 -0
  49. package/dist/lib/core/natives/json.d.ts +5 -0
  50. package/dist/lib/core/natives/json.js +273 -0
  51. package/dist/lib/core/natives/math.d.ts +3 -0
  52. package/dist/lib/core/natives/math.js +500 -0
  53. package/dist/lib/core/natives/parse.d.ts +1 -0
  54. package/dist/lib/core/natives/parse.js +600 -0
  55. package/dist/lib/core/natives/series.d.ts +4 -0
  56. package/dist/lib/core/natives/series.js +509 -0
  57. package/dist/lib/core/natives/text.d.ts +1 -0
  58. package/dist/lib/core/natives/text.js +484 -0
  59. package/dist/lib/core/natives/xml.d.ts +9 -0
  60. package/dist/lib/core/natives/xml.js +242 -0
  61. package/dist/lib/core/series.d.ts +26 -0
  62. package/dist/lib/core/series.js +73 -0
  63. package/dist/lib/core/symbols.d.ts +9 -0
  64. package/dist/lib/core/symbols.js +44 -0
  65. package/dist/lib/core/values.d.ts +206 -0
  66. package/dist/lib/core/values.js +223 -0
  67. package/dist/lib/host/browser.d.ts +4 -0
  68. package/dist/lib/host/browser.js +4081 -0
  69. package/dist/lib/host/chart.d.ts +26 -0
  70. package/dist/lib/host/chart.js +158 -0
  71. package/dist/lib/host/compress.d.ts +1 -0
  72. package/dist/lib/host/compress.js +37 -0
  73. package/dist/lib/host/draw.d.ts +31 -0
  74. package/dist/lib/host/draw.js +348 -0
  75. package/dist/lib/host/icons.d.ts +3 -0
  76. package/dist/lib/host/icons.js +97 -0
  77. package/dist/lib/host/index.d.ts +38 -0
  78. package/dist/lib/host/index.js +190 -0
  79. package/dist/lib/host/locale.d.ts +40 -0
  80. package/dist/lib/host/locale.js +241 -0
  81. package/dist/lib/host/markdown.d.ts +28 -0
  82. package/dist/lib/host/markdown.js +151 -0
  83. package/dist/lib/host/modules.d.ts +10 -0
  84. package/dist/lib/host/modules.js +262 -0
  85. package/dist/lib/host/natives.d.ts +6 -0
  86. package/dist/lib/host/natives.js +98 -0
  87. package/dist/lib/host/net.d.ts +12 -0
  88. package/dist/lib/host/net.js +541 -0
  89. package/dist/lib/host/page.d.ts +9 -0
  90. package/dist/lib/host/page.js +55 -0
  91. package/dist/lib/host/rows.d.ts +15 -0
  92. package/dist/lib/host/rows.js +80 -0
  93. package/dist/lib/host/scheduler.d.ts +45 -0
  94. package/dist/lib/host/scheduler.js +173 -0
  95. package/dist/lib/host/theme.d.ts +58 -0
  96. package/dist/lib/host/theme.js +1462 -0
  97. package/dist/lib/ui/i18n.trb +111 -0
  98. package/dist/lib/ui/ui.trb +1237 -0
  99. package/dist/trebol.js +123 -56
  100. package/package.json +17 -5
  101. package/src/host/browser.ts +274 -33
  102. package/src/host/index.ts +2 -2
  103. package/src/host/modules.ts +8 -1
  104. package/src/host/theme.ts +63 -4
  105. package/src/ui/i18n.trb +4 -0
  106. package/src/ui/ui.trb +48 -15
@@ -0,0 +1,4081 @@
1
+ // The browser host: boots Trebol in a page, renders faces to the DOM and
2
+ // turns DOM events into tasks.
3
+ //
4
+ // A page needs only:
5
+ //
6
+ // <script type="module">import 'trebol/browser';</script>
7
+ // <script type="text/trebol" src="app.trb"></script>
8
+ //
9
+ // (`trebol dev` resolves `trebol/browser` to this file.)
10
+ //
11
+ // There is one DOM node per face and no virtual DOM. Setting a field of a
12
+ // mounted face marks it dirty (see `ctxSet` in the core); after every round
13
+ // of scheduler slices the host copies the fields of the dirty faces to their
14
+ // nodes, so `total/text: "42"` shows up without any explicit refresh.
15
+ // Changing a series in place (`append f/text "x"`) does not mark the face:
16
+ // set the field again to repaint it.
17
+ import { logic, K, NONE, TRUE, FALSE, native, value, string, form, money, decToNumber, decFromNumber, ctxFind, intern, spell, text, canon, blockOf, wordOf, char, compare, UNSET, throwError, } from "../core/index.js";
18
+ import { mapAt, startHost, startUi, runSource, report, shown, translate, uiText, activeLanguage, editLocal, readLocal, readDate, weekStart, fileSize, LOCAL_KINDS } from "./index.js";
19
+ import { spawn, taskResult, handleOf } from "./scheduler.js";
20
+ import { themeCss, DEFAULT_THEME, LOOKS, THEME_WORDS } from "./theme.js";
21
+ import { iconNode } from "./icons.js";
22
+ import { parseMd, printMd, safeHref } from "./markdown.js";
23
+ import { fileHandle } from "./net.js";
24
+ import { drawSvg } from "./draw.js";
25
+ import { rowField, groupRow, sortGroups } from "./rows.js";
26
+ import { chartSvg, SERIES_COLORS, pieColor } from "./chart.js";
27
+ // --- reading faces -----------------------------------------------------------------
28
+ function get(face, name) {
29
+ const i = ctxFind(face.ctx, intern(name));
30
+ return i < 0 ? NONE : face.ctx.vals[i];
31
+ }
32
+ function str(face, name) {
33
+ const v = get(face, name);
34
+ if (v.t === K.None)
35
+ return null;
36
+ // a text per language, or a word of the dictionary: in the active language
37
+ if (v.t === K.Map || ((name === 'text' || name === 'hint') && v.t === K.Word))
38
+ return translate(v, host.rt);
39
+ return form(v);
40
+ }
41
+ /** What a choice or radio option is worth: itself, or the `value` of a map #(value: .. text: ..). */
42
+ function optionValue(o) {
43
+ const v = o.t === K.Map ? mapAt(o, 'value') : null;
44
+ return form(v ?? o);
45
+ }
46
+ /** What a choice or radio option shows, in the active language. */
47
+ function optionText(o) {
48
+ const t = o.t === K.Map ? mapAt(o, 'text') : null;
49
+ return t !== null ? translate(t, host.rt) : optionValue(o);
50
+ }
51
+ /** The options of a choice or radio as written: options and groups, a title followed by a block. */
52
+ function entriesOf(face) {
53
+ const opts = get(face, 'options');
54
+ if (opts.t !== K.Block)
55
+ return [];
56
+ const data = opts.s.data.slice(opts.i);
57
+ const out = [];
58
+ for (let i = 0; i < data.length; i++) {
59
+ const next = data[i + 1];
60
+ if (next !== undefined && next.t === K.Block && data[i].t !== K.Block) {
61
+ out.push({ title: data[i], options: next.s.data.slice(next.i) });
62
+ i++;
63
+ }
64
+ else if (data[i].t !== K.Block)
65
+ out.push(data[i]);
66
+ }
67
+ return out;
68
+ }
69
+ function isGroup(e) {
70
+ return 'options' in e;
71
+ }
72
+ /** The options of a choice or radio, those of its groups included, in order. */
73
+ function optionsOf(face) {
74
+ return entriesOf(face).flatMap(e => isGroup(e) ? e.options : [e]);
75
+ }
76
+ /** What tells apart two sets of options: their values and where each group starts. */
77
+ function optionsKey(face) {
78
+ return entriesOf(face).map(e => isGroup(e) ? `\u0001${e.options.map(optionValue).join('\0')}` : optionValue(e)).join('\0');
79
+ }
80
+ /** Writes the options of a select: an empty one first, then those of the face, each group in an optgroup. */
81
+ function fillSelect(sel, face) {
82
+ const first = el('option');
83
+ first.value = '';
84
+ sel.replaceChildren(first);
85
+ const option = (o) => {
86
+ const opt = el('option');
87
+ opt.value = optionValue(o);
88
+ opt.textContent = optionText(o);
89
+ return opt;
90
+ };
91
+ for (const e of entriesOf(face)) {
92
+ if (isGroup(e)) {
93
+ const group = el('optgroup');
94
+ group.label = translate(e.title, host.rt);
95
+ group.append(...e.options.map(option));
96
+ sel.append(group);
97
+ }
98
+ else
99
+ sel.append(option(e));
100
+ }
101
+ sel.dataset.options = optionsKey(face);
102
+ }
103
+ /** One of Trebol's own texts (`i18n/ui`) in the active language. */
104
+ function own(key, ...args) {
105
+ return uiText(host.rt, key, ...args);
106
+ }
107
+ /** Gives a node built once one of Trebol's own texts (its text or an attribute); `repaint` keeps it in the active language. */
108
+ function keepOwn(node, key, attr) {
109
+ node.dataset.tbOwn = attr === undefined ? key : `${attr} ${key}`;
110
+ showOwn(node);
111
+ }
112
+ function showOwn(node) {
113
+ const [a, k] = node.dataset.tbOwn.split(' ');
114
+ if (k === undefined)
115
+ node.textContent = own(a);
116
+ else
117
+ node.setAttribute(a, own(k));
118
+ }
119
+ /** A value as it shows on screen: dates, numbers and money in the active language. */
120
+ function display(v) {
121
+ return LOCAL_KINDS.has(v.t) ? shown(v, activeLanguage(host.rt)) : form(v);
122
+ }
123
+ function flag(face, name) {
124
+ const v = get(face, name);
125
+ return !(v.t === K.None || (v.t === K.Logic && !v.v));
126
+ }
127
+ function word(face, name) {
128
+ const v = get(face, name);
129
+ return v.t === K.Word || v.t === K.LitWord ? spell(v.sym).toLowerCase() : null;
130
+ }
131
+ function children(face) {
132
+ const c = get(face, 'pane');
133
+ if (c.t !== K.Block)
134
+ return [];
135
+ return c.s.data.slice(c.i).filter(x => x.t === K.Object);
136
+ }
137
+ /** The name of a face's icon (`#search` -> "search"). */
138
+ function iconName(face) {
139
+ const v = get(face, 'icon');
140
+ return v.t === K.Issue ? spell(v.sym).toLowerCase() : null;
141
+ }
142
+ function icon(name, label = null) {
143
+ const svg = iconNode(name, label);
144
+ if (svg === null)
145
+ console.warn(`Trebol: unknown icon #${name}`);
146
+ return svg;
147
+ }
148
+ function hasRule(face, rule) {
149
+ const rules = get(face, 'rules');
150
+ if (rules.t !== K.Block)
151
+ return false;
152
+ return rules.s.data.some(r => r.t === K.Block && r.s.data[0]?.t === K.Word && spell(r.s.data[0].sym) === rule);
153
+ }
154
+ let host;
155
+ /** Mounted faces by their node and by their input. */
156
+ const byNode = new WeakMap();
157
+ /** The row cell each table row or list item shows. */
158
+ const rowOf = new WeakMap();
159
+ /** Mounted faces by context; a face rebuilt in a new container replaces its entry. */
160
+ const byCtx = new WeakMap();
161
+ /** Contexts of mounted faces written since the last repaint (filled by the core). */
162
+ const dirty = [];
163
+ let nextId = 1;
164
+ const ACTIVE = new Set([K.Word, K.SetWord, K.GetWord, K.Paren, K.Path, K.SetPath, K.GetPath, K.Function, K.Native]);
165
+ /** Runs a UI event function (ui-input, ui-blur, ui-click) as a new task. */
166
+ function fire(fn, face, ...args) {
167
+ // a word, path or paren given as data (a dropped `date`) is quoted, so it is passed, not evaluated
168
+ const quote = { t: K.Word, sym: intern('quote'), bind: host.rt.lib };
169
+ const call = [{ t: K.Word, sym: intern(fn), bind: host.rt.user }, face, ...args.flatMap(a => ACTIVE.has(a.t) ? [quote, a] : [a])];
170
+ const t = taskResult(spawn(host.sch, { data: call }, 0));
171
+ t.catch(e => console.error(report(e)));
172
+ return t;
173
+ }
174
+ function el(tag, cls) {
175
+ const e = document.createElement(tag);
176
+ if (cls)
177
+ e.className = cls;
178
+ return e;
179
+ }
180
+ const INPUTS = new Set(['field', 'password', 'number', 'money', 'date', 'area', 'choice']);
181
+ function build(face) {
182
+ const style = word(face, 'style') ?? 'face';
183
+ const m = {
184
+ face, el: null, input: null, label: null, error: null, kids: get(face, 'pane'),
185
+ box: null, rows: null, empty: null, button: null, radios: null, open: null, shown: undefined,
186
+ typing: 0, typed: null,
187
+ };
188
+ let node;
189
+ if (INPUTS.has(style)) {
190
+ node = buildInput(face, style, m);
191
+ }
192
+ else if (style === 'check' || style === 'toggle') {
193
+ node = buildCheck(face, m, style === 'toggle');
194
+ }
195
+ else if (style === 'radio') {
196
+ node = buildRadio(face, m);
197
+ }
198
+ else if (style === 'upload') {
199
+ node = buildUpload(face, m);
200
+ }
201
+ else if (style === 'photo') {
202
+ node = buildPhoto(face, m);
203
+ }
204
+ else if (style === 'lookup') {
205
+ node = buildLookup(face, m);
206
+ }
207
+ else if (style === 'rich') {
208
+ node = buildRich(face, m);
209
+ }
210
+ else {
211
+ switch (style) {
212
+ case 'view':
213
+ node = el('main', 'tb-view');
214
+ break;
215
+ case 'column':
216
+ node = el('div', 'tb-column');
217
+ break;
218
+ case 'row':
219
+ node = el('div', 'tb-row');
220
+ break;
221
+ case 'toolbar':
222
+ node = buildToolbar();
223
+ break;
224
+ case 'breadcrumb':
225
+ node = buildBreadcrumb(m);
226
+ break;
227
+ case 'rows':
228
+ node = buildRowsField(m);
229
+ break;
230
+ case 'entry': {
231
+ node = el('div', 'tb-entry');
232
+ node.setAttribute('role', 'group');
233
+ break;
234
+ }
235
+ case 'grid':
236
+ node = el('div', 'tb-grid');
237
+ break;
238
+ case 'desktop':
239
+ node = el('div', 'tb-desktop');
240
+ break;
241
+ case 'scroll': {
242
+ // focusable, so keyboard users can scroll it too
243
+ node = el('div', 'tb-scroll');
244
+ node.tabIndex = 0;
245
+ node.setAttribute('role', 'region');
246
+ break;
247
+ }
248
+ case 'panel':
249
+ node = el('section', 'tb-panel');
250
+ break;
251
+ case 'form': {
252
+ const f = el('form', 'tb-form');
253
+ f.noValidate = true;
254
+ // Enter in a field clicks the submit button, which handles it
255
+ f.addEventListener('submit', ev => ev.preventDefault());
256
+ node = f;
257
+ break;
258
+ }
259
+ case 'title':
260
+ node = el('h1', 'tb-title');
261
+ break;
262
+ case 'heading':
263
+ node = el('h2', 'tb-heading');
264
+ break;
265
+ case 'text':
266
+ node = el('p', 'tb-text');
267
+ break;
268
+ case 'divider':
269
+ node = el('hr', 'tb-divider');
270
+ break;
271
+ case 'link': {
272
+ const a = el('a', 'tb-link');
273
+ a.href = screenHref(get(face, 'value')) ?? str(face, 'value') ?? '#';
274
+ withIcon(a, face, m);
275
+ a.addEventListener('click', ev => {
276
+ if (get(face, 'action').t === K.Block) {
277
+ ev.preventDefault();
278
+ void fire('ui-click', face);
279
+ }
280
+ });
281
+ node = a;
282
+ break;
283
+ }
284
+ case 'button': {
285
+ const b = el('button', 'tb-button');
286
+ const submit = flag(face, 'submit');
287
+ b.type = submit ? 'submit' : 'button';
288
+ b.addEventListener('click', ev => {
289
+ if (!submit)
290
+ return void fire('ui-click', face);
291
+ ev.preventDefault();
292
+ clickSubmit(face, b.closest('form, .tb-view') ?? document.body);
293
+ });
294
+ withIcon(b, face, m);
295
+ node = b;
296
+ break;
297
+ }
298
+ case 'tile': {
299
+ const b = el('button', flag(face, 'linked') ? 'tb-tile tb-tile-linked' : 'tb-tile');
300
+ b.type = 'button';
301
+ b.addEventListener('click', () => void fire('ui-click', face));
302
+ withIcon(b, face, m);
303
+ node = b;
304
+ break;
305
+ }
306
+ case 'progress':
307
+ node = buildProgress(m);
308
+ break;
309
+ case 'image':
310
+ node = el('img', 'tb-image');
311
+ break;
312
+ case 'video':
313
+ case 'audio': {
314
+ const media = el(style, `tb-${style}`);
315
+ media.controls = true;
316
+ media.preload = 'metadata';
317
+ if (media instanceof HTMLVideoElement)
318
+ media.playsInline = true;
319
+ node = media;
320
+ break;
321
+ }
322
+ case 'backdrop': {
323
+ // decoration behind its container: screen readers skip it
324
+ node = el('div', 'tb-backdrop');
325
+ node.setAttribute('aria-hidden', 'true');
326
+ break;
327
+ }
328
+ case 'canvas':
329
+ node = buildCanvas(m);
330
+ break;
331
+ case 'chart':
332
+ node = buildChart(m);
333
+ break;
334
+ case 'icon':
335
+ node = el('span', 'tb-icon-face');
336
+ break;
337
+ case 'table':
338
+ case 'list':
339
+ node = buildRows(face, style, m);
340
+ break;
341
+ case 'tree':
342
+ node = buildTree(face, m);
343
+ break;
344
+ case 'dialog':
345
+ node = buildDialog(face, m);
346
+ break;
347
+ case 'tabs':
348
+ node = buildTabs(face, m);
349
+ break;
350
+ case 'split':
351
+ node = buildSplit(face, m);
352
+ break;
353
+ case 'screens': {
354
+ node = el('div', 'tb-screens');
355
+ screensFace = face;
356
+ break;
357
+ }
358
+ case 'screen': {
359
+ node = el('section', 'tb-screen');
360
+ const t = str(face, 'text');
361
+ if (t !== null) {
362
+ node.setAttribute('aria-label', t);
363
+ document.title = t;
364
+ titleFace = face;
365
+ }
366
+ break;
367
+ }
368
+ case 'tab': {
369
+ node = el('div', 'tb-tab-panel');
370
+ node.setAttribute('role', 'tabpanel');
371
+ break;
372
+ }
373
+ default: node = el('div');
374
+ }
375
+ if (style === 'screens')
376
+ placeScreen(m, node);
377
+ else if (children(face).length > 0 && style !== 'tabs' && style !== 'split')
378
+ appendChildren(m.box ?? node, face, style);
379
+ }
380
+ m.el = node;
381
+ byNode.set(node, m);
382
+ if (m.input !== null)
383
+ byNode.set(m.input, m);
384
+ byCtx.set(face.ctx, m);
385
+ face.ctx.watch = dirty;
386
+ listen(m, style);
387
+ sync(m);
388
+ return node;
389
+ }
390
+ // --- general events ------------------------------------------------------------------
391
+ /** Runs a face's on-xxx handler; `words` are the event's own [word: value ...]. */
392
+ function fireEvent(face, name, words = []) {
393
+ const extra = words.flatMap(([w, v]) => [wordOf(K.SetWord, w), v]);
394
+ void fire('ui-event', face, wordOf(K.LitWord, name), blockOf(K.Block, extra));
395
+ }
396
+ /** Keydown events some face's on-key already saw; the view gets the rest. */
397
+ const seenKeys = new WeakSet();
398
+ /** The view with an on-key handler, if any. */
399
+ let viewKeys = null;
400
+ /** Mounted buttons and links with a shortcut. */
401
+ const shortcuts = new Set();
402
+ function listen(m, style) {
403
+ const f = m.face;
404
+ const node = m.el;
405
+ const left = (ev) => !node.contains(ev.relatedTarget);
406
+ if (handlerFor(f, 'on-focus'))
407
+ node.addEventListener('focusin', ev => { if (left(ev))
408
+ fireEvent(f, 'on-focus'); });
409
+ if (handlerFor(f, 'on-unfocus'))
410
+ node.addEventListener('focusout', ev => { if (left(ev))
411
+ fireEvent(f, 'on-unfocus'); });
412
+ if (handlerFor(f, 'on-over')) {
413
+ // as in Red, event/away? is true when the pointer leaves
414
+ node.addEventListener('pointerenter', () => fireEvent(f, 'on-over', [['away?', FALSE]]));
415
+ node.addEventListener('pointerleave', () => fireEvent(f, 'on-over', [['away?', TRUE]]));
416
+ }
417
+ if (handlerFor(f, 'on-dbl-click'))
418
+ node.addEventListener('dblclick', () => fireEvent(f, 'on-dbl-click'));
419
+ if (handlerFor(f, 'on-end'))
420
+ node.addEventListener('ended', () => fireEvent(f, 'on-end'));
421
+ if (handlerFor(f, 'on-key')) {
422
+ if (style === 'view')
423
+ viewKeys = f;
424
+ else
425
+ node.addEventListener('keydown', ev => {
426
+ if (seenKeys.has(ev) || keyCell(ev) === null)
427
+ return;
428
+ seenKeys.add(ev);
429
+ fireEvent(f, 'on-key', keyWords(ev));
430
+ });
431
+ }
432
+ if (str(f, 'shortcut') !== null)
433
+ shortcuts.add(m);
434
+ if (flag(f, 'drop'))
435
+ dropZones.add(m);
436
+ const menu = get(f, 'menu');
437
+ // a button or link without an action opens its menu; anything else has it as its context menu
438
+ if (menu.t === K.Block && (style === 'button' || style === 'link') && get(f, 'action').t !== K.Block) {
439
+ node.setAttribute('aria-haspopup', 'menu');
440
+ node.setAttribute('aria-expanded', 'false');
441
+ // a chevron after the text (or alone after the icon) says it opens a menu; it turns up while open
442
+ if (m.label === null) {
443
+ m.label = el('span');
444
+ node.prepend(m.label);
445
+ }
446
+ const chevron = icon('chevron-down');
447
+ if (chevron !== null) {
448
+ chevron.classList.add('tb-menu-chevron');
449
+ node.append(chevron);
450
+ }
451
+ node.addEventListener('click', ev => {
452
+ ev.preventDefault();
453
+ const r = node.getBoundingClientRect();
454
+ openMenu(trebolEntries(f, menu, NONE), r.left, r.bottom + 4, node);
455
+ });
456
+ }
457
+ else if (menu.t === K.Block || flag(f, 'drag')) {
458
+ node.addEventListener('contextmenu', ev => {
459
+ const target = ev.target;
460
+ const data = style === 'table' || style === 'list' || style === 'tree';
461
+ const item = data ? target.closest(style === 'tree' ? '[role="treeitem"]' : 'tr, li') : null;
462
+ if (item === null && data && menu.t !== K.Block)
463
+ return;
464
+ const row = item !== null ? rowOf.get(item) ?? NONE : NONE;
465
+ const entries = menu.t === K.Block ? trebolEntries(f, menu, row) : [];
466
+ // faces you can drag can also be moved to a drop zone from the menu, without a mouse
467
+ if (flag(f, 'drag')) {
468
+ const zones = moveTargets(f, item !== null ? row : get(f, 'value'));
469
+ if (zones.length > 0) {
470
+ if (entries.length > 0)
471
+ entries.push({ text: '', divider: true });
472
+ entries.push({ text: own('move-to'), sub: zones });
473
+ }
474
+ }
475
+ if (entries.length === 0)
476
+ return;
477
+ ev.preventDefault();
478
+ ev.stopPropagation();
479
+ // from the keyboard (Menu key, Shift+F10) there is no pointer: open by the focused element
480
+ let { clientX: x, clientY: y } = ev;
481
+ if (x === 0 && y === 0) {
482
+ const r = (item ?? (document.activeElement && node.contains(document.activeElement) ? document.activeElement : node)).getBoundingClientRect();
483
+ x = r.left + 8;
484
+ y = r.top + Math.min(r.height, 40);
485
+ }
486
+ openMenu(entries, x, y, item ?? target);
487
+ });
488
+ }
489
+ }
490
+ // --- drag and drop -----------------------------------------------------------------
491
+ //
492
+ // Pointer events rather than HTML drag and drop, so it also works with touch
493
+ // (after a long press) and shows the theme's own indicator.
494
+ /** Mounted faces that accept drops. */
495
+ const dropZones = new Set();
496
+ const isData = (m) => m.rows !== null;
497
+ /** The elements a drop target places things between: rows, or child faces. */
498
+ function slots(m) {
499
+ if (isData(m))
500
+ return Array.from(m.box.children);
501
+ return children(m.face).map(c => byCtx.get(c.ctx)?.el).filter((e) => e !== undefined && e.isConnected);
502
+ }
503
+ function mountedAbove(e) {
504
+ for (let x = e; x !== null; x = x.parentElement) {
505
+ const m = byNode.get(x);
506
+ if (m !== undefined && m.el === x)
507
+ return m;
508
+ }
509
+ return undefined;
510
+ }
511
+ /** The drag source at an element: a draggable face, a row, or a child of a reorderable container. */
512
+ function sourceAt(start) {
513
+ if (start.closest('input, textarea, select, [contenteditable], .tb-split-handle, .tb-menu') !== null)
514
+ return null;
515
+ for (let e = start; e !== null; e = e.parentElement) {
516
+ const row = rowOf.get(e);
517
+ if (row !== undefined) {
518
+ const m = mountedAbove(e);
519
+ // rows the host sorted are not in the order of data, so they cannot be moved
520
+ const reorder = flag(m.face, 'reorder') && hostSorted(m.face) === null;
521
+ if (!flag(m.face, 'drag') && !reorder)
522
+ return null;
523
+ const group = e.parentElement;
524
+ const index = Array.prototype.indexOf.call(group.children, e);
525
+ return { face: m.face, el: e, payload: row, within: reorder ? m : null, index, group };
526
+ }
527
+ const m = byNode.get(e);
528
+ if (m === undefined || m.el !== e)
529
+ continue;
530
+ const parent = mountedAbove(e.parentElement);
531
+ const reorder = parent !== undefined && !isData(parent) && flag(parent.face, 'reorder');
532
+ if (flag(m.face, 'drag') && !isData(m) || reorder) {
533
+ const index = reorder ? slots(parent).indexOf(e) : -1;
534
+ return { face: m.face, el: e, payload: get(m.face, 'value'), within: reorder ? parent : null, index, group: null };
535
+ }
536
+ }
537
+ return null;
538
+ }
539
+ /** The drop target under a point, and the insertion index there. */
540
+ function targetAt(src, x, y) {
541
+ for (let m = mountedAbove(document.elementFromPoint(x, y)); m !== undefined; m = mountedAbove(m.el.parentElement)) {
542
+ if (m.open !== null) {
543
+ const t = treeTarget(m, src, x, y);
544
+ if (t !== null)
545
+ return t;
546
+ continue;
547
+ }
548
+ const reorder = m === src.within;
549
+ if ((reorder || flag(m.face, 'drop')) && m.el !== src.el && !src.el.contains(m.el)) {
550
+ return { m, index: insertionAt(m, x, y), reorder };
551
+ }
552
+ }
553
+ return null;
554
+ }
555
+ const horizontal = (m) => word(m.face, 'style') === 'row';
556
+ function insertionAt(m, x, y) {
557
+ const across = horizontal(m);
558
+ let i = 0;
559
+ for (const e of slots(m)) {
560
+ const r = e.getBoundingClientRect();
561
+ if ((across ? x : y) > (across ? r.left + r.width / 2 : r.top + r.height / 2))
562
+ i++;
563
+ }
564
+ return i;
565
+ }
566
+ let line = null;
567
+ /** Shows where a drop would land: a line between slots, and the target outlined. */
568
+ function indicate(t) {
569
+ document.querySelectorAll('.tb-drop-over').forEach(e => e.classList.remove('tb-drop-over'));
570
+ if (t === null) {
571
+ line?.remove();
572
+ line = null;
573
+ return;
574
+ }
575
+ if (t.into !== undefined) {
576
+ // into a folder: outline its row instead of drawing a line
577
+ t.into.querySelector(':scope > .tb-tree-row').classList.add('tb-drop-over');
578
+ line?.remove();
579
+ line = null;
580
+ return;
581
+ }
582
+ t.m.el.classList.add('tb-drop-over');
583
+ if (line === null) {
584
+ line = el('div', 'tb-drop-line');
585
+ line.setAttribute('aria-hidden', 'true');
586
+ document.body.append(line);
587
+ }
588
+ const across = horizontal(t.m);
589
+ const all = t.group !== undefined ? Array.from(t.group.children) : slots(t.m);
590
+ const box = (t.group ?? t.m.box ?? t.m.el).getBoundingClientRect();
591
+ const before = all[t.index]?.getBoundingClientRect();
592
+ const after = all[t.index - 1]?.getBoundingClientRect();
593
+ line.classList.toggle('tb-across', across);
594
+ if (across) {
595
+ const at = before && after ? (after.right + before.left) / 2 : before ? before.left - 3 : after ? after.right + 3 : box.left + 8;
596
+ const r = before ?? after ?? box;
597
+ Object.assign(line.style, { left: `${at - 1}px`, top: `${r.top}px`, width: '', height: `${r.height}px` });
598
+ }
599
+ else {
600
+ const at = before && after ? (after.bottom + before.top) / 2 : before ? before.top - 3 : after ? after.bottom + 3 : box.top + 8;
601
+ const r = before ?? after ?? box;
602
+ Object.assign(line.style, { left: `${r.left}px`, top: `${at - 1}px`, width: `${r.width}px`, height: '' });
603
+ }
604
+ }
605
+ /** Ends a drag on a target: a move inside its container, or a drop. */
606
+ function land(src, t) {
607
+ if (t.reorder) {
608
+ const to = t.index > src.index ? t.index - 1 : t.index;
609
+ if (to !== src.index)
610
+ void reorder(t.m, src.index, to, t.group, t.parent);
611
+ }
612
+ else {
613
+ void fire('ui-drop', t.m.face, src.payload, src.face, int(t.index + 1), t.parent ?? NONE);
614
+ }
615
+ }
616
+ const int = (n) => ({ t: K.Integer, v: n });
617
+ /** Moves a child or row and keeps the focus on it once the page is repainted. */
618
+ async function reorder(m, from, to, group, parent = NONE) {
619
+ const had = document.activeElement !== null && document.activeElement !== document.body && m.el.contains(document.activeElement);
620
+ await fire('ui-reorder', m.face, int(from + 1), int(to + 1), parent);
621
+ syncDirty();
622
+ if (!had)
623
+ return;
624
+ const e = (group !== undefined ? Array.from(group.children) : slots(m))[to];
625
+ const focusable = e?.matches('[tabindex], button, a, input, textarea, select') ? e : e?.querySelector('[tabindex], button, a, input, textarea, select');
626
+ (focusable ?? null)?.focus();
627
+ }
628
+ /** "Move to" entries: the visible drop zones other than the face itself. */
629
+ function moveTargets(face, payload) {
630
+ const out = [];
631
+ for (const z of dropZones) {
632
+ if (!z.el.isConnected) {
633
+ dropZones.delete(z);
634
+ continue;
635
+ }
636
+ if (z.face.ctx === face.ctx || z.el.getClientRects().length === 0)
637
+ continue;
638
+ // a nameless zone around a named one is the same place
639
+ if (str(z.face, 'text') === null && z.el.querySelector('.tb-drop-zone') !== null)
640
+ continue;
641
+ out.push({
642
+ text: str(z.face, 'text') ?? word(z.face, 'style') ?? '',
643
+ run: () => void fire('ui-drop', z.face, payload, face, int(slots(z).length + 1), NONE),
644
+ });
645
+ }
646
+ return out;
647
+ }
648
+ let dragging = null;
649
+ function startDrag(d) {
650
+ d.on = true;
651
+ d.ghost = el('div', 'tb-drag-ghost');
652
+ d.ghost.textContent = (d.src.el.innerText || d.src.el.textContent || '').split('\n').find(t => t.trim() !== '')?.trim() ?? '';
653
+ d.ghost.setAttribute('aria-hidden', 'true');
654
+ document.body.append(d.ghost);
655
+ d.src.el.classList.add('tb-dragging');
656
+ getSelection()?.removeAllRanges();
657
+ document.documentElement.classList.add('tb-drag-active');
658
+ moveDrag(d, d.x, d.y);
659
+ }
660
+ function moveDrag(d, x, y) {
661
+ d.ghost.style.transform = `translate(${x + 12}px, ${y + 12}px)`;
662
+ d.target = targetAt(d.src, x, y);
663
+ indicate(d.target);
664
+ }
665
+ function endDrag(drop) {
666
+ const d = dragging;
667
+ if (d === null)
668
+ return;
669
+ dragging = null;
670
+ clearTimeout(d.timer);
671
+ if (!d.on)
672
+ return;
673
+ d.ghost?.remove();
674
+ d.src.el.classList.remove('tb-dragging');
675
+ document.documentElement.classList.remove('tb-drag-active');
676
+ indicate(null);
677
+ if (drop && d.target !== null)
678
+ land(d.src, d.target);
679
+ // the click that ends a drag is not a click
680
+ addEventListener('click', swallowClick, true);
681
+ setTimeout(() => removeEventListener('click', swallowClick, true), 0);
682
+ }
683
+ function swallowClick(ev) {
684
+ ev.stopPropagation();
685
+ ev.preventDefault();
686
+ }
687
+ function onPointerDown(ev) {
688
+ if (ev.button !== 0 || dragging !== null)
689
+ return;
690
+ const src = sourceAt(ev.target);
691
+ if (src === null)
692
+ return;
693
+ const d = { src, x: ev.clientX, y: ev.clientY, id: ev.pointerId, on: false, ghost: null, target: null, timer: 0 };
694
+ dragging = d;
695
+ // on touch a long press starts the drag, so a swipe still scrolls
696
+ if (ev.pointerType === 'touch')
697
+ d.timer = setTimeout(() => { if (dragging === d)
698
+ startDrag(d); }, 400);
699
+ }
700
+ function onPointerMove(ev) {
701
+ const d = dragging;
702
+ if (d === null || ev.pointerId !== d.id)
703
+ return;
704
+ if (!d.on) {
705
+ const far = Math.hypot(ev.clientX - d.x, ev.clientY - d.y) > 5;
706
+ if (!far)
707
+ return;
708
+ if (ev.pointerType === 'touch')
709
+ return endDrag(false);
710
+ d.x = ev.clientX;
711
+ d.y = ev.clientY;
712
+ startDrag(d);
713
+ }
714
+ ev.preventDefault();
715
+ moveDrag(d, ev.clientX, ev.clientY);
716
+ }
717
+ /** Alt+Up and Alt+Down move the focused row or child inside a reorderable container. */
718
+ function onReorderKey(ev) {
719
+ if (!ev.altKey || ev.ctrlKey || ev.metaKey || (ev.key !== 'ArrowUp' && ev.key !== 'ArrowDown'))
720
+ return;
721
+ const at = document.activeElement;
722
+ if (at === null)
723
+ return;
724
+ const src = sourceAt(at);
725
+ if (src === null || src.within === null)
726
+ return;
727
+ const to = src.index + (ev.key === 'ArrowUp' ? -1 : 1);
728
+ if (to < 0 || to >= (src.group !== null ? src.group.children.length : slots(src.within).length))
729
+ return;
730
+ ev.preventDefault();
731
+ seenKeys.add(ev);
732
+ const group = src.group ?? undefined;
733
+ void reorder(src.within, src.index, to, group, group !== undefined && src.within.open !== null ? groupParent(src.within, group) : NONE);
734
+ }
735
+ // --- menus ---------------------------------------------------------------------------
736
+ /** The open menus, outermost first. */
737
+ const menus = [];
738
+ /** Where focus goes back when the menus close. */
739
+ let menuOpener = null;
740
+ function closeMenus(from = 0, refocus = true) {
741
+ for (const mn of menus.splice(from)) {
742
+ mn.hidePopover?.();
743
+ mn.remove();
744
+ }
745
+ if (from === 0) {
746
+ menuOpener?.setAttribute('aria-expanded', 'false');
747
+ if (!menuOpener?.hasAttribute('aria-haspopup'))
748
+ menuOpener?.removeAttribute('aria-expanded');
749
+ if (refocus)
750
+ menuOpener?.focus();
751
+ menuOpener = null;
752
+ document.removeEventListener('pointerdown', outsideMenu, true);
753
+ }
754
+ else {
755
+ menus[from - 1]?.querySelector('[aria-expanded="true"]')?.setAttribute('aria-expanded', 'false');
756
+ }
757
+ }
758
+ function outsideMenu(ev) {
759
+ if (!menus.some(mn => mn.contains(ev.target)))
760
+ closeMenus(0, false);
761
+ }
762
+ function menuItems(mn) {
763
+ return Array.from(mn.querySelectorAll(':scope > [role="menuitem"]'));
764
+ }
765
+ /** A menu block of the dialect as menu entries; choosing one runs ui-menu. */
766
+ function trebolEntries(face, items, row) {
767
+ return items.s.data.slice(items.i).filter(x => x.t === K.Object).map(item => {
768
+ const sub = get(item, 'items');
769
+ return {
770
+ text: str(item, 'text') ?? '',
771
+ icon: iconName(item),
772
+ divider: flag(item, 'divider'),
773
+ sub: sub.t === K.Block ? trebolEntries(face, sub, row) : undefined,
774
+ run: () => void fire('ui-menu', face, item, row),
775
+ };
776
+ });
777
+ }
778
+ /** Opens a menu at x, y; level > 0 is a submenu. */
779
+ function openMenu(entries, x, y, opener, level = 0) {
780
+ closeMenus(level, false);
781
+ if (level === 0) {
782
+ menuOpener = opener;
783
+ if (opener.hasAttribute('aria-haspopup'))
784
+ opener.setAttribute('aria-expanded', 'true');
785
+ document.addEventListener('pointerdown', outsideMenu, true);
786
+ }
787
+ const mn = el('div', 'tb-menu');
788
+ mn.setAttribute('role', 'menu');
789
+ mn.setAttribute('popover', 'manual');
790
+ const label = opener.getAttribute('aria-label') ?? opener.textContent;
791
+ if (label)
792
+ mn.setAttribute('aria-label', label.trim());
793
+ for (const item of entries) {
794
+ if (item.divider) {
795
+ const d = el('div', 'tb-menu-divider');
796
+ d.setAttribute('role', 'separator');
797
+ mn.append(d);
798
+ continue;
799
+ }
800
+ const b = el('button', 'tb-menu-item');
801
+ b.type = 'button';
802
+ b.tabIndex = -1;
803
+ b.setAttribute('role', 'menuitem');
804
+ const svg = item.icon ? icon(item.icon) : null;
805
+ const text = el('span');
806
+ text.textContent = item.text;
807
+ b.append(svg ?? el('span', 'tb-menu-gap'), text);
808
+ const sub = item.sub;
809
+ if (sub !== undefined) {
810
+ b.setAttribute('aria-haspopup', 'menu');
811
+ b.setAttribute('aria-expanded', 'false');
812
+ const chevron = icon('chevron-right');
813
+ if (chevron !== null)
814
+ b.append(chevron);
815
+ const openSub = () => {
816
+ const r = b.getBoundingClientRect();
817
+ openMenu(sub, r.right - 4, r.top - 5, b, level + 1);
818
+ b.setAttribute('aria-expanded', 'true');
819
+ };
820
+ b.addEventListener('click', openSub);
821
+ b.addEventListener('keydown', ev => { if (ev.key === 'ArrowRight') {
822
+ ev.preventDefault();
823
+ openSub();
824
+ } });
825
+ }
826
+ else {
827
+ b.addEventListener('click', () => {
828
+ closeMenus();
829
+ item.run?.();
830
+ });
831
+ }
832
+ b.addEventListener('pointerenter', () => b.focus());
833
+ mn.append(b);
834
+ }
835
+ mn.addEventListener('keydown', ev => {
836
+ seenKeys.add(ev);
837
+ const list = menuItems(mn);
838
+ const at = list.indexOf(document.activeElement);
839
+ const n = list.length;
840
+ const to = ev.key === 'ArrowDown' ? (at + 1) % n : ev.key === 'ArrowUp' ? (at - 1 + n) % n
841
+ : ev.key === 'Home' ? 0 : ev.key === 'End' ? n - 1 : -1;
842
+ if (to >= 0) {
843
+ ev.preventDefault();
844
+ list[to]?.focus();
845
+ }
846
+ else if (ev.key === 'Escape' || (ev.key === 'ArrowLeft' && level > 0)) {
847
+ ev.preventDefault();
848
+ ev.stopPropagation();
849
+ if (level > 0) {
850
+ closeMenus(level);
851
+ opener.focus();
852
+ }
853
+ else
854
+ closeMenus();
855
+ }
856
+ else if (ev.key === 'Tab') {
857
+ ev.preventDefault();
858
+ closeMenus();
859
+ }
860
+ else if (ev.key.length === 1 && /\S/.test(ev.key)) {
861
+ // type a letter to jump to the next item that starts with it
862
+ const k = ev.key.toLowerCase();
863
+ const next = [...list.slice(at + 1), ...list.slice(0, at + 1)].find(b => b.textContent?.trim().toLowerCase().startsWith(k));
864
+ next?.focus();
865
+ }
866
+ });
867
+ // keep the icon column only when some item has an icon
868
+ if (mn.querySelector('.tb-menu-item > svg:first-child') === null)
869
+ mn.querySelectorAll('.tb-menu-gap').forEach(g => g.remove());
870
+ // in the top layer, so it shows above an open dialog
871
+ document.body.append(mn);
872
+ mn.showPopover?.();
873
+ const r = mn.getBoundingClientRect();
874
+ mn.style.left = `${Math.max(8, Math.min(x, innerWidth - r.width - 8))}px`;
875
+ mn.style.top = `${Math.max(8, y + r.height > innerHeight - 8 ? y - r.height : y)}px`;
876
+ menus.push(mn);
877
+ menuItems(mn)[0]?.focus();
878
+ }
879
+ let calendar = null;
880
+ const DAY_MS = 86400000;
881
+ /** A date! cell as a UTC date at midnight, or null. */
882
+ function utcDate(v) {
883
+ return v.t === K.Date ? new Date(Date.UTC(v.v.y, v.v.m - 1, v.v.d)) : null;
884
+ }
885
+ function isoDay(d) {
886
+ return d.toISOString().slice(0, 10);
887
+ }
888
+ /** The date argument of a min or max rule of a face, or null. */
889
+ function dateRule(face, rule) {
890
+ const rules = get(face, 'rules');
891
+ if (rules.t !== K.Block)
892
+ return null;
893
+ for (const r of rules.s.data) {
894
+ if (r.t !== K.Block || r.s.data[0]?.t !== K.Word || spell(r.s.data[0].sym) !== rule)
895
+ continue;
896
+ return utcDate(r.s.data[1] ?? NONE);
897
+ }
898
+ return null;
899
+ }
900
+ function openCalendar(face, opener) {
901
+ closeCalendar(false);
902
+ const today = new Date(Date.UTC(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()));
903
+ const box = el('div', 'tb-calendar');
904
+ box.setAttribute('role', 'dialog');
905
+ box.setAttribute('aria-label', opener.getAttribute('aria-label') ?? own('choose-date'));
906
+ box.setAttribute('popover', 'manual');
907
+ const month = el('h2', 'tb-calendar-month');
908
+ month.id = `tb-${nextId++}`;
909
+ month.setAttribute('aria-live', 'polite');
910
+ const step = (name, label, by) => {
911
+ const b = el('button', 'tb-calendar-step');
912
+ b.type = 'button';
913
+ b.setAttribute('aria-label', label);
914
+ const svg = icon(name);
915
+ if (svg !== null)
916
+ b.append(svg);
917
+ b.addEventListener('click', () => {
918
+ if (calendar === null)
919
+ return;
920
+ calendar.at = addMonths(calendar.at, by);
921
+ renderCalendar();
922
+ });
923
+ return b;
924
+ };
925
+ const head = el('div', 'tb-calendar-head');
926
+ head.append(step('chevron-left', own('previous-month'), -1), month, step('chevron-right', own('next-month'), 1));
927
+ box.append(head);
928
+ calendar = { face, opener, box, month, at: utcDate(get(face, 'value')) ?? today };
929
+ opener.setAttribute('aria-expanded', 'true');
930
+ box.addEventListener('keydown', calendarKey);
931
+ box.addEventListener('focusout', ev => {
932
+ if (calendar?.box === box && !box.contains(ev.relatedTarget) && ev.relatedTarget !== null)
933
+ closeCalendar(false);
934
+ });
935
+ document.addEventListener('pointerdown', outsideCalendar, true);
936
+ document.body.append(box);
937
+ box.showPopover?.();
938
+ renderCalendar();
939
+ const r = opener.closest('.tb-date').getBoundingClientRect();
940
+ const c = box.getBoundingClientRect();
941
+ box.style.left = `${Math.max(8, Math.min(r.right - c.width, innerWidth - c.width - 8))}px`;
942
+ box.style.top = `${r.bottom + 4 + c.height > innerHeight - 8 ? Math.max(8, r.top - 4 - c.height) : r.bottom + 4}px`;
943
+ focusDay();
944
+ }
945
+ function closeCalendar(refocus = true) {
946
+ if (calendar === null)
947
+ return;
948
+ const { box, opener } = calendar;
949
+ calendar = null;
950
+ box.hidePopover?.();
951
+ box.remove();
952
+ opener.setAttribute('aria-expanded', 'false');
953
+ document.removeEventListener('pointerdown', outsideCalendar, true);
954
+ if (refocus)
955
+ opener.focus();
956
+ }
957
+ function outsideCalendar(ev) {
958
+ if (calendar !== null && !calendar.box.contains(ev.target) && !calendar.opener.contains(ev.target))
959
+ closeCalendar(false);
960
+ }
961
+ /** Draws the month of the focused day; the head stays. */
962
+ function renderCalendar() {
963
+ const cal = calendar;
964
+ const lang = activeLanguage(host.rt);
965
+ const at = cal.at;
966
+ const min = dateRule(cal.face, 'min');
967
+ const max = dateRule(cal.face, 'max');
968
+ const chosen = utcDate(get(cal.face, 'value'));
969
+ const now = new Date();
970
+ const today = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
971
+ const fmt = (opts) => new Intl.DateTimeFormat(lang, { timeZone: 'UTC', ...opts });
972
+ cal.month.textContent = fmt({ month: 'long', year: 'numeric' }).format(at);
973
+ const grid = el('table', 'tb-calendar-grid');
974
+ grid.setAttribute('role', 'grid');
975
+ grid.setAttribute('aria-labelledby', cal.month.id);
976
+ const first = weekStart(lang) % 7;
977
+ const names = el('tr');
978
+ for (let i = 0; i < 7; i++) {
979
+ // 4-Jan-1970 was a Sunday
980
+ const day = new Date(Date.UTC(1970, 0, 4 + ((first + i) % 7)));
981
+ const th = el('th');
982
+ th.scope = 'col';
983
+ th.abbr = fmt({ weekday: 'long' }).format(day);
984
+ th.textContent = fmt({ weekday: 'narrow' }).format(day);
985
+ names.append(th);
986
+ }
987
+ const thead = el('thead');
988
+ thead.append(names);
989
+ const body = el('tbody');
990
+ const start = Date.UTC(at.getUTCFullYear(), at.getUTCMonth(), 1);
991
+ let ms = start - ((new Date(start).getUTCDay() - first + 7) % 7) * DAY_MS;
992
+ const label = fmt({ dateStyle: 'full' });
993
+ do {
994
+ const row = el('tr');
995
+ for (let i = 0; i < 7; i++, ms += DAY_MS) {
996
+ const d = new Date(ms);
997
+ const td = el('td', 'tb-calendar-day');
998
+ td.setAttribute('role', 'gridcell');
999
+ td.textContent = String(d.getUTCDate());
1000
+ td.setAttribute('aria-label', label.format(d));
1001
+ td.dataset.day = isoDay(d);
1002
+ td.tabIndex = ms === at.getTime() ? 0 : -1;
1003
+ if (d.getUTCMonth() !== at.getUTCMonth())
1004
+ td.classList.add('tb-calendar-other');
1005
+ if (ms === today)
1006
+ td.setAttribute('aria-current', 'date');
1007
+ td.setAttribute('aria-selected', chosen !== null && ms === chosen.getTime() ? 'true' : 'false');
1008
+ if ((min !== null && d < min) || (max !== null && d > max))
1009
+ td.setAttribute('aria-disabled', 'true');
1010
+ td.addEventListener('click', () => pickDay(d));
1011
+ row.append(td);
1012
+ }
1013
+ body.append(row);
1014
+ } while (new Date(ms).getUTCMonth() === at.getUTCMonth());
1015
+ grid.append(thead, body);
1016
+ cal.box.querySelector('table')?.remove();
1017
+ cal.box.append(grid);
1018
+ }
1019
+ function addMonths(d, n) {
1020
+ const y = d.getUTCFullYear(), m = d.getUTCMonth() + n;
1021
+ // the same day, or the last one of a shorter month
1022
+ const last = new Date(Date.UTC(y, m + 1, 0)).getUTCDate();
1023
+ return new Date(Date.UTC(y, m, Math.min(d.getUTCDate(), last)));
1024
+ }
1025
+ function focusDay() {
1026
+ calendar?.box.querySelector('td[tabindex="0"]')?.focus();
1027
+ }
1028
+ function pickDay(d) {
1029
+ const cal = calendar;
1030
+ if (cal === null)
1031
+ return;
1032
+ if (cal.box.querySelector(`td[data-day="${isoDay(d)}"]`)?.getAttribute('aria-disabled') === 'true')
1033
+ return;
1034
+ const face = cal.face;
1035
+ closeCalendar();
1036
+ void fire('ui-input', face, string(isoDay(d))).then(() => fire('ui-blur', face));
1037
+ }
1038
+ function calendarKey(ev) {
1039
+ const cal = calendar;
1040
+ if (cal === null)
1041
+ return;
1042
+ seenKeys.add(ev);
1043
+ if (ev.key === 'Escape') {
1044
+ ev.preventDefault();
1045
+ ev.stopPropagation();
1046
+ closeCalendar();
1047
+ return;
1048
+ }
1049
+ if (!(ev.target instanceof HTMLTableCellElement))
1050
+ return;
1051
+ const at = cal.at;
1052
+ const first = weekStart(activeLanguage(host.rt)) % 7;
1053
+ const back = (at.getUTCDay() - first + 7) % 7;
1054
+ const days = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7, Home: -back, End: 6 - back };
1055
+ let to = null;
1056
+ if (ev.key in days)
1057
+ to = new Date(at.getTime() + days[ev.key] * DAY_MS);
1058
+ else if (ev.key === 'PageUp' || ev.key === 'PageDown')
1059
+ to = addMonths(at, (ev.key === 'PageUp' ? -1 : 1) * (ev.shiftKey ? 12 : 1));
1060
+ else if (ev.key === 'Enter' || ev.key === ' ') {
1061
+ ev.preventDefault();
1062
+ pickDay(at);
1063
+ return;
1064
+ }
1065
+ if (to === null)
1066
+ return;
1067
+ ev.preventDefault();
1068
+ cal.at = to;
1069
+ if (to.getUTCMonth() === at.getUTCMonth()) {
1070
+ cal.box.querySelectorAll('td[tabindex="0"]').forEach(td => { td.tabIndex = -1; });
1071
+ const td = cal.box.querySelector(`td[data-day="${isoDay(to)}"]`);
1072
+ td.tabIndex = 0;
1073
+ td.focus();
1074
+ }
1075
+ else {
1076
+ renderCalendar();
1077
+ focusDay();
1078
+ }
1079
+ }
1080
+ const MODIFIER_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph', 'CapsLock', 'Dead', 'Unidentified']);
1081
+ /** Keys that are characters in Red's event/key. */
1082
+ const KEY_CHARS = { Enter: 13, Escape: 27, Tab: 9, Backspace: 8 };
1083
+ /** Keys that are words in Red's event/key. */
1084
+ const KEY_WORDS = {
1085
+ ArrowLeft: 'left', ArrowRight: 'right', ArrowUp: 'up', ArrowDown: 'down', Home: 'home', End: 'end',
1086
+ PageUp: 'page-up', PageDown: 'page-down', Insert: 'insert', Delete: 'delete',
1087
+ };
1088
+ /** A key as Red gives it in event/key: a char! (#"a", #"^M" for Enter) or a word ('left, 'F2). */
1089
+ function keyCell(ev) {
1090
+ if (MODIFIER_KEYS.has(ev.key))
1091
+ return null;
1092
+ const c = KEY_CHARS[ev.key];
1093
+ if (c !== undefined)
1094
+ return char(c);
1095
+ const cps = [...ev.key];
1096
+ if (cps.length === 1)
1097
+ return char(cps[0].codePointAt(0));
1098
+ if (/^F\d+$/.test(ev.key))
1099
+ return wordOf(K.LitWord, ev.key);
1100
+ return wordOf(K.LitWord, KEY_WORDS[ev.key] ?? ev.key.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase());
1101
+ }
1102
+ function keyWords(ev) {
1103
+ const b = (x) => x ? TRUE : FALSE;
1104
+ return [['key', keyCell(ev)], ['ctrl?', b(ev.ctrlKey)], ['shift?', b(ev.shiftKey)], ['alt?', b(ev.altKey)], ['meta?', b(ev.metaKey)]];
1105
+ }
1106
+ const APPLE = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);
1107
+ const KEY_NAMES = {
1108
+ esc: 'escape', space: ' ', del: 'delete', up: 'arrowup', down: 'arrowdown', left: 'arrowleft', right: 'arrowright',
1109
+ };
1110
+ /** "Ctrl+Shift+K" -> its parts; Ctrl also means Cmd on Apple devices. */
1111
+ function parseShortcut(spec) {
1112
+ const parts = spec.toLowerCase().split('+').map(p => p.trim());
1113
+ const key = parts.pop() ?? '';
1114
+ const has = (...names) => parts.some(p => names.includes(p));
1115
+ return { key: KEY_NAMES[key] ?? key, ctrl: has('ctrl', 'control'), shift: has('shift'), alt: has('alt', 'option'), meta: has('meta', 'cmd') };
1116
+ }
1117
+ function matches(ev, s) {
1118
+ const ctrl = APPLE ? ev.metaKey || ev.ctrlKey : ev.ctrlKey;
1119
+ if (ctrl !== (s.ctrl || (APPLE && s.meta)) || ev.shiftKey !== s.shift || ev.altKey !== s.alt)
1120
+ return false;
1121
+ if (!APPLE && ev.metaKey !== s.meta)
1122
+ return false;
1123
+ // letters and digits by physical key, so Shift or Alt do not change them
1124
+ if (/^[a-z]$/.test(s.key))
1125
+ return ev.code === `Key${s.key.toUpperCase()}`;
1126
+ if (/^[0-9]$/.test(s.key))
1127
+ return ev.code === `Digit${s.key}`;
1128
+ return ev.key.toLowerCase() === s.key;
1129
+ }
1130
+ /** How a shortcut is announced (aria-keyshortcuts) and shown (tooltip). */
1131
+ function shortcutAria(spec) {
1132
+ return spec.split('+').map(p => {
1133
+ const w = p.trim().toLowerCase();
1134
+ if (w === 'ctrl' || w === 'control')
1135
+ return APPLE ? 'Meta' : 'Control';
1136
+ if (w === 'cmd')
1137
+ return 'Meta';
1138
+ return p.trim().length === 1 ? p.trim().toUpperCase() : p.trim();
1139
+ }).join('+');
1140
+ }
1141
+ function shortcutLabel(spec) {
1142
+ return APPLE ? spec.replace(/ctrl|control/i, 'Cmd') : spec;
1143
+ }
1144
+ /** Shortcuts beat the browser's own keys; the view's on-key gets keys nobody handled. */
1145
+ function onKeyDown(ev) {
1146
+ const modal = Array.from(document.querySelectorAll('dialog[open]')).pop();
1147
+ for (const m of shortcuts) {
1148
+ if (!m.el.isConnected) {
1149
+ shortcuts.delete(m);
1150
+ continue;
1151
+ }
1152
+ const spec = str(m.face, 'shortcut');
1153
+ if (spec === null || !matches(ev, parseShortcut(spec)))
1154
+ continue;
1155
+ // only what the user can see: not in a hidden tab, a closed dialog or behind a modal
1156
+ if (m.el.getClientRects().length === 0 || (modal !== undefined && !modal.contains(m.el)))
1157
+ continue;
1158
+ ev.preventDefault();
1159
+ seenKeys.add(ev);
1160
+ m.el.click();
1161
+ return;
1162
+ }
1163
+ }
1164
+ function onViewKey(ev) {
1165
+ if (viewKeys === null || seenKeys.has(ev) || keyCell(ev) === null)
1166
+ return;
1167
+ fireEvent(viewKeys, 'on-key', keyWords(ev));
1168
+ }
1169
+ /** Puts the face's icon before its caption, which then goes in `m.label`. */
1170
+ function withIcon(node, face, m) {
1171
+ const name = iconName(face);
1172
+ const svg = name !== null ? icon(name) : null;
1173
+ if (svg === null)
1174
+ return;
1175
+ m.label = el('span');
1176
+ node.append(svg, m.label);
1177
+ node.classList.add('tb-has-icon');
1178
+ }
1179
+ /** A face with an icon and no text is named after its icon: #arrow-left -> "Arrow left". */
1180
+ function iconLabel(face) {
1181
+ const name = iconName(face);
1182
+ if (name === null || (str(face, 'text') ?? '') !== '')
1183
+ return null;
1184
+ const hint = str(face, 'hint');
1185
+ if (hint !== null)
1186
+ return hint;
1187
+ const words = name.replace(/-/g, ' ');
1188
+ return words.charAt(0).toUpperCase() + words.slice(1);
1189
+ }
1190
+ /** Children of a container; consecutive buttons in a form share an action row. */
1191
+ function appendChildren(node, face, style) {
1192
+ let actions = null;
1193
+ for (const c of children(face)) {
1194
+ const isButton = word(c, 'style') === 'button';
1195
+ if (style === 'form' && isButton) {
1196
+ if (actions === null) {
1197
+ actions = el('div', 'tb-actions');
1198
+ node.append(actions);
1199
+ }
1200
+ actions.append(build(c));
1201
+ }
1202
+ else {
1203
+ actions = null;
1204
+ const n = build(c);
1205
+ if (style === 'toolbar' && n.tagName === 'HR')
1206
+ n.setAttribute('aria-orientation', 'vertical');
1207
+ node.append(n);
1208
+ }
1209
+ }
1210
+ }
1211
+ function clickSubmit(face, formEl) {
1212
+ void fire('ui-click', face).then(() => {
1213
+ // after a failed submit, take the user to the first problem
1214
+ for (const i of Array.from(formEl.querySelectorAll('input, textarea, select'))) {
1215
+ const m = byNode.get(i);
1216
+ if (m !== undefined && get(m.face, 'error').t === K.String)
1217
+ return i.focus();
1218
+ }
1219
+ });
1220
+ }
1221
+ function buildInput(face, style, m) {
1222
+ const id = `tb-${nextId++}`;
1223
+ const wrap = el('div', 'tb-field');
1224
+ const label = el('label', 'tb-label');
1225
+ label.htmlFor = id;
1226
+ const control = el('div', 'tb-control');
1227
+ let input;
1228
+ if (style === 'area') {
1229
+ input = el('textarea', 'tb-input');
1230
+ }
1231
+ else if (style === 'choice') {
1232
+ const sel = el('select', 'tb-input');
1233
+ fillSelect(sel, face);
1234
+ input = sel;
1235
+ }
1236
+ else {
1237
+ const i = el('input', 'tb-input');
1238
+ i.type = style === 'password' ? 'password' : hasRule(face, 'email') ? 'email' : hasRule(face, 'url') ? 'url' : 'text';
1239
+ if (style === 'number' || style === 'money' || hasRule(face, 'integer'))
1240
+ i.inputMode = hasRule(face, 'integer') ? 'numeric' : 'decimal';
1241
+ if (style === 'password')
1242
+ i.autocomplete = 'new-password';
1243
+ input = i;
1244
+ }
1245
+ input.id = id;
1246
+ const error = el('div', 'tb-error');
1247
+ error.id = `${id}-error`;
1248
+ error.setAttribute('aria-live', 'polite');
1249
+ input.setAttribute('aria-describedby', error.id);
1250
+ const name = word(face, 'name');
1251
+ if (name !== null)
1252
+ input.name = name;
1253
+ input.addEventListener(style === 'choice' ? 'change' : 'input', () => {
1254
+ // an amount goes to Trebol as 1234.5 and a date as 2026-11-03; what is not one goes as typed
1255
+ const lang = activeLanguage(host.rt);
1256
+ const typed = style === 'money' ? readLocal(input.value, lang) ?? input.value
1257
+ : style === 'date' ? readDate(input.value, lang) ?? input.value : input.value;
1258
+ m.typing++;
1259
+ const settled = () => {
1260
+ m.typing--;
1261
+ m.typed = get(face, 'value');
1262
+ };
1263
+ void fire('ui-input', face, typed === '' ? NONE : string(typed)).then(settled, settled);
1264
+ });
1265
+ // an amount shows formatted, and is edited as a plain number of the active language
1266
+ if (style === 'money')
1267
+ input.addEventListener('focus', () => {
1268
+ if (!flag(face, 'readonly'))
1269
+ input.value = editLocal(get(face, 'value'), activeLanguage(host.rt));
1270
+ });
1271
+ input.addEventListener('blur', () => void fire('ui-blur', face));
1272
+ const iconWord = style === 'area' || style === 'choice' ? null : iconName(face);
1273
+ const svg = iconWord !== null ? icon(iconWord) : null;
1274
+ if (style === 'date') {
1275
+ const box = el('div', 'tb-date');
1276
+ const pick = el('button', 'tb-date-button');
1277
+ pick.type = 'button';
1278
+ pick.setAttribute('aria-haspopup', 'dialog');
1279
+ pick.setAttribute('aria-expanded', 'false');
1280
+ const cal = icon('calendar');
1281
+ if (cal !== null)
1282
+ pick.append(cal);
1283
+ pick.addEventListener('click', () => (calendar?.opener === pick ? closeCalendar() : openCalendar(face, pick)));
1284
+ box.append(input, pick);
1285
+ control.append(box, error);
1286
+ }
1287
+ else if (svg !== null) {
1288
+ const box = el('div', 'tb-input-icon');
1289
+ box.append(svg, input);
1290
+ control.append(box, error);
1291
+ }
1292
+ else {
1293
+ control.append(input, error);
1294
+ }
1295
+ wrap.append(label, control);
1296
+ m.input = input;
1297
+ m.label = label;
1298
+ m.error = error;
1299
+ return wrap;
1300
+ }
1301
+ function buildCheck(face, m, toggle) {
1302
+ const row = el('div', 'tb-check-row tb-control');
1303
+ const label = el('label', toggle ? 'tb-check tb-switch' : 'tb-check');
1304
+ const box = el('input');
1305
+ box.type = 'checkbox';
1306
+ if (toggle)
1307
+ box.setAttribute('role', 'switch');
1308
+ const caption = el('span');
1309
+ const error = el('div', 'tb-error');
1310
+ error.id = `tb-${nextId++}-error`;
1311
+ error.setAttribute('aria-live', 'polite');
1312
+ box.setAttribute('aria-describedby', error.id);
1313
+ box.addEventListener('change', () => {
1314
+ void fire('ui-input', face, box.checked ? TRUE : FALSE).then(() => fire('ui-blur', face));
1315
+ });
1316
+ label.append(box, caption);
1317
+ row.append(label, error);
1318
+ m.input = box;
1319
+ m.label = caption;
1320
+ m.error = error;
1321
+ return row;
1322
+ }
1323
+ function buildRadio(face, m) {
1324
+ const id = `tb-${nextId++}`;
1325
+ const wrap = el('div', 'tb-field');
1326
+ const label = el('span', 'tb-label');
1327
+ label.id = id;
1328
+ const control = el('div', 'tb-control');
1329
+ const group = el('div', 'tb-radios');
1330
+ group.setAttribute('role', 'radiogroup');
1331
+ group.setAttribute('aria-labelledby', id);
1332
+ const error = el('div', 'tb-error');
1333
+ error.id = `${id}-error`;
1334
+ error.setAttribute('aria-live', 'polite');
1335
+ group.setAttribute('aria-describedby', error.id);
1336
+ m.radios = [];
1337
+ const radio = (o) => {
1338
+ const option = el('label', 'tb-check');
1339
+ const r = el('input');
1340
+ r.type = 'radio';
1341
+ r.name = id;
1342
+ r.value = optionValue(o);
1343
+ r.addEventListener('change', () => {
1344
+ if (r.checked)
1345
+ void fire('ui-input', face, string(r.value)).then(() => fire('ui-blur', face));
1346
+ });
1347
+ const caption = el('span');
1348
+ caption.textContent = optionText(o);
1349
+ option.append(r, caption);
1350
+ m.radios.push(r);
1351
+ return option;
1352
+ };
1353
+ // a group of options: its title over them, the group named by it
1354
+ for (const e of entriesOf(face)) {
1355
+ if (isGroup(e)) {
1356
+ const sub = el('div', 'tb-radio-group');
1357
+ sub.setAttribute('role', 'group');
1358
+ const title = el('span', 'tb-radio-title');
1359
+ title.id = `tb-${nextId++}`;
1360
+ title.textContent = translate(e.title, host.rt);
1361
+ sub.setAttribute('aria-labelledby', title.id);
1362
+ const items = el('div', 'tb-radios');
1363
+ items.append(...e.options.map(radio));
1364
+ sub.append(title, items);
1365
+ group.append(sub);
1366
+ }
1367
+ else
1368
+ group.append(radio(e));
1369
+ }
1370
+ control.append(group, error);
1371
+ wrap.append(label, control);
1372
+ m.label = label;
1373
+ m.error = error;
1374
+ return wrap;
1375
+ }
1376
+ // An upload: a button that is also a place to drop files, and the list of the
1377
+ // chosen ones. Files go to Trebol as handles; their bytes stay in the browser.
1378
+ function buildUpload(face, m) {
1379
+ const id = `tb-${nextId++}`;
1380
+ const wrap = el('div', 'tb-field');
1381
+ const label = el('label', 'tb-label');
1382
+ label.htmlFor = id;
1383
+ const control = el('div', 'tb-control');
1384
+ const zone = el('div', 'tb-upload');
1385
+ const picker = el('input');
1386
+ picker.type = 'file';
1387
+ picker.hidden = true;
1388
+ picker.tabIndex = -1;
1389
+ const choose = el('button', 'tb-button');
1390
+ choose.type = 'button';
1391
+ choose.id = id;
1392
+ const svg = icon('upload');
1393
+ if (svg !== null)
1394
+ choose.append(svg);
1395
+ choose.append(el('span'));
1396
+ const hint = el('span', 'tb-upload-hint');
1397
+ const error = el('div', 'tb-error');
1398
+ error.id = `${id}-error`;
1399
+ error.setAttribute('aria-live', 'polite');
1400
+ choose.setAttribute('aria-describedby', error.id);
1401
+ const list = el('ul', 'tb-upload-list');
1402
+ const track = sentBar(label, id);
1403
+ choose.addEventListener('click', () => picker.click());
1404
+ picker.addEventListener('change', () => {
1405
+ const files = [...(picker.files ?? [])];
1406
+ picker.value = '';
1407
+ if (files.length > 0)
1408
+ chooseFiles(face, files);
1409
+ });
1410
+ dropFiles(face, zone, choose);
1411
+ zone.append(choose, hint, picker);
1412
+ control.append(zone, list, track, error);
1413
+ wrap.append(label, control);
1414
+ m.label = label;
1415
+ m.error = error;
1416
+ m.button = choose;
1417
+ m.box = list;
1418
+ return wrap;
1419
+ }
1420
+ /** The accept list of an upload: extensions ("pdf") and types ("image/*"); a photo takes images unless told. */
1421
+ function acceptList(face) {
1422
+ const a = get(face, 'accept');
1423
+ if (a.t !== K.Block && word(face, 'style') === 'photo')
1424
+ return ['image/*'];
1425
+ return a.t === K.Block ? a.s.data.slice(a.i).map(x => form(x).trim().toLowerCase()).filter(x => x !== '') : [];
1426
+ }
1427
+ /** The picker's accept attribute for an accept list. */
1428
+ function pickerAccept(list) {
1429
+ return list.map(x => (x.includes('/') || x.startsWith('.') ? x : `.${x}`)).join(',');
1430
+ }
1431
+ /** Lets a zone take files dropped on it, unless its button is disabled. */
1432
+ function dropFiles(face, zone, button) {
1433
+ const hasFiles = (ev) => ev.dataTransfer?.types.includes('Files') === true;
1434
+ zone.addEventListener('dragover', ev => {
1435
+ if (!hasFiles(ev) || button.disabled)
1436
+ return;
1437
+ ev.preventDefault();
1438
+ ev.dataTransfer.dropEffect = 'copy';
1439
+ zone.classList.add('tb-drop-over');
1440
+ });
1441
+ zone.addEventListener('dragleave', ev => {
1442
+ if (!zone.contains(ev.relatedTarget))
1443
+ zone.classList.remove('tb-drop-over');
1444
+ });
1445
+ zone.addEventListener('drop', ev => {
1446
+ zone.classList.remove('tb-drop-over');
1447
+ if (!hasFiles(ev) || button.disabled)
1448
+ return;
1449
+ ev.preventDefault();
1450
+ chooseFiles(face, [...ev.dataTransfer.files]);
1451
+ });
1452
+ }
1453
+ /** The bar of how far the files went up, while a fetch with progress sends them. */
1454
+ function sentBar(label, id) {
1455
+ label.id = `${id}-label`;
1456
+ const track = el('div', 'tb-progress tb-upload-progress');
1457
+ track.setAttribute('role', 'progressbar');
1458
+ track.setAttribute('aria-valuemin', '0');
1459
+ track.setAttribute('aria-valuemax', '100');
1460
+ track.setAttribute('aria-labelledby', label.id);
1461
+ track.hidden = true;
1462
+ track.append(el('div', 'tb-progress-bar'));
1463
+ return track;
1464
+ }
1465
+ function syncSent(m) {
1466
+ const track = m.el.querySelector('.tb-upload-progress');
1467
+ const sent = get(m.face, 'sent');
1468
+ const part = fraction(sent) ?? 0;
1469
+ track.hidden = sent.t === K.None;
1470
+ track.setAttribute('aria-valuenow', String(Math.round(part * 100)));
1471
+ track.firstChild.style.width = `${part * 100}%`;
1472
+ }
1473
+ // A photo: the image itself, a button to choose one and another to take it away. The
1474
+ // image chosen shows from the browser's memory; one kept elsewhere, from its address.
1475
+ // A video or a sound: the browser's own player. Captions are one track per language;
1476
+ // the active language's is the one shown, and it follows set-language.
1477
+ /** A video's captions as [language, address] pairs: a file alone is in the active language. */
1478
+ function captionTracks(f) {
1479
+ const c = get(f, 'captions');
1480
+ if (c.t === K.File || c.t === K.Url || c.t === K.String)
1481
+ return [[activeLanguage(host.rt), form(c)]];
1482
+ if (c.t !== K.Block)
1483
+ return [];
1484
+ const d = c.s.data.slice(c.i);
1485
+ const out = [];
1486
+ for (let i = 0; i + 1 < d.length; i += 2)
1487
+ out.push([form(d[i]), form(d[i + 1])]);
1488
+ return out;
1489
+ }
1490
+ function syncMedia(m) {
1491
+ const f = m.face;
1492
+ const media = m.el;
1493
+ const src = str(f, 'value') ?? '';
1494
+ if (media.getAttribute('src') !== src)
1495
+ media.src = src;
1496
+ const t = str(f, 'text');
1497
+ if (t !== null)
1498
+ media.setAttribute('aria-label', t);
1499
+ else
1500
+ media.removeAttribute('aria-label');
1501
+ media.loop = flag(f, 'looping');
1502
+ // browsers only let what plays on its own do so without sound
1503
+ const auto = flag(f, 'autoplay');
1504
+ media.muted = flag(f, 'silent') || auto;
1505
+ media.autoplay = auto;
1506
+ if (!(media instanceof HTMLVideoElement))
1507
+ return;
1508
+ const poster = str(f, 'poster') ?? '';
1509
+ if (media.getAttribute('poster') !== poster)
1510
+ media.poster = poster;
1511
+ const lang = activeLanguage(host.rt);
1512
+ const tracks = captionTracks(f);
1513
+ const names = new Intl.DisplayNames([lang], { type: 'language' });
1514
+ const now = Array.from(media.querySelectorAll('track'));
1515
+ if (now.map(x => `${x.srclang} ${x.getAttribute('src')}`).join('|') !== tracks.map(([l, s]) => `${l} ${s}`).join('|')) {
1516
+ media.replaceChildren(...tracks.map(([l, s]) => {
1517
+ const track = el('track');
1518
+ track.kind = 'captions';
1519
+ track.srclang = l;
1520
+ track.src = s;
1521
+ return track;
1522
+ }));
1523
+ }
1524
+ // the captions shown, if any, follow the active language
1525
+ const showing = Array.from(media.textTracks).some(x => x.mode === 'showing');
1526
+ const pick = tracks.findIndex(([l]) => l === lang);
1527
+ media.querySelectorAll('track').forEach((track, i) => {
1528
+ track.label = names.of(track.srclang) ?? track.srclang;
1529
+ track.default = i === Math.max(0, pick);
1530
+ if (showing)
1531
+ track.track.mode = i === Math.max(0, pick) ? 'showing' : 'disabled';
1532
+ });
1533
+ }
1534
+ /** The address that shows each chosen file, made once and freed when the photo shows another. */
1535
+ const shownUrls = new WeakMap();
1536
+ function buildPhoto(face, m) {
1537
+ const id = `tb-${nextId++}`;
1538
+ const wrap = el('div', 'tb-field');
1539
+ const label = el('label', 'tb-label');
1540
+ label.htmlFor = id;
1541
+ const control = el('div', 'tb-control');
1542
+ const zone = el('div', 'tb-photo');
1543
+ // the frame opens the picker for a pointer; the keyboard has the button
1544
+ const frame = el('div', 'tb-photo-frame');
1545
+ frame.addEventListener('click', () => { if (!choose.disabled)
1546
+ picker.click(); });
1547
+ const picker = el('input');
1548
+ picker.type = 'file';
1549
+ picker.hidden = true;
1550
+ picker.tabIndex = -1;
1551
+ const actions = el('div', 'tb-photo-actions');
1552
+ const choose = el('button', 'tb-button');
1553
+ choose.type = 'button';
1554
+ choose.id = id;
1555
+ const svg = icon('upload');
1556
+ if (svg !== null)
1557
+ choose.append(svg);
1558
+ choose.append(el('span'));
1559
+ const remove = el('button', 'tb-button tb-photo-remove');
1560
+ remove.type = 'button';
1561
+ remove.addEventListener('click', () => {
1562
+ choose.focus();
1563
+ void fire('ui-remove-file', face, int(1));
1564
+ });
1565
+ const error = el('div', 'tb-error');
1566
+ error.id = `${id}-error`;
1567
+ error.setAttribute('aria-live', 'polite');
1568
+ choose.setAttribute('aria-describedby', error.id);
1569
+ choose.addEventListener('click', () => picker.click());
1570
+ picker.addEventListener('change', () => {
1571
+ const files = [...(picker.files ?? [])];
1572
+ picker.value = '';
1573
+ if (files.length > 0)
1574
+ chooseFiles(face, files);
1575
+ });
1576
+ dropFiles(face, zone, choose);
1577
+ actions.append(choose, remove);
1578
+ zone.append(frame, actions, picker);
1579
+ control.append(zone, sentBar(label, id), error);
1580
+ wrap.append(label, control);
1581
+ m.label = label;
1582
+ m.error = error;
1583
+ m.button = choose;
1584
+ m.box = frame;
1585
+ return wrap;
1586
+ }
1587
+ /** What a photo shows: the image chosen, or the address of one kept elsewhere; null for none. */
1588
+ function photoSrc(frame, v) {
1589
+ const kept = shownUrls.get(frame);
1590
+ const file = v.t === K.Object ? handleOf(get(v, 'file'), 'file') : null;
1591
+ if (file !== null && kept !== undefined && kept.blob === file)
1592
+ return kept.url;
1593
+ if (kept !== undefined) {
1594
+ URL.revokeObjectURL(kept.url);
1595
+ shownUrls.delete(frame);
1596
+ }
1597
+ if (file !== null) {
1598
+ const url = URL.createObjectURL(file);
1599
+ shownUrls.set(frame, { blob: file, url });
1600
+ return url;
1601
+ }
1602
+ return v.t === K.String || v.t === K.Url || v.t === K.File ? form(v) : null;
1603
+ }
1604
+ function syncPhoto(m, err) {
1605
+ const f = m.face;
1606
+ const t = str(f, 'text') ?? '';
1607
+ m.label.textContent = t;
1608
+ m.label.classList.toggle('tb-required', required(f));
1609
+ const readonly = flag(f, 'readonly');
1610
+ const choose = m.button;
1611
+ choose.disabled = flag(f, 'disabled') || readonly;
1612
+ choose.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
1613
+ const frame = m.box;
1614
+ frame.classList.toggle('tb-round', flag(f, 'round'));
1615
+ frame.classList.toggle('tb-photo-pick', !choose.disabled);
1616
+ const src = photoSrc(frame, get(f, 'value'));
1617
+ let img = frame.querySelector('img');
1618
+ if (src === null) {
1619
+ if (img !== null || frame.firstChild === null) {
1620
+ const svg = icon(flag(f, 'round') ? 'user' : 'image');
1621
+ frame.replaceChildren(...(svg !== null ? [svg] : []));
1622
+ }
1623
+ }
1624
+ else {
1625
+ if (img === null) {
1626
+ img = el('img');
1627
+ frame.replaceChildren(img);
1628
+ }
1629
+ if (img.getAttribute('src') !== src)
1630
+ img.src = src;
1631
+ img.alt = t;
1632
+ }
1633
+ choose.lastChild.textContent = own(src === null ? 'choose-photo' : 'change-photo');
1634
+ const remove = m.el.querySelector('.tb-photo-remove');
1635
+ remove.textContent = own('remove-photo');
1636
+ remove.hidden = src === null || readonly;
1637
+ remove.disabled = choose.disabled;
1638
+ // read only, there is nothing to choose: only the photo is left
1639
+ m.el.querySelector('.tb-photo-actions').hidden = readonly;
1640
+ m.el.querySelector('input[type="file"]').accept = pickerAccept(acceptList(f));
1641
+ m.error.textContent = err ?? '';
1642
+ syncSent(m);
1643
+ }
1644
+ function accepts(file, list) {
1645
+ if (list.length === 0)
1646
+ return true;
1647
+ const name = file.name.toLowerCase();
1648
+ const type = file.type.toLowerCase();
1649
+ return list.some(x => x.includes('/')
1650
+ ? (x.endsWith('/*') ? type.startsWith(x.slice(0, -1)) : type === x)
1651
+ : name.endsWith(x.startsWith('.') ? x : `.${x}`));
1652
+ }
1653
+ function chooseFiles(face, files) {
1654
+ const list = acceptList(face);
1655
+ const ok = files.filter(f => accepts(f, list));
1656
+ const taken = flag(face, 'multiple') ? ok : ok.slice(0, 1);
1657
+ const cells = [];
1658
+ for (const f of taken)
1659
+ cells.push(string(f.name), int(f.size), string(f.type), fileHandle(f));
1660
+ const refused = files.filter(f => !accepts(f, list)).map(f => string(f.name));
1661
+ void fire('ui-files', face, blockOf(K.Block, cells), blockOf(K.Block, refused));
1662
+ }
1663
+ /** A link as the page would follow it, relative ones too; null unless it is http or https. */
1664
+ function webHref(url) {
1665
+ try {
1666
+ const u = new URL(url, location.href);
1667
+ return u.protocol === 'http:' || u.protocol === 'https:' ? u.href : null;
1668
+ }
1669
+ catch {
1670
+ return null;
1671
+ }
1672
+ }
1673
+ function syncUpload(m, err) {
1674
+ const f = m.face;
1675
+ const label = m.label;
1676
+ label.textContent = str(f, 'text') ?? '';
1677
+ label.classList.toggle('tb-required', required(f));
1678
+ const many = flag(f, 'multiple');
1679
+ const choose = m.button;
1680
+ choose.lastChild.textContent = own(many ? 'choose-files' : 'choose-file');
1681
+ const readonly = flag(f, 'readonly');
1682
+ choose.disabled = flag(f, 'disabled') || readonly;
1683
+ choose.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
1684
+ const zone = choose.parentElement;
1685
+ // read only, there is nothing to choose: only the files are left
1686
+ zone.hidden = readonly;
1687
+ zone.querySelector('.tb-upload-hint').textContent = own(many ? 'drop-files' : 'drop-file');
1688
+ const picker = zone.querySelector('input');
1689
+ picker.multiple = many;
1690
+ picker.accept = pickerAccept(acceptList(f));
1691
+ m.error.textContent = err ?? '';
1692
+ const v = get(f, 'value');
1693
+ const files = v.t === K.Block ? v.s.data.slice(v.i).filter(x => x.t === K.Object) : [];
1694
+ const lang = activeLanguage(host.rt);
1695
+ const items = files.map((file, i) => {
1696
+ const li = el('li');
1697
+ // a file kept elsewhere has a url: its name opens it, and an image shows itself small
1698
+ const url = str(file, 'url');
1699
+ const href = url !== null ? webHref(url) : null;
1700
+ const name = el(href !== null ? 'a' : 'span', 'tb-upload-name');
1701
+ name.textContent = str(file, 'name') ?? '';
1702
+ if (name instanceof HTMLAnchorElement && href !== null) {
1703
+ name.href = href;
1704
+ name.target = '_blank';
1705
+ name.rel = 'noopener';
1706
+ }
1707
+ if (href !== null && (str(file, 'type') ?? '').startsWith('image/')) {
1708
+ const thumb = el('img', 'tb-upload-thumb');
1709
+ thumb.src = href;
1710
+ thumb.alt = '';
1711
+ li.append(thumb);
1712
+ }
1713
+ const size = el('span', 'tb-upload-size');
1714
+ const n = get(file, 'size');
1715
+ size.textContent = n.t === K.Integer ? fileSize(Number(n.v), lang) : '';
1716
+ if (readonly) {
1717
+ li.append(name, size);
1718
+ return li;
1719
+ }
1720
+ const remove = el('button', 'tb-upload-remove');
1721
+ remove.type = 'button';
1722
+ remove.disabled = choose.disabled;
1723
+ remove.setAttribute('aria-label', own('remove-file', name.textContent ?? ''));
1724
+ const x = icon('close');
1725
+ if (x !== null)
1726
+ remove.append(x);
1727
+ remove.addEventListener('click', () => {
1728
+ choose.focus();
1729
+ void fire('ui-remove-file', f, int(i + 1));
1730
+ });
1731
+ li.append(name, size, remove);
1732
+ return li;
1733
+ });
1734
+ m.box.replaceChildren(...items);
1735
+ m.box.hidden = items.length === 0;
1736
+ syncSent(m);
1737
+ }
1738
+ let lookup = null;
1739
+ let lookupTimer;
1740
+ const LOOKUP_WAIT_MS = 200;
1741
+ function lookupValues(f) {
1742
+ const v = get(f, 'value');
1743
+ return v.t === K.None ? [] : v.t === K.Block ? v.s.data.slice(v.i) : [v];
1744
+ }
1745
+ function lookupText(f, v) {
1746
+ const known = get(f, 'known');
1747
+ const t = known.t === K.Map ? mapAt(known, form(v)) : null;
1748
+ return t !== null ? translate(t, host.rt) : form(v);
1749
+ }
1750
+ /** Where a readonly lookup's value links to, from its `links` map, or null to show it as text. */
1751
+ function lookupHref(f, v) {
1752
+ const links = get(f, 'links');
1753
+ if (!flag(f, 'readonly') || links.t !== K.Map)
1754
+ return null;
1755
+ const to = mapAt(links, form(v));
1756
+ if (to === null)
1757
+ return null;
1758
+ if (to.t === K.LitWord)
1759
+ return screenHref({ ...to, t: K.Word });
1760
+ if (to.t === K.LitPath)
1761
+ return screenHref({ ...to, t: K.Path });
1762
+ return screenHref(to) ?? (to.t === K.Url || to.t === K.File || to.t === K.String ? form(to) : null);
1763
+ }
1764
+ function buildLookup(face, m) {
1765
+ const id = `tb-${nextId++}`;
1766
+ const wrap = el('div', 'tb-field');
1767
+ const label = el('label', 'tb-label');
1768
+ label.htmlFor = id;
1769
+ const control = el('div', 'tb-control');
1770
+ const box = el('div', 'tb-lookup');
1771
+ const chosen = el('ul', 'tb-lookup-chosen');
1772
+ const input = el('input', 'tb-input');
1773
+ input.id = id;
1774
+ input.type = 'text';
1775
+ input.autocomplete = 'off';
1776
+ input.setAttribute('role', 'combobox');
1777
+ input.setAttribute('aria-autocomplete', 'list');
1778
+ input.setAttribute('aria-expanded', 'false');
1779
+ const name = word(face, 'name');
1780
+ if (name !== null)
1781
+ input.name = name;
1782
+ const error = el('div', 'tb-error');
1783
+ error.id = `${id}-error`;
1784
+ error.setAttribute('aria-live', 'polite');
1785
+ input.setAttribute('aria-describedby', error.id);
1786
+ input.addEventListener('click', () => {
1787
+ if (lookup?.m !== m)
1788
+ openLookup(m, input, '');
1789
+ });
1790
+ input.addEventListener('input', () => {
1791
+ if (lookup?.m !== m)
1792
+ openLookup(m, input, null);
1793
+ clearTimeout(lookupTimer);
1794
+ lookupTimer = setTimeout(() => void fire('ui-lookup-search', face, string(input.value)), LOOKUP_WAIT_MS);
1795
+ });
1796
+ input.addEventListener('keydown', ev => lookupKey(m, input, ev));
1797
+ input.addEventListener('blur', () => {
1798
+ closeLookup();
1799
+ // what was typed is not a value: emptied, a lookup has none; else it goes back to what it had
1800
+ if (input.readOnly)
1801
+ return;
1802
+ const many = flag(face, 'multiple');
1803
+ const emptied = !many && input.value === '' && get(face, 'value').t !== K.None;
1804
+ if (emptied)
1805
+ void fire('ui-input', face, NONE);
1806
+ else
1807
+ input.value = many ? '' : lookupValues(face).map(v => lookupText(face, v)).join('');
1808
+ void fire('ui-blur', face);
1809
+ });
1810
+ box.append(chosen, input);
1811
+ control.append(box, error);
1812
+ wrap.append(label, control);
1813
+ m.input = input;
1814
+ m.label = label;
1815
+ m.error = error;
1816
+ m.box = chosen;
1817
+ return wrap;
1818
+ }
1819
+ function syncLookup(m, err) {
1820
+ const f = m.face;
1821
+ const input = m.input;
1822
+ const label = m.label;
1823
+ label.textContent = str(f, 'text') ?? '';
1824
+ label.classList.toggle('tb-required', required(f));
1825
+ const many = flag(f, 'multiple');
1826
+ const readonly = flag(f, 'readonly');
1827
+ const off = flag(f, 'disabled');
1828
+ const values = lookupValues(f);
1829
+ // readonly values with a link are shown as chips, so that each one is a real link
1830
+ const chips = many || values.some(v => lookupHref(f, v) !== null);
1831
+ input.readOnly = readonly;
1832
+ input.disabled = off;
1833
+ input.hidden = chips && readonly && values.length > 0;
1834
+ input.setAttribute('aria-required', required(f) ? 'true' : 'false');
1835
+ input.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
1836
+ const hint = str(f, 'hint');
1837
+ if (hint !== null)
1838
+ input.placeholder = hint;
1839
+ m.error.textContent = err ?? '';
1840
+ if (chips) {
1841
+ m.box.replaceChildren(...values.map((v, i) => {
1842
+ const li = el('li', 'tb-lookup-chip');
1843
+ const href = lookupHref(f, v);
1844
+ const shown = el(href !== null ? 'a' : 'span', href !== null ? 'tb-link' : '');
1845
+ if (shown instanceof HTMLAnchorElement)
1846
+ shown.href = href;
1847
+ shown.textContent = lookupText(f, v);
1848
+ li.append(shown);
1849
+ if (!readonly && !off) {
1850
+ const remove = el('button', 'tb-upload-remove');
1851
+ remove.type = 'button';
1852
+ remove.setAttribute('aria-label', own('remove-value', shown.textContent));
1853
+ const x = icon('close');
1854
+ if (x !== null)
1855
+ remove.append(x);
1856
+ remove.addEventListener('click', () => {
1857
+ input.focus();
1858
+ void fire('ui-lookup-remove', f, int(i + 1));
1859
+ });
1860
+ li.append(remove);
1861
+ }
1862
+ return li;
1863
+ }));
1864
+ }
1865
+ else {
1866
+ // a single value loses its chip when it stops being readonly or linked
1867
+ m.box.replaceChildren();
1868
+ const want = values.map(v => lookupText(f, v)).join('');
1869
+ if (document.activeElement !== input && input.value !== want)
1870
+ input.value = want;
1871
+ }
1872
+ if (lookup?.m === m)
1873
+ renderLookup();
1874
+ }
1875
+ function openLookup(m, input, query) {
1876
+ if (input.readOnly || input.disabled)
1877
+ return;
1878
+ closeLookup();
1879
+ const list = el('ul', 'tb-lookup-list');
1880
+ list.id = `tb-${nextId++}`;
1881
+ list.setAttribute('role', 'listbox');
1882
+ list.setAttribute('popover', 'manual');
1883
+ // choosing with the pointer must not take the focus away from the field
1884
+ list.addEventListener('pointerdown', ev => ev.preventDefault());
1885
+ lookup = { m, list, shown: null, items: [], active: -1 };
1886
+ input.setAttribute('aria-expanded', 'true');
1887
+ input.setAttribute('aria-controls', list.id);
1888
+ // a modal dialog makes all outside it inert: there, a list in the body would take no clicks
1889
+ (input.closest('dialog') ?? document.body).append(list);
1890
+ list.showPopover?.();
1891
+ placeLookup();
1892
+ if (query !== null)
1893
+ void fire('ui-lookup-search', m.face, string(query));
1894
+ }
1895
+ function placeLookup() {
1896
+ if (lookup === null)
1897
+ return;
1898
+ const { list, m } = lookup;
1899
+ const r = m.input.getBoundingClientRect();
1900
+ list.style.width = `${r.width}px`;
1901
+ list.style.left = `${r.left}px`;
1902
+ const height = list.getBoundingClientRect().height;
1903
+ list.style.top = `${r.bottom + 4 + height > innerHeight - 8 ? Math.max(8, r.top - 4 - height) : r.bottom + 4}px`;
1904
+ }
1905
+ function closeLookup() {
1906
+ clearTimeout(lookupTimer);
1907
+ if (lookup === null)
1908
+ return;
1909
+ const { list, m } = lookup;
1910
+ lookup = null;
1911
+ list.hidePopover?.();
1912
+ list.remove();
1913
+ m.input.setAttribute('aria-expanded', 'false');
1914
+ m.input.removeAttribute('aria-controls');
1915
+ m.input.removeAttribute('aria-activedescendant');
1916
+ }
1917
+ function renderLookup() {
1918
+ if (lookup === null)
1919
+ return;
1920
+ const open = lookup;
1921
+ const options = get(open.m.face, 'options');
1922
+ // what is on show stays until the search answers; a query still on its way shows nothing new
1923
+ if (options.t !== K.Block || options === open.shown)
1924
+ return;
1925
+ if (open.shown === null && get(open.m.face, 'query').t === K.None)
1926
+ return;
1927
+ open.shown = options;
1928
+ const taken = new Set(flag(open.m.face, 'multiple') ? lookupValues(open.m.face).map(v => form(v)) : []);
1929
+ open.items = optionsOf(open.m.face).filter(o => !taken.has(optionValue(o)));
1930
+ open.active = -1;
1931
+ open.list.replaceChildren(...open.items.map((o, i) => {
1932
+ const li = el('li', 'tb-lookup-option');
1933
+ li.id = `${open.list.id}-${i}`;
1934
+ li.setAttribute('role', 'option');
1935
+ li.setAttribute('aria-selected', 'false');
1936
+ li.textContent = optionText(o);
1937
+ li.addEventListener('click', () => pickLookup(o));
1938
+ return li;
1939
+ }));
1940
+ if (open.items.length === 0) {
1941
+ const none = el('li', 'tb-lookup-none');
1942
+ none.textContent = own('no-matches');
1943
+ open.list.append(none);
1944
+ }
1945
+ placeLookup();
1946
+ }
1947
+ function pickLookup(option) {
1948
+ if (lookup === null)
1949
+ return;
1950
+ const { m } = lookup;
1951
+ const input = m.input;
1952
+ closeLookup();
1953
+ input.value = flag(m.face, 'multiple') ? '' : optionText(option);
1954
+ void fire('ui-lookup-pick', m.face, option);
1955
+ }
1956
+ function moveLookup(by) {
1957
+ if (lookup === null || lookup.items.length === 0)
1958
+ return;
1959
+ const { list, items, m } = lookup;
1960
+ const at = lookup.active < 0 && by < 0 ? items.length - 1 : (lookup.active + by + items.length) % items.length;
1961
+ list.children[lookup.active]?.setAttribute('aria-selected', 'false');
1962
+ lookup.active = at;
1963
+ const li = list.children[at];
1964
+ li.setAttribute('aria-selected', 'true');
1965
+ li.scrollIntoView({ block: 'nearest' });
1966
+ m.input.setAttribute('aria-activedescendant', li.id);
1967
+ }
1968
+ function lookupKey(m, input, ev) {
1969
+ const open = lookup?.m === m;
1970
+ const stop = () => { ev.preventDefault(); ev.stopPropagation(); };
1971
+ switch (ev.key) {
1972
+ case 'ArrowDown':
1973
+ case 'ArrowUp':
1974
+ stop();
1975
+ if (open)
1976
+ moveLookup(ev.key === 'ArrowDown' ? 1 : -1);
1977
+ else
1978
+ openLookup(m, input, '');
1979
+ break;
1980
+ case 'Enter':
1981
+ if (!open)
1982
+ break;
1983
+ // with its list open, Enter chooses: it never sends the form
1984
+ stop();
1985
+ if (lookup.active >= 0)
1986
+ pickLookup(lookup.items[lookup.active]);
1987
+ break;
1988
+ case 'Escape':
1989
+ if (open) {
1990
+ stop();
1991
+ closeLookup();
1992
+ }
1993
+ break;
1994
+ case 'Backspace':
1995
+ if (flag(m.face, 'multiple') && input.value === '' && !input.readOnly) {
1996
+ const n = lookupValues(m.face).length;
1997
+ if (n > 0)
1998
+ void fire('ui-lookup-remove', m.face, int(n));
1999
+ }
2000
+ break;
2001
+ }
2002
+ }
2003
+ function buildProgress(m) {
2004
+ const wrap = el('div', 'tb-progress-wrap');
2005
+ const label = el('span', 'tb-progress-label');
2006
+ label.id = `tb-${nextId++}`;
2007
+ const track = el('div', 'tb-progress');
2008
+ track.setAttribute('role', 'progressbar');
2009
+ track.setAttribute('aria-valuemin', '0');
2010
+ track.setAttribute('aria-valuemax', '100');
2011
+ track.append(el('div', 'tb-progress-bar'));
2012
+ wrap.append(label, track);
2013
+ m.label = label;
2014
+ m.box = track;
2015
+ return wrap;
2016
+ }
2017
+ /** A progress value as a fraction, or null while it is unknown. */
2018
+ function fraction(v) {
2019
+ const n = v.t === K.Percent || v.t === K.Decimal ? v.v : v.t === K.Integer ? Number(v.v) : null;
2020
+ return n === null || Number.isNaN(n) ? null : Math.min(1, Math.max(0, n));
2021
+ }
2022
+ function syncProgress(m) {
2023
+ const t = str(m.face, 'text');
2024
+ const label = m.label;
2025
+ label.textContent = t ?? '';
2026
+ label.hidden = t === null;
2027
+ const track = m.box;
2028
+ if (t !== null)
2029
+ track.setAttribute('aria-labelledby', label.id);
2030
+ else
2031
+ track.removeAttribute('aria-labelledby');
2032
+ const n = fraction(get(m.face, 'value'));
2033
+ track.classList.toggle('tb-indeterminate', n === null);
2034
+ const bar = track.firstChild;
2035
+ if (n === null) {
2036
+ track.removeAttribute('aria-valuenow');
2037
+ bar.style.removeProperty('width');
2038
+ }
2039
+ else {
2040
+ track.setAttribute('aria-valuenow', String(Math.round(n * 100)));
2041
+ bar.style.width = `${n * 100}%`;
2042
+ }
2043
+ }
2044
+ // --- drawings and charts ---------------------------------------------------------------
2045
+ const SVG_NS = 'http://www.w3.org/2000/svg';
2046
+ function svgNode(e) {
2047
+ const n = document.createElementNS(SVG_NS, e.tag);
2048
+ for (const [k, v] of Object.entries(e.attrs))
2049
+ n.setAttribute(k, v);
2050
+ if (e.text !== undefined)
2051
+ n.textContent = e.text;
2052
+ for (const k of e.kids)
2053
+ n.append(svgNode(k));
2054
+ return n;
2055
+ }
2056
+ /** A canvas: one SVG whose viewBox is the canvas's extent, as wide as it fits up to that. */
2057
+ function buildCanvas(m) {
2058
+ const node = el('div', 'tb-canvas');
2059
+ const svg = document.createElementNS(SVG_NS, 'svg');
2060
+ node.append(svg);
2061
+ m.kids = svg;
2062
+ return node;
2063
+ }
2064
+ function syncCanvas(m) {
2065
+ const svg = m.kids;
2066
+ const ext = get(m.face, 'extent');
2067
+ const [w, h] = ext.t === K.Pair ? [ext.x, ext.y] : [300, 150];
2068
+ svg.setAttribute('viewBox', `0 0 ${w} ${h}`);
2069
+ svg.setAttribute('width', String(w));
2070
+ svg.setAttribute('height', String(h));
2071
+ // with a text, the drawing is a picture with that name; without, it is decoration
2072
+ const t = str(m.face, 'text');
2073
+ if (t !== null) {
2074
+ svg.setAttribute('role', 'img');
2075
+ svg.setAttribute('aria-label', t);
2076
+ svg.removeAttribute('aria-hidden');
2077
+ }
2078
+ else {
2079
+ svg.removeAttribute('role');
2080
+ svg.removeAttribute('aria-label');
2081
+ svg.setAttribute('aria-hidden', 'true');
2082
+ }
2083
+ const { kids, error } = drawSvg(get(m.face, 'draw'));
2084
+ if (error !== null)
2085
+ console.warn(`Trebol: ${error}`);
2086
+ svg.replaceChildren(...kids.map(svgNode));
2087
+ }
2088
+ const CHART_HEIGHT = { small: 160, medium: 240, large: 360 };
2089
+ /**
2090
+ * A chart: its text as a caption, the plot, a legend, and the same numbers as a
2091
+ * table that only a screen reader reads. It is drawn at the width it gets, and
2092
+ * again when that changes, so its text stays the size of the page's.
2093
+ */
2094
+ function buildChart(m) {
2095
+ const node = el('figure', 'tb-chart');
2096
+ const caption = el('figcaption', 'tb-chart-caption');
2097
+ const plot = el('div', 'tb-chart-plot');
2098
+ const svg = document.createElementNS(SVG_NS, 'svg');
2099
+ svg.setAttribute('aria-hidden', 'true');
2100
+ plot.append(svg);
2101
+ const legend = el('ul', 'tb-chart-legend');
2102
+ const table = el('table', 'tb-sr-only');
2103
+ const empty = el('p', 'tb-chart-empty');
2104
+ node.append(caption, plot, legend, empty, table);
2105
+ const parts = { caption, plot, svg, legend, table, empty, width: 0 };
2106
+ m.kids = parts;
2107
+ if (typeof ResizeObserver !== 'undefined') {
2108
+ new ResizeObserver(() => {
2109
+ if (plot.clientWidth !== parts.width)
2110
+ drawChart(m);
2111
+ }).observe(plot);
2112
+ }
2113
+ return node;
2114
+ }
2115
+ /** A cell of a chart as a number, or null. */
2116
+ function chartNumber(v) {
2117
+ if (v.t === K.Integer)
2118
+ return Number(v.v);
2119
+ if (v.t === K.Decimal || v.t === K.Percent)
2120
+ return v.v;
2121
+ if (v.t === K.Money)
2122
+ return decToNumber(v.v);
2123
+ return null;
2124
+ }
2125
+ /** How a number of the chart shows: as the values it stands for, money as money and percent as percent. */
2126
+ function chartFormat(sample) {
2127
+ return n => {
2128
+ if (sample !== null && sample.t === K.Money) {
2129
+ const d = decFromNumber(Math.round(n * 100) / 100);
2130
+ if (d !== null)
2131
+ return display(money(d, sample.cur));
2132
+ }
2133
+ if (sample !== null && sample.t === K.Percent)
2134
+ return display({ t: K.Percent, v: n });
2135
+ return display(Number.isInteger(n) ? { t: K.Integer, v: n } : { t: K.Decimal, v: n });
2136
+ };
2137
+ }
2138
+ function syncChart(m) {
2139
+ const p = m.kids;
2140
+ const t = str(m.face, 'text');
2141
+ p.caption.textContent = t ?? '';
2142
+ p.caption.hidden = t === null;
2143
+ drawChart(m);
2144
+ }
2145
+ function drawChart(m) {
2146
+ const f = m.face;
2147
+ const p = m.kids;
2148
+ const cols = columns(f);
2149
+ const data = get(f, 'data');
2150
+ const rows = data.t === K.Block ? data.s.data.slice(data.i) : [];
2151
+ const kind = (word(f, 'kind') ?? 'bar');
2152
+ const labels = rows.map(r => cellText(rowField(r, cols[0]?.sym ?? intern('label'))));
2153
+ let sample = null;
2154
+ const series = cols.slice(1).map((c, k) => ({
2155
+ name: c.label,
2156
+ color: SERIES_COLORS[k % SERIES_COLORS.length],
2157
+ values: rows.map(r => {
2158
+ const v = rowField(r, c.sym);
2159
+ const n = chartNumber(v);
2160
+ if (n !== null && sample === null)
2161
+ sample = v;
2162
+ return n;
2163
+ }),
2164
+ }));
2165
+ const format = chartFormat(sample);
2166
+ const nothing = rows.length === 0 || series.length === 0;
2167
+ p.empty.hidden = !nothing;
2168
+ p.plot.hidden = nothing;
2169
+ if (nothing) {
2170
+ p.empty.textContent = own('empty');
2171
+ p.legend.replaceChildren();
2172
+ p.table.replaceChildren();
2173
+ return;
2174
+ }
2175
+ const width = p.plot.clientWidth || 600;
2176
+ const height = CHART_HEIGHT[word(f, 'size') ?? 'medium'] ?? 240;
2177
+ p.width = p.plot.clientWidth;
2178
+ // no width of its own: it takes the plot's, so it never widens what holds it
2179
+ p.svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
2180
+ p.svg.replaceChildren(...chartSvg({ kind, labels, series, stacked: flag(f, 'stacked'), width, height, format }).map(svgNode));
2181
+ // the legend names the series, or a pie's slices
2182
+ const keys = kind === 'pie' ? labels.map((l, i) => [l, pieColor(i)]) : series.length > 1 ? series.map(s => [s.name, s.color]) : [];
2183
+ p.legend.replaceChildren(...keys.map(([name, color]) => {
2184
+ const li = el('li', 'tb-chart-key');
2185
+ const swatch = el('span', 'tb-chart-swatch');
2186
+ swatch.style.setProperty('--tb-swatch', color);
2187
+ li.append(swatch, name);
2188
+ return li;
2189
+ }));
2190
+ p.legend.hidden = keys.length === 0;
2191
+ // the same numbers for a screen reader
2192
+ const cap = el('caption');
2193
+ cap.textContent = str(f, 'text') ?? '';
2194
+ const head = el('tr');
2195
+ for (const c of cols) {
2196
+ const th = el('th');
2197
+ th.textContent = c.label;
2198
+ head.append(th);
2199
+ }
2200
+ const body = rows.map(r => {
2201
+ const tr = el('tr');
2202
+ for (const c of cols) {
2203
+ const td = el('td');
2204
+ td.textContent = cellText(rowField(r, c.sym));
2205
+ tr.append(td);
2206
+ }
2207
+ return tr;
2208
+ });
2209
+ p.table.replaceChildren(cap, el('thead'), el('tbody'));
2210
+ p.table.tHead.append(head);
2211
+ p.table.tBodies[0].append(...body);
2212
+ }
2213
+ function syncIcon(m) {
2214
+ const name = iconName(m.face) ?? '';
2215
+ const label = str(m.face, 'text');
2216
+ const key = `${name} ${label ?? ''}`;
2217
+ if (m.el.dataset['icon'] === key)
2218
+ return;
2219
+ m.el.dataset['icon'] = key;
2220
+ const svg = name !== '' ? icon(name, label) : null;
2221
+ m.el.replaceChildren(...(svg !== null ? [svg] : []));
2222
+ }
2223
+ /** No rule applies to a read-only face, so it never asks for a value. */
2224
+ function required(f) {
2225
+ return hasRule(f, 'required') && !flag(f, 'readonly');
2226
+ }
2227
+ function syncRadio(m, err) {
2228
+ const f = m.face;
2229
+ m.label.textContent = str(f, 'text') ?? '';
2230
+ m.label.classList.toggle('tb-required', required(f));
2231
+ const v = get(f, 'value');
2232
+ const want = v.t === K.None ? null : form(v);
2233
+ for (const r of m.radios) {
2234
+ r.checked = r.value === want;
2235
+ r.disabled = flag(f, 'disabled') || flag(f, 'readonly');
2236
+ }
2237
+ const group = m.radios[0]?.closest('[role="radiogroup"]');
2238
+ group?.querySelectorAll('.tb-radio-title').forEach((t, i) => {
2239
+ const g = entriesOf(f).filter(isGroup)[i];
2240
+ if (g)
2241
+ t.textContent = translate(g.title, host.rt);
2242
+ });
2243
+ group?.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
2244
+ group?.setAttribute('aria-required', required(f) ? 'true' : 'false');
2245
+ m.error.textContent = err ?? '';
2246
+ }
2247
+ // --- rows ---------------------------------------------------------------------------
2248
+ //
2249
+ // The dialect makes the rows as faces; the host only draws them, as one line each
2250
+ // with the labels of the first line as the headers, or as cards on narrow screens.
2251
+ function buildRowsField(m) {
2252
+ const id = `tb-${nextId++}`;
2253
+ const wrap = el('div', 'tb-field');
2254
+ const label = el('div', 'tb-label');
2255
+ label.id = id;
2256
+ const control = el('div', 'tb-control');
2257
+ const box = el('div', 'tb-rows');
2258
+ box.setAttribute('role', 'group');
2259
+ box.setAttribute('aria-labelledby', id);
2260
+ const error = el('div', 'tb-error');
2261
+ error.setAttribute('aria-live', 'polite');
2262
+ control.append(box, error);
2263
+ wrap.append(label, control);
2264
+ m.label = label;
2265
+ m.error = error;
2266
+ m.box = box;
2267
+ return wrap;
2268
+ }
2269
+ function syncRowsField(m, err) {
2270
+ const f = m.face;
2271
+ m.label.textContent = str(f, 'text') ?? '';
2272
+ m.label.classList.toggle('tb-required', required(f));
2273
+ m.error.textContent = err ?? '';
2274
+ // code gave it a new value or changed its flags: the dialect makes the rows again
2275
+ const v = get(f, 'value');
2276
+ const now = [v.t === K.Block ? v.s : null, flag(f, 'readonly'), flag(f, 'disabled')];
2277
+ const was = m.shown;
2278
+ if (was === undefined || now.some((x, i) => x !== was[i])) {
2279
+ m.shown = now;
2280
+ void fire('ui-rows', f);
2281
+ }
2282
+ }
2283
+ /** Puts the rows in their new order, keeping the nodes (and the focus) of the ones that stay. */
2284
+ function placeEntries(m) {
2285
+ const box = m.box;
2286
+ const faces = children(m.face);
2287
+ const active = document.activeElement;
2288
+ const fresh = [];
2289
+ const nodes = faces.map(c => {
2290
+ const old = byCtx.get(c.ctx);
2291
+ if (old !== undefined && old.el.parentElement === box)
2292
+ return old.el;
2293
+ const n = build(c);
2294
+ fresh.push(n);
2295
+ return n;
2296
+ });
2297
+ let cursor = box.firstChild;
2298
+ for (const n of nodes) {
2299
+ if (n === cursor)
2300
+ cursor = cursor.nextSibling;
2301
+ else
2302
+ box.insertBefore(n, cursor);
2303
+ }
2304
+ while (cursor !== null) {
2305
+ const next = cursor.nextSibling;
2306
+ box.removeChild(cursor);
2307
+ cursor = next;
2308
+ }
2309
+ const add = nodes[nodes.length - 1];
2310
+ // the button pressed went away with its row, or a row was just added
2311
+ if (active !== null && active !== document.body && !active.isConnected)
2312
+ add?.focus();
2313
+ else if (fresh.length === 1 && (active === add || active === document.body)) {
2314
+ fresh[0].querySelector('input, textarea, select, [contenteditable="true"]')?.focus();
2315
+ }
2316
+ }
2317
+ // --- rich text -----------------------------------------------------------------------
2318
+ //
2319
+ // An editable box whose value is Markdown (see markdown.ts). The box is drawn from
2320
+ // the tree with text nodes and read back the same way; pasting takes only the text.
2321
+ const RICH_TOOLS = [
2322
+ ['bold', 'bold'], ['italic', 'italic'], ['heading', 'heading'],
2323
+ ['list', 'bullet-list'], ['list-ordered', 'number-list'], ['link', 'link'],
2324
+ ];
2325
+ function inlineNodes(items) {
2326
+ return items.flatMap((x) => {
2327
+ switch (x.k) {
2328
+ case 'text': return [document.createTextNode(x.text)];
2329
+ case 'br': return [el('br')];
2330
+ case 'b':
2331
+ case 'i': {
2332
+ const e = el(x.k);
2333
+ e.append(...inlineNodes(x.kids));
2334
+ return [e];
2335
+ }
2336
+ case 'a': {
2337
+ if (!safeHref(x.href))
2338
+ return inlineNodes(x.kids);
2339
+ const a = el('a');
2340
+ a.href = x.href;
2341
+ a.rel = 'noopener noreferrer';
2342
+ a.target = '_blank';
2343
+ a.append(...inlineNodes(x.kids));
2344
+ return [a];
2345
+ }
2346
+ }
2347
+ });
2348
+ }
2349
+ function blockNodes(blocks) {
2350
+ return blocks.map(b => {
2351
+ if (b.k === 'p' || b.k === 'h') {
2352
+ const e = b.k === 'p' ? el('p') : el(`h${b.level}`);
2353
+ e.append(...inlineNodes(b.kids));
2354
+ return e;
2355
+ }
2356
+ const list = el(b.k);
2357
+ for (const item of b.items) {
2358
+ const li = el('li');
2359
+ li.append(...inlineNodes(item));
2360
+ list.append(li);
2361
+ }
2362
+ return list;
2363
+ });
2364
+ }
2365
+ function readInline(nodes) {
2366
+ const out = [];
2367
+ for (const n of nodes) {
2368
+ if (n.nodeType === Node.TEXT_NODE) {
2369
+ const t = (n.textContent ?? '').replace(/\u00a0/g, ' ').replace(/[\n\r]+/g, ' ');
2370
+ const last = out[out.length - 1];
2371
+ if (t === '')
2372
+ continue;
2373
+ if (last?.k === 'text')
2374
+ last.text += t;
2375
+ else
2376
+ out.push({ k: 'text', text: t });
2377
+ }
2378
+ else if (n instanceof HTMLElement) {
2379
+ const kids = readInline(n.childNodes);
2380
+ switch (n.tagName) {
2381
+ case 'BR':
2382
+ out.push({ k: 'br' });
2383
+ break;
2384
+ case 'B':
2385
+ case 'STRONG':
2386
+ if (kids.length > 0)
2387
+ out.push({ k: 'b', kids });
2388
+ break;
2389
+ case 'I':
2390
+ case 'EM':
2391
+ if (kids.length > 0)
2392
+ out.push({ k: 'i', kids });
2393
+ break;
2394
+ case 'A':
2395
+ if (kids.length > 0)
2396
+ out.push({ k: 'a', href: n.getAttribute('href') ?? '', kids });
2397
+ break;
2398
+ default: out.push(...kids);
2399
+ }
2400
+ }
2401
+ }
2402
+ // the browser ends an empty or last line with a <br> that shows nothing
2403
+ while (out[out.length - 1]?.k === 'br')
2404
+ out.pop();
2405
+ return out;
2406
+ }
2407
+ const RICH_BLOCK = /^(P|DIV|H[1-6]|UL|OL|BLOCKQUOTE|SECTION)$/;
2408
+ function readBlocks(box) {
2409
+ const out = [];
2410
+ let loose = [];
2411
+ const flush = () => {
2412
+ const kids = readInline(loose);
2413
+ if (kids.length > 0)
2414
+ out.push({ k: 'p', kids });
2415
+ loose = [];
2416
+ };
2417
+ for (const n of box.childNodes) {
2418
+ if (!(n instanceof HTMLElement) || !RICH_BLOCK.test(n.tagName)) {
2419
+ loose.push(n);
2420
+ continue;
2421
+ }
2422
+ flush();
2423
+ if (n.tagName === 'UL' || n.tagName === 'OL') {
2424
+ const items = [...n.children].map(li => readInline(li.childNodes)).filter(x => x.length > 0);
2425
+ if (items.length > 0)
2426
+ out.push({ k: n.tagName === 'UL' ? 'ul' : 'ol', items });
2427
+ }
2428
+ else if (n.tagName === 'DIV' || n.tagName === 'SECTION' || n.tagName === 'BLOCKQUOTE') {
2429
+ out.push(...readBlocks(n));
2430
+ }
2431
+ else {
2432
+ const kids = readInline(n.childNodes);
2433
+ if (kids.length === 0)
2434
+ continue;
2435
+ if (n.tagName === 'P')
2436
+ out.push({ k: 'p', kids });
2437
+ else
2438
+ out.push({ k: 'h', level: Math.min(3, Number(n.tagName[1])), kids });
2439
+ }
2440
+ }
2441
+ flush();
2442
+ return out;
2443
+ }
2444
+ function buildRich(face, m) {
2445
+ const id = `tb-${nextId++}`;
2446
+ const wrap = el('div', 'tb-field');
2447
+ const label = el('div', 'tb-label');
2448
+ label.id = id;
2449
+ const control = el('div', 'tb-control');
2450
+ const shell = el('div', 'tb-rich');
2451
+ const tools = el('div', 'tb-rich-tools');
2452
+ tools.setAttribute('role', 'toolbar');
2453
+ const box = el('div', 'tb-input tb-rich-box');
2454
+ box.setAttribute('role', 'textbox');
2455
+ box.setAttribute('aria-multiline', 'true');
2456
+ box.setAttribute('aria-labelledby', id);
2457
+ const linkRow = el('div', 'tb-rich-link');
2458
+ linkRow.hidden = true;
2459
+ const linkInput = el('input', 'tb-input');
2460
+ linkInput.type = 'url';
2461
+ const linkOk = el('button', 'tb-button tb-small');
2462
+ linkOk.type = 'button';
2463
+ linkRow.append(linkInput, linkOk);
2464
+ const error = el('div', 'tb-error');
2465
+ error.id = `${id}-error`;
2466
+ error.setAttribute('aria-live', 'polite');
2467
+ box.setAttribute('aria-describedby', error.id);
2468
+ label.addEventListener('click', () => box.focus());
2469
+ const changed = () => {
2470
+ const md = printMd(readBlocks(box));
2471
+ if (md === m.shown)
2472
+ return;
2473
+ m.shown = md;
2474
+ void fire('ui-input', face, md === '' ? NONE : string(md));
2475
+ };
2476
+ box.addEventListener('input', changed);
2477
+ box.addEventListener('paste', ev => {
2478
+ ev.preventDefault();
2479
+ document.execCommand('insertText', false, ev.clipboardData?.getData('text/plain') ?? '');
2480
+ });
2481
+ box.addEventListener('drop', ev => ev.preventDefault());
2482
+ wrap.addEventListener('focusout', ev => {
2483
+ if (!wrap.contains(ev.relatedTarget))
2484
+ void fire('ui-blur', face);
2485
+ });
2486
+ let saved = null;
2487
+ const inHeading = () => {
2488
+ const n = getSelection()?.anchorNode ?? null;
2489
+ return (n instanceof Element ? n : n?.parentElement)?.closest('h1, h2, h3') != null;
2490
+ };
2491
+ const command = (what) => {
2492
+ box.focus();
2493
+ switch (what) {
2494
+ case 'bold':
2495
+ case 'italic':
2496
+ document.execCommand(what);
2497
+ break;
2498
+ case 'heading':
2499
+ document.execCommand('formatBlock', false, inHeading() ? 'P' : 'H2');
2500
+ break;
2501
+ case 'bullet-list':
2502
+ document.execCommand('insertUnorderedList');
2503
+ break;
2504
+ case 'number-list':
2505
+ document.execCommand('insertOrderedList');
2506
+ break;
2507
+ case 'link': {
2508
+ const s = getSelection();
2509
+ saved = s !== null && s.rangeCount > 0 && box.contains(s.anchorNode) ? s.getRangeAt(0).cloneRange() : null;
2510
+ linkRow.hidden = false;
2511
+ linkInput.value = '';
2512
+ linkInput.removeAttribute('aria-invalid');
2513
+ linkInput.focus();
2514
+ return;
2515
+ }
2516
+ }
2517
+ changed();
2518
+ };
2519
+ for (const [name, what] of RICH_TOOLS) {
2520
+ const b = el('button', 'tb-rich-tool');
2521
+ b.type = 'button';
2522
+ b.dataset['tool'] = what;
2523
+ const svg = icon(name);
2524
+ if (svg !== null)
2525
+ b.append(svg);
2526
+ // pressing a tool keeps the selection in the text
2527
+ b.addEventListener('mousedown', ev => ev.preventDefault());
2528
+ b.addEventListener('click', () => command(what));
2529
+ tools.append(b);
2530
+ }
2531
+ const addLink = () => {
2532
+ const typed = linkInput.value.trim();
2533
+ const url = /^[a-z][a-z0-9+.-]*:/i.test(typed) ? typed : `https://${typed}`;
2534
+ if (typed === '' || !safeHref(url)) {
2535
+ linkInput.setAttribute('aria-invalid', 'true');
2536
+ return;
2537
+ }
2538
+ linkRow.hidden = true;
2539
+ box.focus();
2540
+ const s = getSelection();
2541
+ if (saved !== null && s !== null) {
2542
+ s.removeAllRanges();
2543
+ s.addRange(saved);
2544
+ }
2545
+ if (saved === null || saved.collapsed)
2546
+ document.execCommand('insertText', false, typed);
2547
+ if (saved !== null && !saved.collapsed)
2548
+ document.execCommand('createLink', false, url);
2549
+ else {
2550
+ // what was just typed becomes the link
2551
+ const r = getSelection()?.getRangeAt(0);
2552
+ if (r !== undefined) {
2553
+ const node = r.startContainer;
2554
+ const start = Math.max(0, r.startOffset - typed.length);
2555
+ const whole = document.createRange();
2556
+ whole.setStart(node, start);
2557
+ whole.setEnd(node, r.startOffset);
2558
+ s?.removeAllRanges();
2559
+ s?.addRange(whole);
2560
+ document.execCommand('createLink', false, url);
2561
+ }
2562
+ }
2563
+ changed();
2564
+ };
2565
+ linkOk.addEventListener('click', addLink);
2566
+ linkInput.addEventListener('keydown', ev => {
2567
+ if (ev.key === 'Enter') {
2568
+ ev.preventDefault();
2569
+ addLink();
2570
+ }
2571
+ else if (ev.key === 'Escape') {
2572
+ ev.stopPropagation();
2573
+ linkRow.hidden = true;
2574
+ box.focus();
2575
+ }
2576
+ });
2577
+ shell.append(tools, linkRow, box);
2578
+ control.append(shell, error);
2579
+ wrap.append(label, control);
2580
+ m.label = label;
2581
+ m.error = error;
2582
+ m.box = box;
2583
+ return wrap;
2584
+ }
2585
+ function syncRich(m, err) {
2586
+ const f = m.face;
2587
+ const box = m.box;
2588
+ m.label.textContent = str(f, 'text') ?? '';
2589
+ m.label.classList.toggle('tb-required', required(f));
2590
+ const shell = box.parentElement;
2591
+ const readonly = flag(f, 'readonly');
2592
+ const disabled = flag(f, 'disabled');
2593
+ const locked = readonly || disabled;
2594
+ box.contentEditable = locked ? 'false' : 'true';
2595
+ box.tabIndex = disabled ? -1 : 0;
2596
+ box.setAttribute('aria-readonly', locked ? 'true' : 'false');
2597
+ box.setAttribute('aria-disabled', disabled ? 'true' : 'false');
2598
+ box.setAttribute('aria-required', required(f) ? 'true' : 'false');
2599
+ box.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
2600
+ const tools = shell.querySelector('.tb-rich-tools');
2601
+ tools.hidden = locked;
2602
+ tools.setAttribute('aria-label', str(f, 'text') ?? '');
2603
+ for (const b of tools.querySelectorAll('button')) {
2604
+ const name = own(b.dataset['tool']);
2605
+ b.setAttribute('aria-label', name);
2606
+ b.title = name;
2607
+ }
2608
+ const linkRow = shell.querySelector('.tb-rich-link');
2609
+ if (locked)
2610
+ linkRow.hidden = true;
2611
+ linkRow.querySelector('input').placeholder = own('link-url');
2612
+ linkRow.querySelector('button').textContent = own('link-add');
2613
+ m.error.textContent = err ?? '';
2614
+ // never fight the user's typing: only what code set is drawn again
2615
+ const md = str(f, 'value') ?? '';
2616
+ if (md !== m.shown && document.activeElement !== box) {
2617
+ m.shown = md;
2618
+ box.replaceChildren(...blockNodes(parseMd(md)));
2619
+ }
2620
+ }
2621
+ function columns(face) {
2622
+ const c = get(face, 'columns');
2623
+ if (c.t !== K.Block)
2624
+ return [];
2625
+ const out = [];
2626
+ const d = c.s.data;
2627
+ for (let i = c.i; i + 1 < d.length; i += 2) {
2628
+ const w = d[i];
2629
+ if (w.t !== K.Word)
2630
+ continue;
2631
+ // a column of images keeps its label in a block with what it is: ["Photo" image round]
2632
+ const spec = d[i + 1];
2633
+ const parts = spec.t === K.Block ? spec.s.data.slice(spec.i) : [spec];
2634
+ const has = (name) => parts.some(p => p.t === K.Word && canon(p.sym) === canon(intern(name)));
2635
+ out.push({ sym: w.sym, word: w, label: translate(parts[0] ?? NONE, host.rt), image: has('image'), round: has('round') });
2636
+ }
2637
+ return out;
2638
+ }
2639
+ /** The picture of a row in a column of images, from an address or a file; without one, an empty place for it. */
2640
+ function thumb(box, v, round) {
2641
+ const src = v.t === K.String || v.t === K.Url || v.t === K.File ? form(v) : '';
2642
+ const old = box.querySelector(':scope > .tb-thumb');
2643
+ let pic = old;
2644
+ if (src === '' ? pic?.tagName !== 'SPAN' : pic?.tagName !== 'IMG') {
2645
+ // decoration: the row's text says who or what it is
2646
+ pic = el(src === '' ? 'span' : 'img', 'tb-thumb');
2647
+ if (src !== '')
2648
+ pic.alt = '';
2649
+ if (old !== null)
2650
+ old.replaceWith(pic);
2651
+ else
2652
+ box.prepend(pic);
2653
+ }
2654
+ if (src !== '' && pic.getAttribute('src') !== src)
2655
+ pic.src = src;
2656
+ pic.classList.toggle('tb-round', round);
2657
+ }
2658
+ function sameRow(a, b) {
2659
+ if (a.t === K.Map && b.t === K.Map)
2660
+ return a.s === b.s;
2661
+ if (a.t === K.Object && b.t === K.Object)
2662
+ return a.ctx === b.ctx;
2663
+ return false;
2664
+ }
2665
+ function cellText(v) {
2666
+ if (v.t === K.None)
2667
+ return '';
2668
+ if (v.t === K.Logic)
2669
+ return own(v.v ? 'yes' : 'no');
2670
+ return display(v);
2671
+ }
2672
+ const NUMERIC = new Set([K.Integer, K.Decimal, K.Money, K.Percent]);
2673
+ function buildRows(face, style, m) {
2674
+ const wrap = el('div', style === 'table' ? 'tb-table-wrap' : 'tb-list-wrap');
2675
+ let box;
2676
+ if (style === 'table') {
2677
+ // explicit roles keep the table semantics when narrow screens restyle it as cards
2678
+ const table = el('table', 'tb-table');
2679
+ table.setAttribute('role', 'table');
2680
+ const head = el('thead');
2681
+ const tr = el('tr');
2682
+ tr.setAttribute('role', 'row');
2683
+ const cols = columns(face);
2684
+ for (const c of cols) {
2685
+ const th = el('th');
2686
+ th.scope = 'col';
2687
+ th.setAttribute('role', 'columnheader');
2688
+ tr.append(th);
2689
+ }
2690
+ head.append(tr);
2691
+ head.addEventListener('click', ev => {
2692
+ const th = ev.target.closest('th');
2693
+ const c = th !== null && th.querySelector('.tb-sort') !== null ? cols[th.cellIndex] : undefined;
2694
+ if (c !== undefined)
2695
+ void fire('ui-sort', face, c.word);
2696
+ });
2697
+ box = el('tbody');
2698
+ // the totals row sits outside tbody, so it is never chosen, sorted or moved
2699
+ const foot = el('tfoot');
2700
+ const totals = newTableRow(cols);
2701
+ totals.className = 'tb-totals';
2702
+ foot.append(totals);
2703
+ table.append(head, box, foot);
2704
+ wrap.append(table);
2705
+ }
2706
+ else {
2707
+ box = el('ul', 'tb-list');
2708
+ wrap.append(box);
2709
+ }
2710
+ const empty = el('p', 'tb-empty');
2711
+ wrap.append(empty);
2712
+ const choose = (target) => {
2713
+ const item = target?.closest(style === 'table' ? 'tr' : 'li');
2714
+ const row = item ? rowOf.get(item) : undefined;
2715
+ if (row !== undefined)
2716
+ void fire('ui-select', face, row);
2717
+ };
2718
+ box.addEventListener('click', ev => choose(ev.target));
2719
+ box.addEventListener('keydown', ev => {
2720
+ if (ev.key === 'Enter' || ev.key === ' ') {
2721
+ ev.preventDefault();
2722
+ choose(ev.target);
2723
+ }
2724
+ });
2725
+ m.box = box;
2726
+ m.rows = new Map();
2727
+ m.empty = empty;
2728
+ return wrap;
2729
+ }
2730
+ /** Creates, updates, moves or removes only the rows whose key changed. */
2731
+ function syncRows(m) {
2732
+ const f = m.face;
2733
+ const box = m.box;
2734
+ const table = box.tagName === 'TBODY';
2735
+ const cols = columns(f);
2736
+ const data = get(f, 'data');
2737
+ let rows = data.t === K.Block ? data.s.data.slice(data.i) : [];
2738
+ if (table) {
2739
+ syncHead(f, box.parentElement, cols);
2740
+ const order = hostSorted(f);
2741
+ if (order !== null)
2742
+ rows = sortGroups(rows, order.sym, order.desc, activeLanguage(host.rt), cellText);
2743
+ }
2744
+ const keyWord = get(f, 'key');
2745
+ const key = keyWord.t === K.Word || keyWord.t === K.LitWord ? keyWord.sym : intern('id');
2746
+ const selected = get(f, 'selected');
2747
+ const selectable = handlerFor(f, 'on-select');
2748
+ box.parentElement.classList.toggle('tb-selectable', selectable);
2749
+ const old = m.rows;
2750
+ const next = new Map();
2751
+ let cursor = box.firstChild;
2752
+ rows.forEach((row, i) => {
2753
+ const group = groupRow(row);
2754
+ if (group !== null) {
2755
+ // a group's head or foot: kept by its place, never chosen, dragged or sorted
2756
+ const k = `${group.kind}#${i}`;
2757
+ let item = old.get(k);
2758
+ if (item === undefined)
2759
+ item = group.kind === 'head' ? newGroupHead(cols, table) : table ? newTableRow(cols) : newListItem();
2760
+ next.set(k, item);
2761
+ item.className = `tb-group-${group.kind} tb-level-${group.level}`;
2762
+ if (group.kind === 'head') {
2763
+ const t = translate(group.value, host.rt);
2764
+ const cell = item.firstElementChild;
2765
+ if (cell.textContent !== t)
2766
+ cell.textContent = t;
2767
+ if (table)
2768
+ cell.colSpan = Math.max(1, cols.length);
2769
+ }
2770
+ else
2771
+ fillRow(item, group.value, cols, table);
2772
+ if (item !== cursor)
2773
+ box.insertBefore(item, cursor);
2774
+ else
2775
+ cursor = cursor.nextSibling;
2776
+ return;
2777
+ }
2778
+ const id = rowField(row, key);
2779
+ let k = id.t === K.None ? `#${i}` : `${id.t}:${form(id)}`;
2780
+ if (next.has(k))
2781
+ k = `${k}#${i}`;
2782
+ let item = old.get(k);
2783
+ if (item === undefined)
2784
+ item = table ? newTableRow(cols) : newListItem();
2785
+ next.set(k, item);
2786
+ rowOf.set(item, row);
2787
+ fillRow(item, row, cols, table);
2788
+ if (selectable)
2789
+ item.tabIndex = 0;
2790
+ else
2791
+ item.removeAttribute('tabindex');
2792
+ const on = selected.t !== K.None && sameRow(selected, row);
2793
+ item.classList.toggle('tb-selected', on);
2794
+ if (selectable)
2795
+ item.setAttribute('aria-selected', on ? 'true' : 'false');
2796
+ else
2797
+ item.removeAttribute('aria-selected');
2798
+ if (item !== cursor)
2799
+ box.insertBefore(item, cursor);
2800
+ else
2801
+ cursor = cursor.nextSibling;
2802
+ });
2803
+ for (const [k, item] of old)
2804
+ if (next.get(k) !== item)
2805
+ item.remove();
2806
+ m.rows = next;
2807
+ m.empty.textContent = str(f, 'text') ?? own('empty');
2808
+ m.empty.hidden = rows.length > 0;
2809
+ }
2810
+ /** Headers in the active language; in a sortable table each is a button, with an arrow on the sorted one. */
2811
+ function syncHead(f, table, cols) {
2812
+ const sortable = flag(f, 'sortable') || handlerFor(f, 'on-sort');
2813
+ const order = sortedBy(f);
2814
+ const ths = table.tHead.rows[0].cells;
2815
+ cols.forEach((c, i) => {
2816
+ const th = ths[i];
2817
+ if (th === undefined)
2818
+ return;
2819
+ const on = order !== null && canon(order.sym) === canon(c.sym);
2820
+ let button = th.querySelector('.tb-sort');
2821
+ if (sortable && button === null) {
2822
+ button = el('button', 'tb-sort');
2823
+ button.type = 'button';
2824
+ button.append(el('span'));
2825
+ th.replaceChildren(button);
2826
+ }
2827
+ else if (!sortable && button !== null) {
2828
+ th.replaceChildren();
2829
+ button = null;
2830
+ }
2831
+ const label = button !== null ? button.firstChild : th;
2832
+ if (label.textContent !== c.label)
2833
+ label.textContent = c.label;
2834
+ if (button !== null) {
2835
+ // the button stays, so a header chosen from the keyboard keeps the focus
2836
+ const arrow = on && order.desc ? 'arrow-down' : 'arrow-up';
2837
+ const svg = button.querySelector('svg');
2838
+ if (svg?.dataset['icon'] !== arrow) {
2839
+ const next = icon(arrow);
2840
+ if (next !== null) {
2841
+ next.dataset['icon'] = arrow;
2842
+ if (svg)
2843
+ svg.replaceWith(next);
2844
+ else
2845
+ button.append(next);
2846
+ }
2847
+ }
2848
+ button.querySelector('svg')?.classList.toggle('tb-sort-idle', !on);
2849
+ }
2850
+ if (on)
2851
+ th.setAttribute('aria-sort', order.desc ? 'descending' : 'ascending');
2852
+ else
2853
+ th.removeAttribute('aria-sort');
2854
+ });
2855
+ const totals = get(f, 'totals');
2856
+ const foot = table.tFoot;
2857
+ foot.hidden = totals.t === K.None;
2858
+ if (totals.t !== K.None)
2859
+ fillRow(foot.rows[0], totals, cols, true);
2860
+ }
2861
+ /** A table's sorted facet: [column asc] or [column desc]. */
2862
+ function sortedBy(f) {
2863
+ const v = get(f, 'sorted');
2864
+ if (v.t !== K.Block || v.s.data.length - v.i < 2)
2865
+ return null;
2866
+ const c = v.s.data[v.i];
2867
+ const o = v.s.data[v.i + 1];
2868
+ if ((c.t !== K.Word && c.t !== K.LitWord) || (o.t !== K.Word && o.t !== K.LitWord))
2869
+ return null;
2870
+ return { sym: c.sym, desc: canon(o.sym) === canon(intern('desc')) };
2871
+ }
2872
+ /** The order the host applies itself: a sortable table without on-sort, which sorts for itself. */
2873
+ function hostSorted(f) {
2874
+ return flag(f, 'sortable') && !handlerFor(f, 'on-sort') ? sortedBy(f) : null;
2875
+ }
2876
+ /** A group's title, the width of the whole row. */
2877
+ function newGroupHead(cols, table) {
2878
+ if (!table) {
2879
+ const li = el('li');
2880
+ li.append(el('span'));
2881
+ return li;
2882
+ }
2883
+ const tr = el('tr');
2884
+ tr.setAttribute('role', 'row');
2885
+ const th = el('th');
2886
+ th.scope = 'rowgroup';
2887
+ th.setAttribute('role', 'rowheader');
2888
+ th.colSpan = Math.max(1, cols.length);
2889
+ tr.append(th);
2890
+ return tr;
2891
+ }
2892
+ function newTableRow(cols) {
2893
+ const tr = el('tr');
2894
+ tr.setAttribute('role', 'row');
2895
+ for (const c of cols) {
2896
+ const td = el('td');
2897
+ td.setAttribute('role', 'cell');
2898
+ td.dataset['label'] = c.label;
2899
+ tr.append(td);
2900
+ }
2901
+ return tr;
2902
+ }
2903
+ function newListItem() {
2904
+ const li = el('li');
2905
+ const texts = el('span', 'tb-list-texts');
2906
+ texts.append(el('span', 'tb-list-primary'), el('span', 'tb-list-secondary'));
2907
+ li.append(texts);
2908
+ return li;
2909
+ }
2910
+ function fillRow(item, row, cols, table) {
2911
+ const set = (e, t) => {
2912
+ if (e.textContent !== t)
2913
+ e.textContent = t;
2914
+ };
2915
+ if (table) {
2916
+ cols.forEach((c, i) => {
2917
+ const v = rowField(row, c.sym);
2918
+ const td = item.children[i];
2919
+ if (c.image) {
2920
+ td.classList.add('tb-thumb-cell');
2921
+ return thumb(td, v, c.round);
2922
+ }
2923
+ set(td, cellText(v));
2924
+ td.classList.toggle('tb-num', NUMERIC.has(v.t));
2925
+ });
2926
+ return;
2927
+ }
2928
+ // a list shows its picture first, then its first column, and the others on a quieter line
2929
+ const pic = cols.find(c => c.image);
2930
+ if (pic !== undefined)
2931
+ thumb(item, rowField(row, pic.sym), pic.round);
2932
+ else
2933
+ item.querySelector(':scope > .tb-thumb')?.remove();
2934
+ const [first, ...rest] = cols.filter(c => !c.image).map(c => cellText(rowField(row, c.sym)));
2935
+ const texts = item.querySelector(':scope > .tb-list-texts');
2936
+ set(texts.children[0], first ?? '');
2937
+ set(texts.children[1], rest.filter(Boolean).join(' · '));
2938
+ }
2939
+ function handlerFor(face, name) {
2940
+ const ev = get(face, 'events');
2941
+ if (ev.t !== K.Block)
2942
+ return false;
2943
+ const c = canon(intern(name));
2944
+ return ev.s.data.some(x => x.t === K.Word && canon(x.sym) === c);
2945
+ }
2946
+ // --- trees ---------------------------------------------------------------------------
2947
+ const CHILDREN = intern('children');
2948
+ const EXPANDED = intern('expanded');
2949
+ function treeItems(m) {
2950
+ return Array.from(m.box.querySelectorAll('[role="treeitem"]'));
2951
+ }
2952
+ /** The node whose children a group holds; none for the root. */
2953
+ function groupParent(m, group) {
2954
+ if (group === m.box)
2955
+ return NONE;
2956
+ const item = group.closest('[role="treeitem"]');
2957
+ return item !== null ? rowOf.get(item) ?? NONE : NONE;
2958
+ }
2959
+ function buildTree(face, m) {
2960
+ const wrap = el('div', 'tb-tree-wrap');
2961
+ const box = el('ul', 'tb-tree');
2962
+ box.setAttribute('role', 'tree');
2963
+ const empty = el('p', 'tb-empty');
2964
+ wrap.append(box, empty);
2965
+ box.addEventListener('click', ev => {
2966
+ const target = ev.target;
2967
+ const item = target.closest('[role="treeitem"]');
2968
+ if (item === null)
2969
+ return;
2970
+ if (target.closest('.tb-tree-toggle') !== null)
2971
+ return toggleNode(m, item);
2972
+ focusItem(m, item);
2973
+ selectNode(m, item);
2974
+ });
2975
+ box.addEventListener('keydown', ev => treeKey(m, ev));
2976
+ m.box = box;
2977
+ m.rows = new Map();
2978
+ m.empty = empty;
2979
+ m.open = new Set();
2980
+ return wrap;
2981
+ }
2982
+ function newTreeItem() {
2983
+ const li = el('li');
2984
+ li.setAttribute('role', 'treeitem');
2985
+ const row = el('div', 'tb-tree-row');
2986
+ const toggle = el('span', 'tb-tree-toggle');
2987
+ toggle.setAttribute('aria-hidden', 'true');
2988
+ const chevron = icon('chevron-right');
2989
+ if (chevron !== null)
2990
+ toggle.append(chevron);
2991
+ row.append(toggle, el('span', 'tb-tree-label'));
2992
+ const group = el('ul');
2993
+ group.setAttribute('role', 'group');
2994
+ li.append(row, group);
2995
+ return li;
2996
+ }
2997
+ /** Creates, updates, moves or removes the items of a tree, level by level, by key. */
2998
+ function syncTree(m) {
2999
+ const f = m.face;
3000
+ const label = columns(f)[0]?.sym ?? intern('name');
3001
+ const keyWord = get(f, 'key');
3002
+ const key = keyWord.t === K.Word || keyWord.t === K.LitWord ? keyWord.sym : intern('id');
3003
+ const selected = get(f, 'selected');
3004
+ const old = m.rows;
3005
+ const open = m.open;
3006
+ const next = new Map();
3007
+ const level = (group, nodes, depth, parentKey) => {
3008
+ let cursor = group.firstChild;
3009
+ nodes.forEach((node, i) => {
3010
+ const id = rowField(node, key);
3011
+ let k = id.t === K.None ? `${parentKey}/${i}` : `${id.t}:${form(id)}`;
3012
+ if (next.has(k))
3013
+ k = `${parentKey}/${i}#${k}`;
3014
+ const known = old.get(k);
3015
+ const item = known ?? newTreeItem();
3016
+ next.set(k, item);
3017
+ rowOf.set(item, node);
3018
+ item.dataset['key'] = k;
3019
+ item.setAttribute('aria-level', String(depth));
3020
+ item.style.setProperty('--tb-level', String(depth - 1));
3021
+ const text = cellText(rowField(node, label));
3022
+ const name = item.firstElementChild.lastElementChild;
3023
+ if (name.textContent !== text)
3024
+ name.textContent = text;
3025
+ const kids = rowField(node, CHILDREN);
3026
+ const folder = kids.t === K.Block;
3027
+ // `expanded: true` opens a node the first time it shows
3028
+ if (folder && known === undefined && rowField(node, EXPANDED).t === K.Logic && rowField(node, EXPANDED).v)
3029
+ open.add(k);
3030
+ const isOpen = folder && open.has(k);
3031
+ if (folder)
3032
+ item.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
3033
+ else
3034
+ item.removeAttribute('aria-expanded');
3035
+ const sub = item.lastElementChild;
3036
+ if (isOpen)
3037
+ level(sub, kids.s.data.slice(kids.i), depth + 1, k);
3038
+ else
3039
+ sub.replaceChildren();
3040
+ sub.hidden = sub.childElementCount === 0;
3041
+ const on = selected.t !== K.None && sameRow(selected, node);
3042
+ item.classList.toggle('tb-selected', on);
3043
+ item.setAttribute('aria-selected', on ? 'true' : 'false');
3044
+ if (item !== cursor)
3045
+ group.insertBefore(item, cursor);
3046
+ else
3047
+ cursor = cursor.nextSibling;
3048
+ });
3049
+ // whatever is left after the last placed item is gone from the data
3050
+ while (cursor !== null) {
3051
+ const gone = cursor;
3052
+ cursor = cursor.nextSibling;
3053
+ gone.remove();
3054
+ }
3055
+ };
3056
+ const data = get(f, 'data');
3057
+ level(m.box, data.t === K.Block ? data.s.data.slice(data.i) : [], 1, '');
3058
+ m.rows = next;
3059
+ // one Tab stop: the item that had it, else the selected one, else the first
3060
+ const items = treeItems(m);
3061
+ const current = items.find(e => e.tabIndex === 0 && e.hasAttribute('tabindex'))
3062
+ ?? items.find(e => e.classList.contains('tb-selected')) ?? items[0];
3063
+ for (const e of items)
3064
+ e.tabIndex = e === current ? 0 : -1;
3065
+ m.empty.textContent = str(f, 'text') ?? own('empty');
3066
+ m.empty.hidden = items.length > 0;
3067
+ }
3068
+ function focusItem(m, item) {
3069
+ for (const e of treeItems(m))
3070
+ e.tabIndex = e === item ? 0 : -1;
3071
+ item.focus();
3072
+ }
3073
+ function selectNode(m, item) {
3074
+ const node = rowOf.get(item);
3075
+ if (node !== undefined)
3076
+ void fire('ui-select', m.face, node);
3077
+ }
3078
+ /** Opens or closes a folder; opening runs on-expand, which may load its children. */
3079
+ function toggleNode(m, item, want) {
3080
+ if (!item.hasAttribute('aria-expanded'))
3081
+ return;
3082
+ const k = item.dataset['key'];
3083
+ const open = want ?? !m.open.has(k);
3084
+ if (open === m.open.has(k))
3085
+ return;
3086
+ const inside = document.activeElement !== item && item.contains(document.activeElement);
3087
+ if (open)
3088
+ m.open.add(k);
3089
+ else
3090
+ m.open.delete(k);
3091
+ syncTree(m);
3092
+ if (inside)
3093
+ focusItem(m, item);
3094
+ const node = rowOf.get(item);
3095
+ if (open && node !== undefined)
3096
+ void fire('ui-expand', m.face, node);
3097
+ }
3098
+ /** The keys of the treeview pattern: arrows, Home, End, Enter, Space and a letter to jump. */
3099
+ function treeKey(m, ev) {
3100
+ const item = ev.target.closest('[role="treeitem"]');
3101
+ if (item === null || ev.altKey || ev.ctrlKey || ev.metaKey)
3102
+ return;
3103
+ const items = treeItems(m);
3104
+ const i = items.indexOf(item);
3105
+ const expanded = item.getAttribute('aria-expanded');
3106
+ let to = null;
3107
+ switch (ev.key) {
3108
+ case 'ArrowDown':
3109
+ to = items[i + 1];
3110
+ break;
3111
+ case 'ArrowUp':
3112
+ to = items[i - 1];
3113
+ break;
3114
+ case 'Home':
3115
+ to = items[0];
3116
+ break;
3117
+ case 'End':
3118
+ to = items[items.length - 1];
3119
+ break;
3120
+ case 'ArrowRight':
3121
+ if (expanded === 'false')
3122
+ toggleNode(m, item, true);
3123
+ else if (expanded === 'true')
3124
+ to = item.querySelector('[role="treeitem"]');
3125
+ break;
3126
+ case 'ArrowLeft':
3127
+ if (expanded === 'true')
3128
+ toggleNode(m, item, false);
3129
+ else
3130
+ to = item.parentElement.closest('[role="treeitem"]');
3131
+ break;
3132
+ case 'Enter':
3133
+ case ' ':
3134
+ selectNode(m, item);
3135
+ break;
3136
+ default: {
3137
+ if (ev.key.length !== 1 || ev.key.trim() === '')
3138
+ return;
3139
+ const c = ev.key.toLowerCase();
3140
+ const label = (e) => (e.querySelector('.tb-tree-label')?.textContent ?? '').toLowerCase();
3141
+ to = [...items.slice(i + 1), ...items.slice(0, i)].find(e => label(e).startsWith(c));
3142
+ }
3143
+ }
3144
+ ev.preventDefault();
3145
+ if (to)
3146
+ focusItem(m, to);
3147
+ }
3148
+ /** Where a drag over a tree lands: between siblings, or into a folder when over the middle of its row. */
3149
+ function treeTarget(m, src, x, y) {
3150
+ const at = document.elementFromPoint(x, y)?.closest('[role="treeitem"]');
3151
+ const drop = flag(m.face, 'drop');
3152
+ let t;
3153
+ if (at === null || at === undefined || !m.box.contains(at)) {
3154
+ t = { m, index: insertionAt(m, x, y), reorder: false, group: m.box, parent: NONE };
3155
+ }
3156
+ else {
3157
+ const r = at.querySelector(':scope > .tb-tree-row').getBoundingClientRect();
3158
+ if (at.hasAttribute('aria-expanded') && y > r.top + r.height / 4 && y < r.bottom - r.height / 4) {
3159
+ const node = rowOf.get(at);
3160
+ const kids = rowField(node, CHILDREN);
3161
+ t = { m, index: kids.s.data.length - kids.i, reorder: false, group: at.lastElementChild, parent: node, into: at };
3162
+ }
3163
+ else {
3164
+ const group = at.parentElement;
3165
+ const index = Array.prototype.indexOf.call(group.children, at) + (y > r.top + r.height / 2 ? 1 : 0);
3166
+ t = { m, index, reorder: false, group, parent: groupParent(m, group) };
3167
+ }
3168
+ }
3169
+ // never into itself or below itself
3170
+ if (src.el === t.into || src.el.contains(t.group))
3171
+ return null;
3172
+ t.reorder = src.within === m && t.group === src.group && t.into === undefined;
3173
+ return t.reorder || drop ? t : null;
3174
+ }
3175
+ // --- toolbars and breadcrumbs -------------------------------------------------------
3176
+ const BAR_ITEMS = 'button, a[href], input, select, textarea, [tabindex]';
3177
+ /** The controls of a toolbar, in order; `shown` skips hidden and disabled ones. */
3178
+ function barItems(bar, shown = true) {
3179
+ return Array.from(bar.querySelectorAll(BAR_ITEMS)).filter(e => e.closest('.tb-toolbar') === bar
3180
+ && (!shown || e.getClientRects().length > 0 && !e.disabled));
3181
+ }
3182
+ function buildToolbar() {
3183
+ const bar = el('div', 'tb-toolbar');
3184
+ bar.setAttribute('role', 'toolbar');
3185
+ // one Tab stop: the arrows move between the controls (roving tabindex)
3186
+ bar.addEventListener('keydown', ev => {
3187
+ const at = ev.target;
3188
+ if (ev.altKey || ev.ctrlKey || ev.metaKey || at.matches('input, select, textarea'))
3189
+ return;
3190
+ const items = barItems(bar);
3191
+ const i = items.indexOf(at);
3192
+ if (i < 0)
3193
+ return;
3194
+ const to = ev.key === 'ArrowRight' ? (i + 1) % items.length : ev.key === 'ArrowLeft' ? (i - 1 + items.length) % items.length
3195
+ : ev.key === 'Home' ? 0 : ev.key === 'End' ? items.length - 1 : -1;
3196
+ if (to < 0)
3197
+ return;
3198
+ ev.preventDefault();
3199
+ items[to].focus();
3200
+ });
3201
+ bar.addEventListener('focusin', ev => {
3202
+ const at = ev.target;
3203
+ if (!barItems(bar, false).includes(at))
3204
+ return;
3205
+ for (const e of barItems(bar, false))
3206
+ e.tabIndex = e === at ? 0 : -1;
3207
+ });
3208
+ return bar;
3209
+ }
3210
+ /** Keeps exactly one control of a toolbar in the Tab order, and the text of its buttons as their tooltip. */
3211
+ function syncToolbar(bar) {
3212
+ for (const e of Array.from(bar.children)) {
3213
+ const m = byNode.get(e);
3214
+ if (m !== undefined && m.el === e && word(m.face, 'style') === 'button')
3215
+ sync(m);
3216
+ }
3217
+ // the bar may not be on the page yet, so visibility is checked only when moving
3218
+ const items = barItems(bar, false);
3219
+ const current = items.find(e => e.tabIndex === 0 && e.hasAttribute('tabindex')) ?? items[0];
3220
+ for (const e of items)
3221
+ e.tabIndex = e === current ? 0 : -1;
3222
+ }
3223
+ /** The items of a breadcrumb: a label and a word or path each, the last one maybe without. */
3224
+ function crumbs(face) {
3225
+ const d = get(face, 'data');
3226
+ if (d.t !== K.Block)
3227
+ return [];
3228
+ const out = [];
3229
+ const cells = d.s.data.slice(d.i);
3230
+ for (let i = 0; i < cells.length; i++) {
3231
+ const c = cells[i];
3232
+ if (c.t !== K.String && c.t !== K.Map)
3233
+ continue;
3234
+ const next = cells[i + 1];
3235
+ const id = next !== undefined && (next.t === K.Word || next.t === K.Path) ? next : NONE;
3236
+ if (id !== NONE)
3237
+ i++;
3238
+ out.push({ text: translate(c, host.rt), id });
3239
+ }
3240
+ return out;
3241
+ }
3242
+ function buildBreadcrumb(m) {
3243
+ const nav = el('nav', 'tb-breadcrumb');
3244
+ keepOwn(nav, 'breadcrumb', 'aria-label');
3245
+ m.box = el('ol');
3246
+ nav.append(m.box);
3247
+ return nav;
3248
+ }
3249
+ /** Rebuilds the items; on narrow screens the middle ones hide behind a "…" that lists them in a menu. */
3250
+ function syncBreadcrumb(m) {
3251
+ const f = m.face;
3252
+ const items = crumbs(f);
3253
+ // choosing an item sets value, which repaints the face: keep the nodes (and the focus) if nothing changed
3254
+ const signature = items.map(c => `${c.text}\u0000${form(c.id)}`).join('\u0001');
3255
+ if (m.kids === signature)
3256
+ return;
3257
+ m.kids = signature;
3258
+ // a lit-word or lit-path, so that passing it on does not evaluate it
3259
+ const pick = (c) => void fire('ui-crumb', f, c.id.t === K.Path ? { ...c.id, t: K.LitPath } : wordOf(K.LitWord, form(c.id)));
3260
+ const middle = items.length > 3 ? items.slice(1, -2) : [];
3261
+ const nodes = items.map((c, i) => {
3262
+ const li = el('li');
3263
+ if (middle.includes(c))
3264
+ li.className = 'tb-crumb-middle';
3265
+ if (c.id === NONE) {
3266
+ const span = el('span', 'tb-crumb');
3267
+ span.textContent = c.text;
3268
+ if (i === items.length - 1)
3269
+ span.setAttribute('aria-current', 'page');
3270
+ li.append(span);
3271
+ }
3272
+ else {
3273
+ const b = el('button', 'tb-crumb');
3274
+ b.type = 'button';
3275
+ b.textContent = c.text;
3276
+ b.addEventListener('click', () => pick(c));
3277
+ li.append(b);
3278
+ }
3279
+ return li;
3280
+ });
3281
+ if (middle.length > 0) {
3282
+ const li = el('li', 'tb-crumb-more');
3283
+ const b = el('button', 'tb-crumb');
3284
+ b.type = 'button';
3285
+ b.textContent = '…';
3286
+ keepOwn(b, 'more-levels', 'aria-label');
3287
+ b.setAttribute('aria-haspopup', 'menu');
3288
+ b.setAttribute('aria-expanded', 'false');
3289
+ b.addEventListener('click', () => {
3290
+ const r = b.getBoundingClientRect();
3291
+ openMenu(middle.map(c => ({ text: c.text, run: () => pick(c) })), r.left, r.bottom + 4, b);
3292
+ });
3293
+ li.append(b);
3294
+ nodes.splice(1, 0, li);
3295
+ }
3296
+ m.box.replaceChildren(...nodes);
3297
+ }
3298
+ // --- dialogs, tabs and toasts --------------------------------------------------------
3299
+ function buildDialog(face, m) {
3300
+ const d = el('dialog', 'tb-dialog');
3301
+ const head = el('header', 'tb-dialog-head');
3302
+ const title = el('h2', 'tb-dialog-title');
3303
+ title.id = `tb-${nextId++}`;
3304
+ d.setAttribute('aria-labelledby', title.id);
3305
+ const x = el('button', 'tb-dialog-close');
3306
+ x.type = 'button';
3307
+ keepOwn(x, 'close', 'aria-label');
3308
+ x.textContent = '×';
3309
+ x.addEventListener('click', () => void fire('ui-close', face));
3310
+ head.append(title, x);
3311
+ const body = el('div', 'tb-dialog-body');
3312
+ d.append(head, body);
3313
+ // Esc: let the face decide, so code that keeps it open still wins
3314
+ d.addEventListener('cancel', ev => {
3315
+ ev.preventDefault();
3316
+ void fire('ui-close', face);
3317
+ });
3318
+ m.label = title;
3319
+ m.box = body;
3320
+ return d;
3321
+ }
3322
+ function syncDialog(m) {
3323
+ const d = m.el;
3324
+ m.label.textContent = str(m.face, 'text') ?? '';
3325
+ const open = !flag(m.face, 'hidden');
3326
+ if (open === d.open)
3327
+ return;
3328
+ if (!d.isConnected) {
3329
+ queueMicrotask(() => { if (d.isConnected)
3330
+ syncDialog(m); });
3331
+ return;
3332
+ }
3333
+ if (!open)
3334
+ return d.close();
3335
+ d.showModal();
3336
+ // after this repaint, which never writes into a focused input
3337
+ queueMicrotask(() => d.querySelector('input, textarea, select')?.focus());
3338
+ }
3339
+ function buildTabs(face, m) {
3340
+ const node = el('div', 'tb-tabs');
3341
+ const list = el('div', 'tb-tablist');
3342
+ list.setAttribute('role', 'tablist');
3343
+ node.append(list);
3344
+ const tabs = children(face);
3345
+ const pick = (i) => {
3346
+ void fire('ui-input', face, { t: K.Integer, v: i + 1 });
3347
+ list.children[i]?.focus();
3348
+ };
3349
+ tabs.forEach((t, i) => {
3350
+ const panel = build(t);
3351
+ const b = el('button', 'tb-tab');
3352
+ b.type = 'button';
3353
+ b.id = `tb-${nextId++}`;
3354
+ panel.id = `${b.id}-panel`;
3355
+ b.setAttribute('role', 'tab');
3356
+ b.setAttribute('aria-controls', panel.id);
3357
+ panel.setAttribute('aria-labelledby', b.id);
3358
+ b.textContent = str(t, 'text') ?? '';
3359
+ b.addEventListener('click', () => pick(i));
3360
+ const tm = byCtx.get(t.ctx);
3361
+ tm.button = b;
3362
+ list.append(b);
3363
+ node.append(panel);
3364
+ });
3365
+ list.addEventListener('keydown', ev => {
3366
+ const at = Array.prototype.indexOf.call(list.children, document.activeElement);
3367
+ const n = tabs.length;
3368
+ const to = ev.key === 'ArrowRight' ? (at + 1) % n : ev.key === 'ArrowLeft' ? (at - 1 + n) % n
3369
+ : ev.key === 'Home' ? 0 : ev.key === 'End' ? n - 1 : -1;
3370
+ if (to < 0 || at < 0)
3371
+ return;
3372
+ ev.preventDefault();
3373
+ pick(to);
3374
+ });
3375
+ m.box = list;
3376
+ return node;
3377
+ }
3378
+ function syncTabs(m) {
3379
+ const v = get(m.face, 'value');
3380
+ const tabs = children(m.face);
3381
+ const at = v.t === K.Integer ? Math.min(Math.max(Number(v.v), 1), tabs.length) - 1 : 0;
3382
+ tabs.forEach((t, i) => {
3383
+ const tm = byCtx.get(t.ctx);
3384
+ if (tm === undefined || tm.button === null)
3385
+ return;
3386
+ const on = i === at;
3387
+ tm.button.setAttribute('aria-selected', on ? 'true' : 'false');
3388
+ tm.button.tabIndex = on ? 0 : -1;
3389
+ tm.el.hidden = !on;
3390
+ });
3391
+ }
3392
+ // A split shows two panes side by side with a handle between them; on narrow
3393
+ // screens it shows one pane, the one its value names, and the second pane
3394
+ // gets a back button.
3395
+ function buildSplit(face, m) {
3396
+ const node = el('div', 'tb-split');
3397
+ const [a, b] = children(face);
3398
+ const first = el('div', 'tb-split-pane');
3399
+ const second = el('div', 'tb-split-pane');
3400
+ first.tabIndex = second.tabIndex = -1;
3401
+ const handle = el('div', 'tb-split-handle');
3402
+ handle.tabIndex = 0;
3403
+ handle.setAttribute('role', 'separator');
3404
+ handle.setAttribute('aria-orientation', 'vertical');
3405
+ keepOwn(handle, 'resize-panes', 'aria-label');
3406
+ handle.setAttribute('aria-valuemin', '20');
3407
+ handle.setAttribute('aria-valuemax', '80');
3408
+ const resize = (pct) => {
3409
+ const p = Math.round(Math.min(80, Math.max(20, pct)));
3410
+ node.style.setProperty('--tb-split', `${p}%`);
3411
+ handle.setAttribute('aria-valuenow', String(p));
3412
+ };
3413
+ resize(40);
3414
+ handle.addEventListener('pointerdown', ev => {
3415
+ handle.setPointerCapture(ev.pointerId);
3416
+ ev.preventDefault();
3417
+ });
3418
+ handle.addEventListener('pointermove', ev => {
3419
+ if (!handle.hasPointerCapture(ev.pointerId))
3420
+ return;
3421
+ const r = node.getBoundingClientRect();
3422
+ resize(((ev.clientX - r.left) / r.width) * 100);
3423
+ });
3424
+ handle.addEventListener('keydown', ev => {
3425
+ const now = Number(handle.getAttribute('aria-valuenow'));
3426
+ const to = ev.key === 'ArrowLeft' ? now - 5 : ev.key === 'ArrowRight' ? now + 5
3427
+ : ev.key === 'Home' ? 20 : ev.key === 'End' ? 80 : null;
3428
+ if (to === null)
3429
+ return;
3430
+ ev.preventDefault();
3431
+ resize(to);
3432
+ });
3433
+ const back = el('button', 'tb-button tb-split-back');
3434
+ back.type = 'button';
3435
+ const arrow = iconNode('arrow-left');
3436
+ const caption = el('span');
3437
+ keepOwn(caption, 'back');
3438
+ back.append(...(arrow !== null ? [arrow] : []), caption);
3439
+ back.addEventListener('click', () => void fire('ui-input', face, { t: K.Integer, v: 1 }));
3440
+ if (a !== undefined)
3441
+ first.append(build(a));
3442
+ second.append(back);
3443
+ if (b !== undefined)
3444
+ second.append(build(b));
3445
+ node.append(first, handle, second);
3446
+ return node;
3447
+ }
3448
+ function syncSplit(m) {
3449
+ const v = get(m.face, 'value');
3450
+ const pane = v.t === K.Integer && Number(v.v) === 2 ? '2' : '1';
3451
+ const was = m.el.dataset['pane'];
3452
+ if (was === pane)
3453
+ return;
3454
+ m.el.dataset['pane'] = pane;
3455
+ // on narrow screens the other pane just appeared: take the focus there
3456
+ if (was !== undefined && matchMedia('(max-width: 640px)').matches) {
3457
+ const shown = m.el.children[pane === '2' ? 2 : 0];
3458
+ (shown.querySelector('.tb-selected') ?? shown).focus();
3459
+ }
3460
+ }
3461
+ let toasts = null;
3462
+ native('show-toast', '["Shows a short message at the edge of the screen." message [string!] kind [word! none!]]', (_t, f) => {
3463
+ if (toasts === null) {
3464
+ // a manual popover sits in the top layer, so toasts show above open dialogs
3465
+ toasts = el('div', 'tb-toasts');
3466
+ toasts.popover = 'manual';
3467
+ toasts.setAttribute('aria-live', 'polite');
3468
+ document.body.append(toasts);
3469
+ }
3470
+ const kind = f.args[1].t === K.Word ? spell(f.args[1].sym).toLowerCase() : null;
3471
+ const t = el('div', kind !== null ? `tb-toast tb-${kind}` : 'tb-toast');
3472
+ if (kind === 'danger')
3473
+ t.setAttribute('role', 'alert');
3474
+ const message = text(f.args[0]);
3475
+ const box = toasts;
3476
+ const dismiss = () => {
3477
+ t.remove();
3478
+ if (box.childElementCount === 0 && box.matches(':popover-open'))
3479
+ box.hidePopover();
3480
+ };
3481
+ t.addEventListener('click', dismiss);
3482
+ setTimeout(dismiss, kind === 'danger' ? 6000 : 4000);
3483
+ if (box.matches(':popover-open'))
3484
+ box.hidePopover();
3485
+ box.append(t);
3486
+ box.showPopover();
3487
+ // screen readers announce text that changes inside a live region already shown
3488
+ setTimeout(() => { t.textContent = message; }, 50);
3489
+ return value(f.args[0]);
3490
+ });
3491
+ native('show-confirm', '["Asks a question in a small dialog; true when the user says yes." question [string!] yes [string! none!] no [string! none!] kind [word! none!]]', (_t, f, v) => {
3492
+ if (f.phase === 1)
3493
+ return value(v);
3494
+ f.phase = 1;
3495
+ const answer = (at, key) => f.args[at].t === K.String ? text(f.args[at]) : own(key);
3496
+ const danger = f.args[3].t === K.Word && spell(f.args[3].sym).toLowerCase() === 'danger';
3497
+ const d = el('dialog', 'tb-dialog tb-confirm');
3498
+ d.setAttribute('role', 'alertdialog');
3499
+ const body = el('div', 'tb-dialog-body');
3500
+ const q = el('p', 'tb-confirm-question');
3501
+ q.id = `tb-${nextId++}`;
3502
+ q.textContent = text(f.args[0]);
3503
+ d.setAttribute('aria-labelledby', q.id);
3504
+ const row = el('div', 'tb-row tb-right');
3505
+ const no = el('button', 'tb-button');
3506
+ const yes = el('button', danger ? 'tb-button tb-danger' : 'tb-button tb-primary');
3507
+ no.type = yes.type = 'button';
3508
+ no.textContent = answer(2, 'no');
3509
+ yes.textContent = answer(1, 'yes');
3510
+ row.append(no, yes);
3511
+ body.append(q, row);
3512
+ d.append(body);
3513
+ const p = new Promise(resolve => {
3514
+ const done = (ok) => {
3515
+ d.close();
3516
+ d.remove();
3517
+ resolve(ok ? TRUE : FALSE);
3518
+ };
3519
+ yes.addEventListener('click', () => done(true));
3520
+ no.addEventListener('click', () => done(false));
3521
+ // Esc is no
3522
+ d.addEventListener('cancel', ev => { ev.preventDefault(); done(false); });
3523
+ });
3524
+ document.body.append(d);
3525
+ // over an open dialog too: the top layer stacks dialogs in the order they open
3526
+ d.showModal();
3527
+ // what cannot be undone starts on no, so Enter does not do it by mistake
3528
+ (danger ? no : yes).focus();
3529
+ return { k: 'await', p };
3530
+ });
3531
+ native('print-faces', '["Opens the print dialog for the page, or for one face only." face [object! none!]]', (_t, f) => {
3532
+ const target = f.args[0].t === K.Object ? byCtx.get(f.args[0].ctx)?.el : undefined;
3533
+ if (f.args[0].t === K.Object && (target === undefined || !target.isConnected)) {
3534
+ return throwError('script', 'not-shown', 'print-page/only needs a face on the screen');
3535
+ }
3536
+ if (target !== undefined) {
3537
+ target.classList.add('tb-print-target');
3538
+ document.documentElement.classList.add('tb-print-only');
3539
+ addEventListener('afterprint', () => {
3540
+ target.classList.remove('tb-print-target');
3541
+ document.documentElement.classList.remove('tb-print-only');
3542
+ }, { once: true });
3543
+ }
3544
+ print();
3545
+ return value(UNSET);
3546
+ });
3547
+ // --- syncing -----------------------------------------------------------------------
3548
+ function sync(m) {
3549
+ const f = m.face;
3550
+ const style = word(f, 'style') ?? '';
3551
+ const role = word(f, 'role');
3552
+ const t = str(f, 'text');
3553
+ const hidden = flag(f, 'hidden');
3554
+ const err = str(f, 'error');
3555
+ const cls = [];
3556
+ if (hidden && style !== 'dialog')
3557
+ cls.push('tb-hidden');
3558
+ if (flag(f, 'fill'))
3559
+ cls.push('tb-fill');
3560
+ if (flag(f, 'narrow-only'))
3561
+ cls.push('tb-narrow-only');
3562
+ if (flag(f, 'wide-only'))
3563
+ cls.push('tb-wide-only');
3564
+ if (flag(f, 'fit'))
3565
+ cls.push('tb-fit');
3566
+ if (flag(f, 'drop'))
3567
+ cls.push('tb-drop-zone');
3568
+ if (role !== null && !INPUTS.has(style))
3569
+ cls.push(`tb-${role}`);
3570
+ const size = word(f, 'size');
3571
+ if (size !== null)
3572
+ cls.push(`tb-${size}`);
3573
+ const align = word(f, 'align');
3574
+ if (align !== null && style === 'row')
3575
+ cls.push(`tb-${align}`);
3576
+ const valign = word(f, 'valign');
3577
+ if (valign !== null && style === 'row')
3578
+ cls.push(`tb-${valign}`);
3579
+ if (err !== null)
3580
+ cls.push('tb-invalid');
3581
+ if (flag(f, 'pending'))
3582
+ cls.push('tb-pending');
3583
+ setExtra(m.el, cls);
3584
+ // shown as it is, but it and its children cannot be used
3585
+ m.el.inert = flag(f, 'inert');
3586
+ // a face you can drag takes the focus, so the keyboard reaches its menu and moves it
3587
+ if (flag(f, 'drag') && !isData(m) && m.el.tabIndex < 0)
3588
+ m.el.tabIndex = 0;
3589
+ space(m.el, 'padding', get(f, 'pad'));
3590
+ space(m.el, 'gap', get(f, 'gap'));
3591
+ if (style === 'radio')
3592
+ return syncRadio(m, err);
3593
+ if (style === 'upload')
3594
+ return syncUpload(m, err);
3595
+ if (style === 'photo')
3596
+ return syncPhoto(m, err);
3597
+ if (style === 'lookup')
3598
+ return syncLookup(m, err);
3599
+ if (style === 'rich')
3600
+ return syncRich(m, err);
3601
+ if (m.input !== null) {
3602
+ if (m.label !== null) {
3603
+ m.label.textContent = t ?? '';
3604
+ m.label.classList.toggle('tb-required', required(f) && style !== 'check');
3605
+ }
3606
+ const v = get(f, 'value');
3607
+ if (m.input instanceof HTMLInputElement && m.input.type === 'checkbox') {
3608
+ m.input.checked = v.t === K.Logic && v.v;
3609
+ }
3610
+ else {
3611
+ // options given by code after the face was made
3612
+ if (m.input instanceof HTMLSelectElement) {
3613
+ if (m.input.dataset.options !== optionsKey(f))
3614
+ fillSelect(m.input, f);
3615
+ }
3616
+ const want = v.t === K.None ? str(f, 'typed') ?? '' : style === 'money' || style === 'date' ? display(v) : form(v);
3617
+ // never fight the user's typing: with the focus, only a value code set is drawn (set-values
3618
+ // after Enter sent the form); a read-only field has no typing to fight
3619
+ const theirs = document.activeElement === m.input && !flag(f, 'readonly') && (m.typing > 0 || v === m.typed);
3620
+ if (!theirs && m.input.value !== want)
3621
+ m.input.value = want;
3622
+ const hint = str(f, 'hint');
3623
+ if (m.input instanceof HTMLSelectElement) {
3624
+ const select = m.input;
3625
+ select.options[0].textContent = hint ?? own('choose');
3626
+ optionsOf(f).forEach((o, i) => {
3627
+ const opt = select.options[i + 1];
3628
+ if (opt)
3629
+ opt.textContent = optionText(o);
3630
+ });
3631
+ const groups = select.querySelectorAll('optgroup');
3632
+ entriesOf(f).filter(isGroup).forEach((g, i) => {
3633
+ if (groups[i])
3634
+ groups[i].label = translate(g.title, host.rt);
3635
+ });
3636
+ }
3637
+ else if (hint !== null)
3638
+ m.input.placeholder = hint;
3639
+ }
3640
+ const readonly = flag(f, 'readonly');
3641
+ // text can be read-only; a choice or a checkbox can only be disabled
3642
+ const typing = m.input instanceof HTMLTextAreaElement || (m.input instanceof HTMLInputElement && m.input.type !== 'checkbox');
3643
+ if (typing)
3644
+ m.input.readOnly = readonly;
3645
+ m.input.disabled = flag(f, 'disabled') || (readonly && !typing);
3646
+ if (style === 'date') {
3647
+ const pick = m.input.nextElementSibling;
3648
+ pick.disabled = m.input.disabled || readonly;
3649
+ pick.setAttribute('aria-label', t !== null ? own('choose-date-of', t) : own('choose-date'));
3650
+ }
3651
+ m.input.setAttribute('aria-required', required(f) ? 'true' : 'false');
3652
+ m.input.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
3653
+ if (m.error !== null)
3654
+ m.error.textContent = err ?? '';
3655
+ return;
3656
+ }
3657
+ switch (style) {
3658
+ case 'title':
3659
+ case 'heading':
3660
+ case 'text': {
3661
+ const tv = get(f, 'text');
3662
+ m.el.textContent = tv.t === K.None ? '' : tv.t === K.Map || tv.t === K.Word ? translate(tv, host.rt) : display(tv);
3663
+ break;
3664
+ }
3665
+ case 'tile':
3666
+ (m.label ?? m.el).textContent = t ?? '';
3667
+ break;
3668
+ case 'button':
3669
+ case 'link': {
3670
+ (m.label ?? m.el).textContent = t ?? '';
3671
+ const named = iconLabel(f);
3672
+ if (named !== null)
3673
+ m.el.setAttribute('aria-label', named);
3674
+ else
3675
+ m.el.removeAttribute('aria-label');
3676
+ const keys = str(f, 'shortcut');
3677
+ if (keys !== null)
3678
+ m.el.setAttribute('aria-keyshortcuts', shortcutAria(keys));
3679
+ else
3680
+ m.el.removeAttribute('aria-keyshortcuts');
3681
+ // in a toolbar, narrow screens show only the icon, so the text goes in the tooltip too
3682
+ const bar = m.label !== null && m.el.parentElement?.classList.contains('tb-toolbar') === true;
3683
+ const tip = named ?? (keys !== null || bar ? t : null);
3684
+ m.el.title = tip === null ? '' : keys === null ? tip : `${tip} (${shortcutLabel(keys)})`;
3685
+ break;
3686
+ }
3687
+ case 'progress':
3688
+ syncProgress(m);
3689
+ return;
3690
+ case 'canvas':
3691
+ syncCanvas(m);
3692
+ return;
3693
+ case 'chart':
3694
+ syncChart(m);
3695
+ return;
3696
+ case 'icon':
3697
+ syncIcon(m);
3698
+ return;
3699
+ case 'video':
3700
+ case 'audio':
3701
+ syncMedia(m);
3702
+ return;
3703
+ case 'image': {
3704
+ const img = m.el;
3705
+ const src = str(f, 'value') ?? '';
3706
+ if (img.getAttribute('src') !== src)
3707
+ img.src = src;
3708
+ img.alt = t ?? '';
3709
+ img.classList.toggle('tb-round', flag(f, 'round'));
3710
+ // a size, as in Red: the image fills it, cut to fit
3711
+ const ext = get(f, 'extent');
3712
+ img.style.width = ext.t === K.Pair ? `${ext.x}px` : '';
3713
+ img.style.height = ext.t === K.Pair ? `${ext.y}px` : '';
3714
+ return;
3715
+ }
3716
+ case 'table':
3717
+ case 'list':
3718
+ syncRows(m);
3719
+ return;
3720
+ case 'rows':
3721
+ syncRowsField(m, err);
3722
+ break;
3723
+ case 'tree':
3724
+ syncTree(m);
3725
+ return;
3726
+ case 'breadcrumb':
3727
+ syncBreadcrumb(m);
3728
+ return;
3729
+ case 'toolbar': {
3730
+ if (t !== null)
3731
+ m.el.setAttribute('aria-label', t);
3732
+ else
3733
+ m.el.removeAttribute('aria-label');
3734
+ break;
3735
+ }
3736
+ case 'desktop':
3737
+ case 'backdrop': {
3738
+ const src = str(f, 'value');
3739
+ m.el.style.backgroundImage = src !== null ? `url(${JSON.stringify(src)})` : '';
3740
+ break;
3741
+ }
3742
+ case 'dialog':
3743
+ syncDialog(m);
3744
+ break;
3745
+ case 'tabs':
3746
+ syncTabs(m);
3747
+ return;
3748
+ case 'split':
3749
+ syncSplit(m);
3750
+ return;
3751
+ case 'tab':
3752
+ if (m.button !== null)
3753
+ m.button.textContent = t ?? '';
3754
+ break;
3755
+ case 'panel': {
3756
+ let h = m.el.querySelector(':scope > .tb-panel-title');
3757
+ if (t === null)
3758
+ h?.remove();
3759
+ else {
3760
+ if (h === null) {
3761
+ h = el('h2', 'tb-panel-title');
3762
+ m.el.prepend(h);
3763
+ }
3764
+ h.textContent = t;
3765
+ }
3766
+ break;
3767
+ }
3768
+ case 'scroll': {
3769
+ if (t !== null)
3770
+ m.el.setAttribute('aria-label', t);
3771
+ else
3772
+ m.el.removeAttribute('aria-label');
3773
+ break;
3774
+ }
3775
+ case 'grid': {
3776
+ const cols = get(f, 'cols');
3777
+ m.el.style.setProperty('--tb-cols', cols.t === K.Integer ? String(cols.v) : '2');
3778
+ // [1 4 1]: a column per weight, never narrower than what it holds
3779
+ const weights = cols.t === K.Block ? cols.s.data.slice(cols.i).filter(c => c.t === K.Integer) : [];
3780
+ if (weights.length > 0)
3781
+ m.el.style.setProperty('--tb-tracks', weights.map(w => `minmax(min-content, ${form(w)}fr)`).join(' '));
3782
+ else
3783
+ m.el.style.removeProperty('--tb-tracks');
3784
+ break;
3785
+ }
3786
+ }
3787
+ if (style === 'toolbar')
3788
+ syncToolbar(m.el);
3789
+ if (m.el instanceof HTMLButtonElement) {
3790
+ // a submit stays focusable while the form has errors; clicking it shows them
3791
+ if (flag(f, 'submit'))
3792
+ m.el.setAttribute('aria-disabled', flag(f, 'disabled') ? 'true' : 'false');
3793
+ else
3794
+ m.el.disabled = flag(f, 'disabled');
3795
+ }
3796
+ // children replaced by code: rebuild this container
3797
+ const kids = get(f, 'pane');
3798
+ if (kids.t === K.Block && m.kids?.s !== kids.s) {
3799
+ m.kids = kids;
3800
+ if (style === 'rows') {
3801
+ placeEntries(m);
3802
+ void fire('ui-pane', f);
3803
+ return;
3804
+ }
3805
+ const box = m.box ?? m.el;
3806
+ if (style === 'screens')
3807
+ placeScreen(m, box);
3808
+ else {
3809
+ const keep = box.querySelector(':scope > .tb-panel-title');
3810
+ box.replaceChildren(...(keep ? [keep] : []));
3811
+ appendChildren(box, f, style);
3812
+ }
3813
+ // let the dialect link the new faces to their view and form
3814
+ void fire('ui-pane', f);
3815
+ }
3816
+ if (style === 'screens')
3817
+ settleScreen(m.box ?? m.el, f);
3818
+ }
3819
+ /** A screen is made away from the page; the page keeps the one it has until `entering` ends. */
3820
+ function placeScreen(m, box) {
3821
+ comingScreen = el('div');
3822
+ appendChildren(comingScreen, m.face, 'screens');
3823
+ settleScreen(box, m.face);
3824
+ }
3825
+ function settleScreen(box, f) {
3826
+ const entering = flag(f, 'entering');
3827
+ box.toggleAttribute('aria-busy', entering);
3828
+ if (entering || comingScreen === null)
3829
+ return;
3830
+ box.replaceChildren(...comingScreen.childNodes);
3831
+ comingScreen = null;
3832
+ enteredScreen(box);
3833
+ }
3834
+ /** Sets a spacing property to a step of the theme's scale, or back to the stylesheet's. */
3835
+ function space(e, prop, v) {
3836
+ if (v.t === K.Integer)
3837
+ e.style.setProperty(prop, `var(--tb-space-${v.v})`);
3838
+ else
3839
+ e.style.removeProperty(prop);
3840
+ }
3841
+ /** Sets the face-driven classes, keeping the base classes from build. */
3842
+ function setExtra(e, cls) {
3843
+ const prev = (e.dataset['tb'] ?? '').split(' ').filter(Boolean);
3844
+ for (const c of prev)
3845
+ if (!cls.includes(c))
3846
+ e.classList.remove(c);
3847
+ for (const c of cls)
3848
+ e.classList.add(c);
3849
+ e.dataset['tb'] = cls.join(' ');
3850
+ }
3851
+ function syncDirty() {
3852
+ for (const ctx of dirty) {
3853
+ ctx.dirty = false;
3854
+ const m = byCtx.get(ctx);
3855
+ if (m !== undefined && (m.el.isConnected || comingScreen?.contains(m.el)))
3856
+ sync(m);
3857
+ }
3858
+ dirty.length = 0;
3859
+ }
3860
+ // --- screens ---------------------------------------------------------------------
3861
+ //
3862
+ // The page's link is `#/name/arg...`, each part URI-encoded. `go` pushes a
3863
+ // history entry; back, forward and links to a screen change the hash, and the
3864
+ // host passes the new route to `ui-route`.
3865
+ /** The screens face of the page. */
3866
+ let screensFace = null;
3867
+ let comingScreen = null; // the screen being made, not on the page yet
3868
+ /** Where a change of screen is announced. */
3869
+ let screenNews = null;
3870
+ function routeParts() {
3871
+ const h = location.hash.replace(/^#\/?/, '');
3872
+ if (h === '')
3873
+ return [];
3874
+ return h.split('/').map(p => {
3875
+ try {
3876
+ return decodeURIComponent(p);
3877
+ }
3878
+ catch {
3879
+ return p;
3880
+ }
3881
+ });
3882
+ }
3883
+ function routeBlock() {
3884
+ return blockOf(K.Block, routeParts().map(p => string(p)));
3885
+ }
3886
+ /** `#/client/42` for the word `client` or the path `client/42`; null for anything else. */
3887
+ function screenHref(v) {
3888
+ const part = (c) => encodeURIComponent(c.t === K.String ? text(c) : c.t === K.Word ? spell(c.sym) : form(c));
3889
+ if (v.t === K.Word)
3890
+ return '#/' + part(v);
3891
+ if (v.t === K.Path)
3892
+ return '#/' + v.s.data.slice(v.i).map(part).join('/');
3893
+ return null;
3894
+ }
3895
+ native('route', '["The screen and arguments in the address bar." ]', () => value(routeBlock()));
3896
+ // Where the page stands in the browser's history: how many of its screens lie behind the
3897
+ // current one (depth) and how far forward it has been (top). Each entry keeps both in
3898
+ // history.state, so back, forward and a reload find them again.
3899
+ let here = { depth: 0, top: 0 };
3900
+ /** At start: an entry with no state is the first of the page. */
3901
+ function startHistory() {
3902
+ const state = history.state;
3903
+ if (typeof state?.depth === 'number')
3904
+ here = { depth: state.depth, top: state.top ?? state.depth };
3905
+ history.replaceState({ ...here }, '');
3906
+ }
3907
+ /** The link changed: back or forward lands on an entry the page made; a link or a typed address makes a new one, a step ahead. */
3908
+ function landHistory() {
3909
+ const state = history.state;
3910
+ if (typeof state?.depth === 'number')
3911
+ here = { depth: state.depth, top: here.top };
3912
+ else
3913
+ here = { depth: here.depth + 1, top: here.depth + 1 };
3914
+ history.replaceState({ ...here }, '');
3915
+ }
3916
+ native('set-route', '["Puts a screen and arguments in the address bar." route [block!] replace [logic!]]', (_t, f) => {
3917
+ const href = screenHref({ ...f.args[0], t: K.Path }) ?? '#/';
3918
+ const replace = f.args[1].t === K.Logic && f.args[1].v;
3919
+ if (replace) {
3920
+ history.replaceState({ ...here }, '', href);
3921
+ return value(f.args[0]);
3922
+ }
3923
+ // a new screen after going back drops the ones ahead, as the browser does
3924
+ here = { depth: here.depth + 1, top: here.depth + 1 };
3925
+ history.pushState({ ...here }, '', href);
3926
+ return value(f.args[0]);
3927
+ });
3928
+ native('route-steps', '["How many steps back and forward the history has." ]', () => value(blockOf(K.Block, [int(here.depth), int(here.top - here.depth)])));
3929
+ native('route-back', '["Goes one step back in the history." ]', () => {
3930
+ if (here.depth === 0)
3931
+ return value(logic(false));
3932
+ history.back();
3933
+ return value(logic(true));
3934
+ });
3935
+ native('route-forward', '["Goes one step forward in the history." ]', () => {
3936
+ if (here.depth >= here.top)
3937
+ return value(logic(false));
3938
+ history.forward();
3939
+ return value(logic(true));
3940
+ });
3941
+ /** After code showed another screen: focus it and announce its title. */
3942
+ function enteredScreen(box) {
3943
+ const screen = box.firstElementChild;
3944
+ if (screen === null)
3945
+ return;
3946
+ const heading = screen.querySelector('h1, h2');
3947
+ const target = heading ?? screen;
3948
+ if (target.tabIndex < 0)
3949
+ target.tabIndex = -1;
3950
+ target.focus({ preventScroll: true });
3951
+ window.scrollTo(0, 0);
3952
+ if (screenNews === null) {
3953
+ screenNews = el('div', 'tb-sr-only');
3954
+ screenNews.setAttribute('aria-live', 'polite');
3955
+ document.body.append(screenNews);
3956
+ }
3957
+ const news = screenNews;
3958
+ news.textContent = '';
3959
+ setTimeout(() => { news.textContent = screen.getAttribute('aria-label') ?? ''; }, 50);
3960
+ }
3961
+ // --- natives -----------------------------------------------------------------------
3962
+ native('repaint', '["Redraws the faces that changed." ]', () => {
3963
+ // after a change of language: every mounted face shows its values again
3964
+ document.documentElement.lang = activeLanguage(host.rt);
3965
+ if (titleFace !== null)
3966
+ document.title = str(titleFace, 'text') ?? document.title;
3967
+ for (const e of Array.from(document.querySelectorAll('[data-tb-own]')))
3968
+ showOwn(e);
3969
+ for (const e of Array.from(document.querySelectorAll('*'))) {
3970
+ const m = byNode.get(e);
3971
+ if (m !== undefined && m.el === e)
3972
+ sync(m);
3973
+ }
3974
+ return value(NONE);
3975
+ });
3976
+ let root = null;
3977
+ /** The face whose text is the page title: the view's title, or the screen shown. */
3978
+ let titleFace = null;
3979
+ native('show', '["Draws a face and everything in it." face [object!]]', (_t, f) => {
3980
+ const face = f.args[0];
3981
+ viewKeys = null;
3982
+ screensFace = null;
3983
+ document.documentElement.lang = activeLanguage(host.rt);
3984
+ const node = build(face);
3985
+ if (root !== null)
3986
+ root.replaceWith(node);
3987
+ else
3988
+ document.body.append(node);
3989
+ root = node;
3990
+ const title = children(face).find(c => word(c, 'style') === 'title');
3991
+ // a screen names the page itself
3992
+ if (title !== undefined && screensFace === null) {
3993
+ document.title = str(title, 'text') ?? document.title;
3994
+ titleFace = title;
3995
+ }
3996
+ return value(face);
3997
+ });
3998
+ /** Theme parameters from a theme object, keeping defaults for anything missing or unknown. */
3999
+ export function themeParams(obj) {
4000
+ const look = word(obj, 'look');
4001
+ const p = { ...DEFAULT_THEME, ...(look !== null ? LOOKS[look] : undefined) };
4002
+ const num = (n) => {
4003
+ const v = get(obj, n);
4004
+ return v.t === K.Integer ? Number(v.v) : v.t === K.Decimal ? v.v : null;
4005
+ };
4006
+ p.base = num('base') ?? p.base;
4007
+ const given = num('accent');
4008
+ p.accent = given ?? (look !== null && num('base') === null && look in LOOKS ? p.accent : (p.base + 180) % 360);
4009
+ p.color = Math.min(1, Math.max(0, num('color') ?? p.color));
4010
+ if (num('line') === 2 || num('line') === 1)
4011
+ p.line = num('line');
4012
+ for (const [key, allowed] of Object.entries(THEME_WORDS)) {
4013
+ const w = word(obj, key);
4014
+ if (w !== null && allowed.includes(w))
4015
+ p[key] = w;
4016
+ }
4017
+ const font = get(obj, 'font');
4018
+ if (font.t === K.Word)
4019
+ p.font = spell(font.sym).toLowerCase();
4020
+ else if (font.t === K.String)
4021
+ p.font = text(font);
4022
+ const headings = get(obj, 'headings');
4023
+ if (headings.t === K.Word)
4024
+ p.headings = spell(headings.sym).toLowerCase();
4025
+ else if (headings.t === K.String)
4026
+ p.headings = text(headings);
4027
+ return p;
4028
+ }
4029
+ function setTheme(p) {
4030
+ let tag = document.getElementById('tb-theme');
4031
+ if (tag === null) {
4032
+ tag = el('style');
4033
+ tag.id = 'tb-theme';
4034
+ document.head.append(tag);
4035
+ }
4036
+ tag.textContent = themeCss(p);
4037
+ }
4038
+ native('apply-theme', '["Changes the look of the whole screen." spec [object!]]', (_t, f) => {
4039
+ setTheme(themeParams(f.args[0]));
4040
+ return value(f.args[0]);
4041
+ });
4042
+ // --- boot --------------------------------------------------------------------------
4043
+ async function boot() {
4044
+ setTheme(DEFAULT_THEME);
4045
+ host = startHost();
4046
+ host.sch.afterPump = syncDirty;
4047
+ document.addEventListener('keydown', onKeyDown, true);
4048
+ document.addEventListener('keydown', onReorderKey);
4049
+ document.addEventListener('pointerdown', onPointerDown);
4050
+ document.addEventListener('pointermove', onPointerMove, { passive: false });
4051
+ document.addEventListener('pointerup', () => endDrag(true));
4052
+ document.addEventListener('pointercancel', () => endDrag(false));
4053
+ document.addEventListener('keydown', ev => { if (ev.key === 'Escape' && dragging?.on) {
4054
+ ev.preventDefault();
4055
+ seenKeys.add(ev);
4056
+ endDrag(false);
4057
+ } }, true);
4058
+ // a touch drag must not scroll the page
4059
+ document.addEventListener('touchmove', ev => { if (dragging?.on)
4060
+ ev.preventDefault(); }, { passive: false });
4061
+ document.addEventListener('keydown', onViewKey);
4062
+ startHistory();
4063
+ window.addEventListener('hashchange', () => {
4064
+ landHistory();
4065
+ if (screensFace !== null)
4066
+ void fire('ui-route', screensFace, routeBlock());
4067
+ });
4068
+ await startUi(host);
4069
+ for (const s of Array.from(document.querySelectorAll('script[type="text/trebol"]'))) {
4070
+ const src = s.getAttribute('src');
4071
+ const url = src !== null ? new URL(src, location.href).href : location.href;
4072
+ const code = src !== null ? await (await fetch(url)).text() : s.textContent ?? '';
4073
+ try {
4074
+ await runSource(host, code, url);
4075
+ }
4076
+ catch (e) {
4077
+ console.error(e instanceof Error ? e.message : report(e));
4078
+ }
4079
+ }
4080
+ }
4081
+ void boot();