trebol 0.1.0 → 0.1.2

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 (160) hide show
  1. package/README.md +18 -3
  2. package/dist/cli.js +13790 -11417
  3. package/dist/fonts/OFL.txt +93 -0
  4. package/dist/fonts/inter-cyrillic-ext.woff2 +0 -0
  5. package/dist/fonts/inter-cyrillic.woff2 +0 -0
  6. package/dist/fonts/inter-greek-ext.woff2 +0 -0
  7. package/dist/fonts/inter-greek.woff2 +0 -0
  8. package/dist/fonts/inter-latin-ext.woff2 +0 -0
  9. package/dist/fonts/inter-latin.woff2 +0 -0
  10. package/dist/fonts/inter-vietnamese.woff2 +0 -0
  11. package/dist/lib/core/access.d.ts +10 -0
  12. package/dist/lib/core/access.js +210 -0
  13. package/dist/lib/core/base.d.ts +4 -0
  14. package/dist/lib/core/base.js +50 -0
  15. package/dist/lib/core/bitset.d.ts +9 -0
  16. package/dist/lib/core/bitset.js +75 -0
  17. package/dist/lib/core/boot.d.ts +18 -0
  18. package/dist/lib/core/boot.js +73 -0
  19. package/dist/lib/core/compare.d.ts +9 -0
  20. package/dist/lib/core/compare.js +156 -0
  21. package/dist/lib/core/ctx.d.ts +36 -0
  22. package/dist/lib/core/ctx.js +251 -0
  23. package/dist/lib/core/dec.d.ts +28 -0
  24. package/dist/lib/core/dec.js +158 -0
  25. package/dist/lib/core/errors.d.ts +15 -0
  26. package/dist/lib/core/errors.js +44 -0
  27. package/dist/lib/core/escapes.d.ts +14 -0
  28. package/dist/lib/core/escapes.js +80 -0
  29. package/dist/lib/core/eval.d.ts +220 -0
  30. package/dist/lib/core/eval.js +666 -0
  31. package/dist/lib/core/func.d.ts +68 -0
  32. package/dist/lib/core/func.js +129 -0
  33. package/dist/lib/core/hash.d.ts +5 -0
  34. package/dist/lib/core/hash.js +155 -0
  35. package/dist/lib/core/index.d.ts +18 -0
  36. package/dist/lib/core/index.js +20 -0
  37. package/dist/lib/core/int64.d.ts +22 -0
  38. package/dist/lib/core/int64.js +113 -0
  39. package/dist/lib/core/kinds.d.ts +67 -0
  40. package/dist/lib/core/kinds.js +134 -0
  41. package/dist/lib/core/lexer.d.ts +13 -0
  42. package/dist/lib/core/lexer.js +702 -0
  43. package/dist/lib/core/mezz.d.ts +1 -0
  44. package/dist/lib/core/mezz.js +360 -0
  45. package/dist/lib/core/mold.d.ts +20 -0
  46. package/dist/lib/core/mold.js +434 -0
  47. package/dist/lib/core/natives/control.d.ts +1 -0
  48. package/dist/lib/core/natives/control.js +374 -0
  49. package/dist/lib/core/natives/csv.d.ts +15 -0
  50. package/dist/lib/core/natives/csv.js +315 -0
  51. package/dist/lib/core/natives/data.d.ts +11 -0
  52. package/dist/lib/core/natives/data.js +367 -0
  53. package/dist/lib/core/natives/define.d.ts +17 -0
  54. package/dist/lib/core/natives/define.js +47 -0
  55. package/dist/lib/core/natives/encode.d.ts +3 -0
  56. package/dist/lib/core/natives/encode.js +187 -0
  57. package/dist/lib/core/natives/json.d.ts +5 -0
  58. package/dist/lib/core/natives/json.js +273 -0
  59. package/dist/lib/core/natives/math.d.ts +3 -0
  60. package/dist/lib/core/natives/math.js +500 -0
  61. package/dist/lib/core/natives/parse.d.ts +1 -0
  62. package/dist/lib/core/natives/parse.js +600 -0
  63. package/dist/lib/core/natives/series.d.ts +4 -0
  64. package/dist/lib/core/natives/series.js +519 -0
  65. package/dist/lib/core/natives/text.d.ts +1 -0
  66. package/dist/lib/core/natives/text.js +487 -0
  67. package/dist/lib/core/natives/xml.d.ts +9 -0
  68. package/dist/lib/core/natives/xml.js +242 -0
  69. package/dist/lib/core/series.d.ts +26 -0
  70. package/dist/lib/core/series.js +73 -0
  71. package/dist/lib/core/symbols.d.ts +9 -0
  72. package/dist/lib/core/symbols.js +44 -0
  73. package/dist/lib/core/values.d.ts +206 -0
  74. package/dist/lib/core/values.js +223 -0
  75. package/dist/lib/host/browser.d.ts +4 -0
  76. package/dist/lib/host/browser.js +4974 -0
  77. package/dist/lib/host/chart.d.ts +26 -0
  78. package/dist/lib/host/chart.js +158 -0
  79. package/dist/lib/host/compress.d.ts +1 -0
  80. package/dist/lib/host/compress.js +37 -0
  81. package/dist/lib/host/devlog.d.ts +11 -0
  82. package/dist/lib/host/devlog.js +13 -0
  83. package/dist/lib/host/devtools.d.ts +23 -0
  84. package/dist/lib/host/devtools.js +626 -0
  85. package/dist/lib/host/draw.d.ts +31 -0
  86. package/dist/lib/host/draw.js +348 -0
  87. package/dist/lib/host/fonts/OFL.txt +93 -0
  88. package/dist/lib/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  89. package/dist/lib/host/fonts/inter-cyrillic.woff2 +0 -0
  90. package/dist/lib/host/fonts/inter-greek-ext.woff2 +0 -0
  91. package/dist/lib/host/fonts/inter-greek.woff2 +0 -0
  92. package/dist/lib/host/fonts/inter-latin-ext.woff2 +0 -0
  93. package/dist/lib/host/fonts/inter-latin.woff2 +0 -0
  94. package/dist/lib/host/fonts/inter-vietnamese.woff2 +0 -0
  95. package/dist/lib/host/fonts.d.ts +11 -0
  96. package/dist/lib/host/fonts.js +29 -0
  97. package/dist/lib/host/icons.d.ts +3 -0
  98. package/dist/lib/host/icons.js +97 -0
  99. package/dist/lib/host/index.d.ts +40 -0
  100. package/dist/lib/host/index.js +192 -0
  101. package/dist/lib/host/js.d.ts +5 -0
  102. package/dist/lib/host/js.js +130 -0
  103. package/dist/lib/host/locale.d.ts +40 -0
  104. package/dist/lib/host/locale.js +241 -0
  105. package/dist/lib/host/markdown.d.ts +30 -0
  106. package/dist/lib/host/markdown.js +161 -0
  107. package/dist/lib/host/modules.d.ts +14 -0
  108. package/dist/lib/host/modules.js +300 -0
  109. package/dist/lib/host/natives.d.ts +6 -0
  110. package/dist/lib/host/natives.js +98 -0
  111. package/dist/lib/host/net.d.ts +12 -0
  112. package/dist/lib/host/net.js +549 -0
  113. package/dist/lib/host/orbit.d.ts +121 -0
  114. package/dist/lib/host/orbit.js +374 -0
  115. package/dist/lib/host/page.d.ts +9 -0
  116. package/dist/lib/host/page.js +55 -0
  117. package/dist/lib/host/rows.d.ts +29 -0
  118. package/dist/lib/host/rows.js +109 -0
  119. package/dist/lib/host/scheduler.d.ts +51 -0
  120. package/dist/lib/host/scheduler.js +197 -0
  121. package/dist/lib/host/theme.d.ts +58 -0
  122. package/dist/lib/host/theme.js +1667 -0
  123. package/dist/lib/ui/i18n.trb +117 -0
  124. package/dist/lib/ui/test.trb +565 -0
  125. package/dist/lib/ui/ui.trb +1678 -0
  126. package/dist/trebol.js +1427 -138
  127. package/editors/vscode/README.md +15 -0
  128. package/editors/vscode/language-configuration.json +28 -0
  129. package/editors/vscode/package.json +42 -0
  130. package/editors/vscode/syntaxes/trebol.tmLanguage.json +237 -0
  131. package/package.json +23 -7
  132. package/src/core/boot.ts +1 -1
  133. package/src/core/func.ts +4 -0
  134. package/src/core/natives/control.ts +1 -1
  135. package/src/core/natives/series.ts +9 -1
  136. package/src/core/natives/text.ts +2 -0
  137. package/src/host/browser.ts +1235 -83
  138. package/src/host/devlog.ts +16 -0
  139. package/src/host/devtools.ts +641 -0
  140. package/src/host/fonts/OFL.txt +93 -0
  141. package/src/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  142. package/src/host/fonts/inter-cyrillic.woff2 +0 -0
  143. package/src/host/fonts/inter-greek-ext.woff2 +0 -0
  144. package/src/host/fonts/inter-greek.woff2 +0 -0
  145. package/src/host/fonts/inter-latin-ext.woff2 +0 -0
  146. package/src/host/fonts/inter-latin.woff2 +0 -0
  147. package/src/host/fonts/inter-vietnamese.woff2 +0 -0
  148. package/src/host/fonts.ts +39 -0
  149. package/src/host/index.ts +5 -3
  150. package/src/host/js.ts +127 -0
  151. package/src/host/markdown.ts +9 -0
  152. package/src/host/modules.ts +41 -2
  153. package/src/host/net.ts +9 -1
  154. package/src/host/orbit.ts +432 -0
  155. package/src/host/rows.ts +30 -0
  156. package/src/host/scheduler.ts +62 -36
  157. package/src/host/theme.ts +270 -6
  158. package/src/ui/i18n.trb +10 -0
  159. package/src/ui/test.trb +565 -0
  160. package/src/ui/ui.trb +564 -90
@@ -16,18 +16,23 @@
16
16
  // set the field again to repaint it.
17
17
 
18
18
  import { logic,
19
- K, NONE, TRUE, FALSE, native, value, string, form, money, decToNumber, decFromNumber, ctxFind, intern, spell, text, canon, blockOf, wordOf, char, compare, UNSET, throwError,
19
+ K, NONE, TRUE, FALSE, native, value, string, form, money, decToNumber, decFromNumber, ctxFind, intern, spell, text, canon, blockOf, wordOf, char, compare, UNSET, throwError, toJson, parseJson,
20
20
  type Cell, type MapCell, type ObjectCell, type BlockCell, type WordCell, type StringCell, type Ctx, type Sym,
21
21
  } from '../core/index.ts';
22
22
  import { mapAt, startHost, startUi, runSource, report, shown, translate, uiText, activeLanguage, editLocal, readLocal, readDate, weekStart, fileSize, LOCAL_KINDS, type Host } from './index.ts';
23
- import { spawn, taskResult } from './scheduler.ts';
23
+ import { spawn, runNow, taskResult, handleOf, type HostTask } from './scheduler.ts';
24
24
  import { themeCss, DEFAULT_THEME, LOOKS, THEME_WORDS, type ThemeParams } from './theme.ts';
25
25
  import { iconNode } from './icons.ts';
26
- import { parseMd, printMd, safeHref, type Block, type Inline } from './markdown.ts';
26
+ import { interCss } from './fonts.ts';
27
+ import { addBuiltIn, builtInText } from './modules.ts';
28
+ import { parseMd, printMd, appendText, safeHref, type Block, type Inline } from './markdown.ts';
27
29
  import { fileHandle } from './net.ts';
28
30
  import { drawSvg, type El } from './draw.ts';
29
- import { rowField, groupRow, sortGroups } from './rows.ts';
31
+ import { rowField, groupRow, sortGroups, rowWindow, DRAW_ALL_UP_TO } from './rows.ts';
30
32
  import { chartSvg, SERIES_COLORS, pieColor, type ChartKind, type Series } from './chart.ts';
33
+ import { readOrbit, layoutOrbit, shownEdges, edgeLabel, bubble, gradients, edgePath, ease, fitCamera, MANY, type OrbitSpec, type Role, type Place, type Placed, type Box } from './orbit.ts';
34
+ import { devLog } from './devlog.ts';
35
+ import { startDevtools, inDevtools, faceRef } from './devtools.ts';
31
36
 
32
37
  // --- reading faces -----------------------------------------------------------------
33
38
 
@@ -181,6 +186,12 @@ interface Mounted {
181
186
  box: HTMLElement | null;
182
187
  /** Rows of a table or list, by key. */
183
188
  rows: Map<string, HTMLElement> | null;
189
+ /** A table or list: all its rows, in the order shown, with their keys; only some may be drawn. */
190
+ items: { row: Cell; k: string }[];
191
+ /** A table or list: the rows drawn, [first, end), and about how tall each is. */
192
+ first: number;
193
+ end: number;
194
+ rowHeight: number;
184
195
  /** Shown instead of the rows when there are none. */
185
196
  empty: HTMLElement | null;
186
197
  /** The tab button of a tab face. */
@@ -206,18 +217,85 @@ const rowOf = new WeakMap<Element, Cell>();
206
217
  const byCtx = new WeakMap<Ctx, Mounted>();
207
218
  /** Contexts of mounted faces written since the last repaint (filled by the core). */
208
219
  const dirty: Ctx[] = [];
220
+ /** Mounted faces with react, is or calc; and whether one came since reactions last ran. */
221
+ const reactors = new Set<Mounted>();
222
+ let newReactor = false;
223
+ /** The ui-react still running because a reaction waits (a fetch); the next one waits for it. */
224
+ let reacting: HostTask | null = null;
209
225
  let nextId = 1;
210
226
 
211
227
  const ACTIVE: ReadonlySet<number> = new Set([K.Word, K.SetWord, K.GetWord, K.Paren, K.Path, K.SetPath, K.GetPath, K.Function, K.Native]);
212
228
 
213
- /** Runs a UI event function (ui-input, ui-blur, ui-click) as a new task. */
229
+ /** The handler each UI event function runs, to name it in an error; the others go by their own name. */
230
+ const HANDLERS: Record<string, string> = {
231
+ 'ui-click': 'action', 'ui-input': 'on-change', 'ui-files': 'on-change', 'ui-remove-file': 'on-change',
232
+ 'ui-lookup-pick': 'on-change', 'ui-lookup-remove': 'on-change', 'ui-lookup-search': 'on-search',
233
+ 'ui-select': 'on-select', 'ui-sort': 'on-sort', 'ui-drop': 'on-drop', 'ui-menu': 'on-menu',
234
+ 'ui-reorder': 'on-reorder', 'ui-expand': 'on-expand', 'ui-close': 'on-close',
235
+ };
236
+
237
+ /**
238
+ * An error of a UI event function says where in the app it happened: `action of button "Save"`, not the
239
+ * name of Trebol's own function (ui-click) that ran it.
240
+ */
241
+ function whereInApp(e: ObjectCell, fn: string, face: ObjectCell, args: Cell[]): void {
242
+ const i = ctxFind(e.ctx, intern('where'));
243
+ const w = i < 0 ? null : e.ctx.vals[i]!;
244
+ if (w === null || w.t !== K.Word || spell((w as WordCell).sym) !== fn) return;
245
+ const ev = fn === 'ui-event' && args[0] !== undefined && args[0].t === K.LitWord ? spell((args[0] as WordCell).sym) : null;
246
+ e.ctx.vals[i] = string(`${ev ?? HANDLERS[fn] ?? fn.replace(/^ui-/, '')} of ${faceRef(face, host.rt)}`);
247
+ }
248
+
249
+ /**
250
+ * Runs a UI event function (ui-input, ui-blur, ui-click) as a new task. An error is shown and gives none, so
251
+ * what the caller does next (focus the first problem, blur) still runs and nothing is left unhandled.
252
+ */
214
253
  function fire(fn: string, face: ObjectCell, ...args: Cell[]): Promise<Cell> {
215
254
  // a word, path or paren given as data (a dropped `date`) is quoted, so it is passed, not evaluated
216
255
  const quote: Cell = { t: K.Word, sym: intern('quote'), bind: host.rt.lib };
217
256
  const call: Cell[] = [{ t: K.Word, sym: intern(fn), bind: host.rt.user }, face, ...args.flatMap(a => ACTIVE.has(a.t) ? [quote, a] : [a])];
218
- const t = taskResult(spawn(host.sch, { data: call }, 0));
219
- t.catch(e => console.error(report(e as ObjectCell)));
220
- return t;
257
+ devLog.event(fn, face, args);
258
+ return taskResult(spawn(host.sch, { data: call }, 0)).catch((e: unknown) => {
259
+ if ((e as Cell).t === K.Error) whereInApp(e as ObjectCell, fn, face, args);
260
+ showError(report(e as ObjectCell));
261
+ return NONE;
262
+ });
263
+ }
264
+
265
+ /** The panel of errors trebol dev shows on the page; null until the first one. */
266
+ let devErrors: HTMLElement | null = null;
267
+
268
+ /**
269
+ * An error nobody caught: in the console and, when trebol dev serves the page (it adds
270
+ * `<meta name="trebol-dev">`), also on the page, so a broken app is not a blank page.
271
+ */
272
+ function showError(message: string): void {
273
+ console.error(message);
274
+ devLog.note('error', message);
275
+ if (document.querySelector('meta[name="trebol-dev"]') === null) return;
276
+ if (devErrors === null || !devErrors.isConnected) {
277
+ // a manual popover sits in the top layer, above open dialogs
278
+ const panel = el('section', 'tb-dev-errors');
279
+ panel.popover = 'manual';
280
+ panel.setAttribute('role', 'alert');
281
+ panel.setAttribute('aria-label', 'Trebol error');
282
+ const head = el('header');
283
+ const title = el('span');
284
+ title.textContent = 'Trebol error';
285
+ const close = el('button', 'tb-button');
286
+ close.type = 'button';
287
+ close.textContent = 'Close';
288
+ close.addEventListener('click', () => panel.remove());
289
+ panel.addEventListener('keydown', ev => { if (ev.key === 'Escape') panel.remove(); });
290
+ head.append(title, close);
291
+ panel.append(head);
292
+ document.body.append(panel);
293
+ panel.showPopover();
294
+ devErrors = panel;
295
+ }
296
+ const pre = el('pre');
297
+ pre.textContent = message;
298
+ devErrors.append(pre);
221
299
  }
222
300
 
223
301
  function el<T extends keyof HTMLElementTagNameMap>(tag: T, cls?: string): HTMLElementTagNameMap[T] {
@@ -233,7 +311,7 @@ function build(face: ObjectCell): HTMLElement {
233
311
  const m: Mounted = {
234
312
  face, el: null!, input: null, label: null, error: null, kids: get(face, 'pane'),
235
313
  box: null, rows: null, empty: null, button: null, radios: null, open: null, shown: undefined,
236
- typing: 0, typed: null,
314
+ typing: 0, typed: null, items: [], first: 0, end: 0, rowHeight: 0,
237
315
  };
238
316
  let node: HTMLElement;
239
317
  if (INPUTS.has(style)) {
@@ -244,6 +322,10 @@ function build(face: ObjectCell): HTMLElement {
244
322
  node = buildRadio(face, m);
245
323
  } else if (style === 'upload') {
246
324
  node = buildUpload(face, m);
325
+ } else if (style === 'photo') {
326
+ node = buildPhoto(face, m);
327
+ } else if (style === 'widget') {
328
+ node = buildWidget(face, m);
247
329
  } else if (style === 'lookup') {
248
330
  node = buildLookup(face, m);
249
331
  } else if (style === 'rich') {
@@ -319,8 +401,23 @@ function build(face: ObjectCell): HTMLElement {
319
401
  }
320
402
  case 'progress': node = buildProgress(m); break;
321
403
  case 'image': node = el('img', 'tb-image'); break;
404
+ case 'video': case 'audio': {
405
+ const media = el(style, `tb-${style}`) as HTMLMediaElement;
406
+ media.controls = true;
407
+ media.preload = 'metadata';
408
+ if (media instanceof HTMLVideoElement) media.playsInline = true;
409
+ node = media;
410
+ break;
411
+ }
412
+ case 'backdrop': {
413
+ // decoration behind its container: screen readers skip it
414
+ node = el('div', 'tb-backdrop');
415
+ node.setAttribute('aria-hidden', 'true');
416
+ break;
417
+ }
322
418
  case 'canvas': node = buildCanvas(m); break;
323
419
  case 'chart': node = buildChart(m); break;
420
+ case 'orbit': node = buildOrbit(m); break;
324
421
  case 'icon': node = el('span', 'tb-icon-face'); break;
325
422
  case 'table': case 'list': node = buildRows(face, style, m); break;
326
423
  case 'tree': node = buildTree(face, m); break;
@@ -357,6 +454,10 @@ function build(face: ObjectCell): HTMLElement {
357
454
  if (m.input !== null) byNode.set(m.input, m);
358
455
  byCtx.set(face.ctx, m);
359
456
  face.ctx.watch = dirty;
457
+ if (get(face, 'reactions').t === K.Block) {
458
+ reactors.add(m);
459
+ newReactor = true;
460
+ }
360
461
  listen(m, style);
361
462
  sync(m);
362
463
  return node;
@@ -389,6 +490,7 @@ function listen(m: Mounted, style: string): void {
389
490
  node.addEventListener('pointerleave', () => fireEvent(f, 'on-over', [['away?', TRUE]]));
390
491
  }
391
492
  if (handlerFor(f, 'on-dbl-click')) node.addEventListener('dblclick', () => fireEvent(f, 'on-dbl-click'));
493
+ if (handlerFor(f, 'on-end')) node.addEventListener('ended', () => fireEvent(f, 'on-end'));
392
494
  if (handlerFor(f, 'on-key')) {
393
495
  if (style === 'view') viewKeys = f;
394
496
  else node.addEventListener('keydown', ev => {
@@ -504,6 +606,11 @@ function sourceAt(start: Element): Source | null {
504
606
  const reorder = flag(m.face, 'reorder') && hostSorted(m.face) === null;
505
607
  if (!flag(m.face, 'drag') && !reorder) return null;
506
608
  const group = e.parentElement!;
609
+ if (m.open === null) {
610
+ // a table or list may not draw its first rows
611
+ const index = m.first + Array.prototype.indexOf.call(group.children, e);
612
+ return { face: m.face, el: e as HTMLElement, payload: row, within: reorder ? m : null, index, group: null };
613
+ }
507
614
  const index = Array.prototype.indexOf.call(group.children, e);
508
615
  return { face: m.face, el: e as HTMLElement, payload: row, within: reorder ? m : null, index, group };
509
616
  }
@@ -544,7 +651,12 @@ function insertionAt(m: Mounted, x: number, y: number): number {
544
651
  const r = e.getBoundingClientRect();
545
652
  if ((across ? x : y) > (across ? r.left + r.width / 2 : r.top + r.height / 2)) i++;
546
653
  }
547
- return i;
654
+ return m.first + i;
655
+ }
656
+
657
+ /** How many things a container places: all the rows of a table or list, drawn or not. */
658
+ function slotCount(m: Mounted): number {
659
+ return isData(m) && m.open === null ? m.items.length : slots(m).length;
548
660
  }
549
661
 
550
662
  let line: HTMLElement | null = null;
@@ -569,8 +681,9 @@ function indicate(t: Target | null): void {
569
681
  const across = horizontal(t.m);
570
682
  const all = t.group !== undefined ? Array.from(t.group.children) : slots(t.m);
571
683
  const box = (t.group ?? t.m.box ?? t.m.el).getBoundingClientRect();
572
- const before = all[t.index]?.getBoundingClientRect();
573
- const after = all[t.index - 1]?.getBoundingClientRect();
684
+ const at = t.group !== undefined ? t.index : t.index - t.m.first;
685
+ const before = all[at]?.getBoundingClientRect();
686
+ const after = all[at - 1]?.getBoundingClientRect();
574
687
  line.classList.toggle('tb-across', across);
575
688
  if (across) {
576
689
  const at = before && after ? (after.right + before.left) / 2 : before ? before.left - 3 : after ? after.right + 3 : box.left + 8;
@@ -601,7 +714,7 @@ async function reorder(m: Mounted, from: number, to: number, group?: HTMLElement
601
714
  await fire('ui-reorder', m.face, int(from + 1), int(to + 1), parent);
602
715
  syncDirty();
603
716
  if (!had) return;
604
- const e = (group !== undefined ? Array.from(group.children) as HTMLElement[] : slots(m))[to];
717
+ const e = group !== undefined ? group.children[to] as HTMLElement | undefined : slots(m)[to - m.first];
605
718
  const focusable = e?.matches('[tabindex], button, a, input, textarea, select') ? e : e?.querySelector<HTMLElement>('[tabindex], button, a, input, textarea, select');
606
719
  (focusable ?? null)?.focus();
607
720
  }
@@ -616,7 +729,7 @@ function moveTargets(face: ObjectCell, payload: Cell): MenuEntry[] {
616
729
  if (str(z.face, 'text') === null && z.el.querySelector('.tb-drop-zone') !== null) continue;
617
730
  out.push({
618
731
  text: str(z.face, 'text') ?? word(z.face, 'style') ?? '',
619
- run: () => void fire('ui-drop', z.face, payload, face, int(slots(z).length + 1), NONE),
732
+ run: () => void fire('ui-drop', z.face, payload, face, int(slotCount(z) + 1), NONE),
620
733
  });
621
734
  }
622
735
  return out;
@@ -691,13 +804,14 @@ function onPointerMove(ev: PointerEvent): void {
691
804
 
692
805
  /** Alt+Up and Alt+Down move the focused row or child inside a reorderable container. */
693
806
  function onReorderKey(ev: KeyboardEvent): void {
807
+ if (inDevtools(ev.target)) return;
694
808
  if (!ev.altKey || ev.ctrlKey || ev.metaKey || (ev.key !== 'ArrowUp' && ev.key !== 'ArrowDown')) return;
695
809
  const at = document.activeElement;
696
810
  if (at === null) return;
697
811
  const src = sourceAt(at);
698
812
  if (src === null || src.within === null) return;
699
813
  const to = src.index + (ev.key === 'ArrowUp' ? -1 : 1);
700
- if (to < 0 || to >= (src.group !== null ? src.group.children.length : slots(src.within).length)) return;
814
+ if (to < 0 || to >= (src.group !== null ? src.group.children.length : slotCount(src.within))) return;
701
815
  ev.preventDefault();
702
816
  seenKeys.add(ev);
703
817
  const group = src.group ?? undefined;
@@ -1113,6 +1227,7 @@ function shortcutLabel(spec: string): string {
1113
1227
 
1114
1228
  /** Shortcuts beat the browser's own keys; the view's on-key gets keys nobody handled. */
1115
1229
  function onKeyDown(ev: KeyboardEvent): void {
1230
+ if (inDevtools(ev.target)) return;
1116
1231
  const modal = Array.from(document.querySelectorAll('dialog[open]')).pop();
1117
1232
  for (const m of shortcuts) {
1118
1233
  if (!m.el.isConnected) { shortcuts.delete(m); continue; }
@@ -1128,6 +1243,7 @@ function onKeyDown(ev: KeyboardEvent): void {
1128
1243
  }
1129
1244
 
1130
1245
  function onViewKey(ev: KeyboardEvent): void {
1246
+ if (inDevtools(ev.target)) return;
1131
1247
  if (viewKeys === null || seenKeys.has(ev) || keyCell(ev) === null) return;
1132
1248
  fireEvent(viewKeys, 'on-key', keyWords(ev));
1133
1249
  }
@@ -1202,6 +1318,7 @@ function buildInput(face: ObjectCell, style: string, m: Mounted): HTMLElement {
1202
1318
  if (style === 'password') i.autocomplete = 'new-password';
1203
1319
  input = i;
1204
1320
  }
1321
+ input.addEventListener('focus', () => hadCaret.add(input));
1205
1322
  input.id = id;
1206
1323
  const error = el('div', 'tb-error');
1207
1324
  error.id = `${id}-error`;
@@ -1225,7 +1342,8 @@ function buildInput(face: ObjectCell, style: string, m: Mounted): HTMLElement {
1225
1342
  if (style === 'money') input.addEventListener('focus', () => {
1226
1343
  if (!flag(face, 'readonly')) input.value = editLocal(get(face, 'value'), activeLanguage(host.rt));
1227
1344
  });
1228
- input.addEventListener('blur', () => void fire('ui-blur', face));
1345
+ // going to the dev tools is not leaving the field: it shows no error for it
1346
+ input.addEventListener('blur', ev => { if (!inDevtools((ev as FocusEvent).relatedTarget)) void fire('ui-blur', face); });
1229
1347
  const iconWord = style === 'area' || style === 'choice' ? null : iconName(face);
1230
1348
  const svg = iconWord !== null ? icon(iconWord) : null;
1231
1349
  if (style === 'date') {
@@ -1352,24 +1470,41 @@ function buildUpload(face: ObjectCell, m: Mounted): HTMLElement {
1352
1470
  error.setAttribute('aria-live', 'polite');
1353
1471
  choose.setAttribute('aria-describedby', error.id);
1354
1472
  const list = el('ul', 'tb-upload-list');
1355
- // how far the files went up, while a fetch with progress: the upload sends them
1356
- label.id = `${id}-label`;
1357
- const track = el('div', 'tb-progress tb-upload-progress');
1358
- track.setAttribute('role', 'progressbar');
1359
- track.setAttribute('aria-valuemin', '0');
1360
- track.setAttribute('aria-valuemax', '100');
1361
- track.setAttribute('aria-labelledby', label.id);
1362
- track.hidden = true;
1363
- track.append(el('div', 'tb-progress-bar'));
1473
+ const track = sentBar(label, id);
1364
1474
  choose.addEventListener('click', () => picker.click());
1365
1475
  picker.addEventListener('change', () => {
1366
1476
  const files = [...(picker.files ?? [])];
1367
1477
  picker.value = '';
1368
1478
  if (files.length > 0) chooseFiles(face, files);
1369
1479
  });
1480
+ dropFiles(face, zone, choose);
1481
+ zone.append(choose, hint, picker);
1482
+ control.append(zone, list, track, error);
1483
+ wrap.append(label, control);
1484
+ m.label = label;
1485
+ m.error = error;
1486
+ m.button = choose;
1487
+ m.box = list;
1488
+ return wrap;
1489
+ }
1490
+
1491
+ /** The accept list of an upload: extensions ("pdf") and types ("image/*"); a photo takes images unless told. */
1492
+ function acceptList(face: ObjectCell): string[] {
1493
+ const a = get(face, 'accept');
1494
+ if (a.t !== K.Block && word(face, 'style') === 'photo') return ['image/*'];
1495
+ return a.t === K.Block ? a.s.data.slice(a.i).map(x => form(x).trim().toLowerCase()).filter(x => x !== '') : [];
1496
+ }
1497
+
1498
+ /** The picker's accept attribute for an accept list. */
1499
+ function pickerAccept(list: string[]): string {
1500
+ return list.map(x => (x.includes('/') || x.startsWith('.') ? x : `.${x}`)).join(',');
1501
+ }
1502
+
1503
+ /** Lets a zone take files dropped on it, unless its button is disabled. */
1504
+ function dropFiles(face: ObjectCell, zone: HTMLElement, button: HTMLButtonElement): void {
1370
1505
  const hasFiles = (ev: DragEvent): boolean => ev.dataTransfer?.types.includes('Files') === true;
1371
1506
  zone.addEventListener('dragover', ev => {
1372
- if (!hasFiles(ev) || choose.disabled) return;
1507
+ if (!hasFiles(ev) || button.disabled) return;
1373
1508
  ev.preventDefault();
1374
1509
  ev.dataTransfer!.dropEffect = 'copy';
1375
1510
  zone.classList.add('tb-drop-over');
@@ -1379,24 +1514,294 @@ function buildUpload(face: ObjectCell, m: Mounted): HTMLElement {
1379
1514
  });
1380
1515
  zone.addEventListener('drop', ev => {
1381
1516
  zone.classList.remove('tb-drop-over');
1382
- if (!hasFiles(ev) || choose.disabled) return;
1517
+ if (!hasFiles(ev) || button.disabled) return;
1383
1518
  ev.preventDefault();
1384
1519
  chooseFiles(face, [...ev.dataTransfer!.files]);
1385
1520
  });
1386
- zone.append(choose, hint, picker);
1387
- control.append(zone, list, track, error);
1521
+ }
1522
+
1523
+ /** The bar of how far the files went up, while a fetch with progress sends them. */
1524
+ function sentBar(label: HTMLElement, id: string): HTMLElement {
1525
+ label.id = `${id}-label`;
1526
+ const track = el('div', 'tb-progress tb-upload-progress');
1527
+ track.setAttribute('role', 'progressbar');
1528
+ track.setAttribute('aria-valuemin', '0');
1529
+ track.setAttribute('aria-valuemax', '100');
1530
+ track.setAttribute('aria-labelledby', label.id);
1531
+ track.hidden = true;
1532
+ track.append(el('div', 'tb-progress-bar'));
1533
+ return track;
1534
+ }
1535
+
1536
+ function syncSent(m: Mounted): void {
1537
+ const track = m.el.querySelector<HTMLElement>('.tb-upload-progress')!;
1538
+ const sent = get(m.face, 'sent');
1539
+ const part = fraction(sent) ?? 0;
1540
+ track.hidden = sent.t === K.None;
1541
+ track.setAttribute('aria-valuenow', String(Math.round(part * 100)));
1542
+ (track.firstChild as HTMLElement).style.width = `${part * 100}%`;
1543
+ }
1544
+
1545
+ // A photo: the image itself, a button to choose one and another to take it away. The
1546
+ // image chosen shows from the browser's memory; one kept elsewhere, from its address.
1547
+
1548
+ // A video or a sound: the browser's own player. Captions are one track per language;
1549
+ // the active language's is the one shown, and it follows set-language.
1550
+
1551
+ /** A video's captions as [language, address] pairs: a file alone is in the active language. */
1552
+ function captionTracks(f: ObjectCell): [string, string][] {
1553
+ const c = get(f, 'captions');
1554
+ if (c.t === K.File || c.t === K.Url || c.t === K.String) return [[activeLanguage(host.rt), form(c)]];
1555
+ if (c.t !== K.Block) return [];
1556
+ const d = c.s.data.slice(c.i);
1557
+ const out: [string, string][] = [];
1558
+ for (let i = 0; i + 1 < d.length; i += 2) out.push([form(d[i]!), form(d[i + 1]!)]);
1559
+ return out;
1560
+ }
1561
+
1562
+ function syncMedia(m: Mounted): void {
1563
+ const f = m.face;
1564
+ const media = m.el as HTMLMediaElement;
1565
+ const src = str(f, 'value') ?? '';
1566
+ if (media.getAttribute('src') !== src) media.src = src;
1567
+ const t = str(f, 'text');
1568
+ if (t !== null) media.setAttribute('aria-label', t);
1569
+ else media.removeAttribute('aria-label');
1570
+ media.loop = flag(f, 'looping');
1571
+ // browsers only let what plays on its own do so without sound
1572
+ const auto = flag(f, 'autoplay');
1573
+ media.muted = flag(f, 'silent') || auto;
1574
+ media.autoplay = auto;
1575
+ if (!(media instanceof HTMLVideoElement)) return;
1576
+ const poster = str(f, 'poster') ?? '';
1577
+ if (media.getAttribute('poster') !== poster) media.poster = poster;
1578
+ const lang = activeLanguage(host.rt);
1579
+ const tracks = captionTracks(f);
1580
+ const names = new Intl.DisplayNames([lang], { type: 'language' });
1581
+ const now = Array.from(media.querySelectorAll('track'));
1582
+ if (now.map(x => `${x.srclang} ${x.getAttribute('src')}`).join('|') !== tracks.map(([l, s]) => `${l} ${s}`).join('|')) {
1583
+ media.replaceChildren(...tracks.map(([l, s]) => {
1584
+ const track = el('track') as HTMLTrackElement;
1585
+ track.kind = 'captions';
1586
+ track.srclang = l;
1587
+ track.src = s;
1588
+ return track;
1589
+ }));
1590
+ }
1591
+ // the captions shown, if any, follow the active language
1592
+ const showing = Array.from(media.textTracks).some(x => x.mode === 'showing');
1593
+ const pick = tracks.findIndex(([l]) => l === lang);
1594
+ media.querySelectorAll('track').forEach((track, i) => {
1595
+ track.label = names.of(track.srclang) ?? track.srclang;
1596
+ track.default = i === Math.max(0, pick);
1597
+ if (showing) track.track.mode = i === Math.max(0, pick) ? 'showing' : 'disabled';
1598
+ });
1599
+ }
1600
+
1601
+ /** The address that shows each chosen file, made once and freed when the photo shows another. */
1602
+ const shownUrls = new WeakMap<HTMLElement, { blob: Blob; url: string }>();
1603
+
1604
+ function buildPhoto(face: ObjectCell, m: Mounted): HTMLElement {
1605
+ const id = `tb-${nextId++}`;
1606
+ const wrap = el('div', 'tb-field');
1607
+ const label = el('label', 'tb-label');
1608
+ label.htmlFor = id;
1609
+ const control = el('div', 'tb-control');
1610
+ const zone = el('div', 'tb-photo');
1611
+ // the frame opens the picker for a pointer; the keyboard has the button
1612
+ const frame = el('div', 'tb-photo-frame');
1613
+ frame.addEventListener('click', () => { if (!choose.disabled) picker.click(); });
1614
+ const picker = el('input');
1615
+ picker.type = 'file';
1616
+ picker.hidden = true;
1617
+ picker.tabIndex = -1;
1618
+ const actions = el('div', 'tb-photo-actions');
1619
+ const choose = el('button', 'tb-button');
1620
+ choose.type = 'button';
1621
+ choose.id = id;
1622
+ const svg = icon('upload');
1623
+ if (svg !== null) choose.append(svg);
1624
+ choose.append(el('span'));
1625
+ const remove = el('button', 'tb-button tb-photo-remove');
1626
+ remove.type = 'button';
1627
+ remove.addEventListener('click', () => {
1628
+ choose.focus();
1629
+ void fire('ui-remove-file', face, int(1));
1630
+ });
1631
+ const error = el('div', 'tb-error');
1632
+ error.id = `${id}-error`;
1633
+ error.setAttribute('aria-live', 'polite');
1634
+ choose.setAttribute('aria-describedby', error.id);
1635
+ choose.addEventListener('click', () => picker.click());
1636
+ picker.addEventListener('change', () => {
1637
+ const files = [...(picker.files ?? [])];
1638
+ picker.value = '';
1639
+ if (files.length > 0) chooseFiles(face, files);
1640
+ });
1641
+ dropFiles(face, zone, choose);
1642
+ actions.append(choose, remove);
1643
+ zone.append(frame, actions, picker);
1644
+ control.append(zone, sentBar(label, id), error);
1388
1645
  wrap.append(label, control);
1389
1646
  m.label = label;
1390
1647
  m.error = error;
1391
1648
  m.button = choose;
1392
- m.box = list;
1649
+ m.box = frame;
1393
1650
  return wrap;
1394
1651
  }
1395
1652
 
1396
- /** The accept list of an upload: extensions ("pdf") and types ("image/*"). */
1397
- function acceptList(face: ObjectCell): string[] {
1398
- const a = get(face, 'accept');
1399
- return a.t === K.Block ? a.s.data.slice(a.i).map(x => form(x).trim().toLowerCase()).filter(x => x !== '') : [];
1653
+ /** What a photo shows: the image chosen, or the address of one kept elsewhere; null for none. */
1654
+ function photoSrc(frame: HTMLElement, v: Cell): string | null {
1655
+ const kept = shownUrls.get(frame);
1656
+ const file = v.t === K.Object ? handleOf<Blob>(get(v as ObjectCell, 'file'), 'file') : null;
1657
+ if (file !== null && kept !== undefined && kept.blob === file) return kept.url;
1658
+ if (kept !== undefined) {
1659
+ URL.revokeObjectURL(kept.url);
1660
+ shownUrls.delete(frame);
1661
+ }
1662
+ if (file !== null) {
1663
+ const url = URL.createObjectURL(file);
1664
+ shownUrls.set(frame, { blob: file, url });
1665
+ return url;
1666
+ }
1667
+ return v.t === K.String || v.t === K.Url || v.t === K.File ? form(v) : null;
1668
+ }
1669
+
1670
+ function syncPhoto(m: Mounted, err: string | null): void {
1671
+ const f = m.face;
1672
+ const t = str(f, 'text') ?? '';
1673
+ m.label!.textContent = t;
1674
+ m.label!.classList.toggle('tb-required', required(f));
1675
+ const readonly = flag(f, 'readonly');
1676
+ const choose = m.button!;
1677
+ choose.disabled = flag(f, 'disabled') || readonly;
1678
+ choose.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
1679
+ const frame = m.box!;
1680
+ frame.classList.toggle('tb-round', flag(f, 'round'));
1681
+ frame.classList.toggle('tb-photo-pick', !choose.disabled);
1682
+ const src = photoSrc(frame, get(f, 'value'));
1683
+ let img = frame.querySelector('img');
1684
+ if (src === null) {
1685
+ if (img !== null || frame.firstChild === null) {
1686
+ const svg = icon(flag(f, 'round') ? 'user' : 'image');
1687
+ frame.replaceChildren(...(svg !== null ? [svg] : []));
1688
+ }
1689
+ } else {
1690
+ if (img === null) {
1691
+ img = el('img') as HTMLImageElement;
1692
+ frame.replaceChildren(img);
1693
+ }
1694
+ if (img.getAttribute('src') !== src) img.src = src;
1695
+ img.alt = t;
1696
+ }
1697
+ (choose.lastChild as HTMLElement).textContent = own(src === null ? 'choose-photo' : 'change-photo');
1698
+ const remove = m.el.querySelector<HTMLButtonElement>('.tb-photo-remove')!;
1699
+ remove.textContent = own('remove-photo');
1700
+ remove.hidden = src === null || readonly;
1701
+ remove.disabled = choose.disabled;
1702
+ // read only, there is nothing to choose: only the photo is left
1703
+ (m.el.querySelector('.tb-photo-actions') as HTMLElement).hidden = readonly;
1704
+ (m.el.querySelector('input[type="file"]') as HTMLInputElement).accept = pickerAccept(acceptList(f));
1705
+ m.error!.textContent = err ?? '';
1706
+ syncSent(m);
1707
+ }
1708
+
1709
+ // --- widget: an element the page's JavaScript defines ----------------------------
1710
+ //
1711
+ // The element is made by its tag, once the page has defined it (import %geo-map.js).
1712
+ // The face's value is the element's value property, both ways, as JSON; its props set
1713
+ // properties. Its change event gives the value back, and any other on-xxx of the face
1714
+ // listens to the element's event xxx, with the event's detail. The theme's custom
1715
+ // properties (--tb-*) reach it, as they reach every element of the page.
1716
+
1717
+ /** What was last given to or taken from each widget, as JSON, so a repaint sets only what changed. */
1718
+ const widgetSet = new WeakMap<HTMLElement, { value: string; props: string }>();
1719
+
1720
+ /** Events every face has, which the host listens to itself. */
1721
+ const FACE_EVENTS = new Set(['on-change', 'on-focus', 'on-unfocus', 'on-over', 'on-dbl-click', 'on-key', 'on-end',
1722
+ 'on-drop', 'on-reorder', 'on-menu', 'on-select']);
1723
+
1724
+ /** A JavaScript value as Trebol's, as JSON carries it; none for what JSON cannot write. */
1725
+ function fromJs(x: unknown): Cell {
1726
+ let json: string | undefined;
1727
+ try {
1728
+ json = JSON.stringify(x);
1729
+ } catch {
1730
+ json = undefined;
1731
+ }
1732
+ if (json === undefined) return NONE;
1733
+ const v = parseJson(json);
1734
+ return typeof v === 'string' ? NONE : v;
1735
+ }
1736
+
1737
+ function buildWidget(face: ObjectCell, m: Mounted): HTMLElement {
1738
+ const id = `tb-${nextId++}`;
1739
+ const wrap = el('div', 'tb-field');
1740
+ const label = el('label', 'tb-label');
1741
+ label.htmlFor = id;
1742
+ const control = el('div', 'tb-control');
1743
+ let node: HTMLElement;
1744
+ try {
1745
+ node = document.createElement(str(face, 'tag') ?? 'div');
1746
+ } catch {
1747
+ // a tag that is no element's name
1748
+ node = el('div');
1749
+ }
1750
+ node.classList.add('tb-widget');
1751
+ node.id = id;
1752
+ const error = el('div', 'tb-error');
1753
+ error.id = `${id}-error`;
1754
+ error.setAttribute('aria-live', 'polite');
1755
+ node.setAttribute('aria-describedby', error.id);
1756
+ widgetSet.set(node, { value: '', props: '' });
1757
+ node.addEventListener('change', ev => {
1758
+ if (ev.target !== node) return;
1759
+ const v = fromJs((node as unknown as { value?: unknown }).value);
1760
+ widgetSet.get(node)!.value = toJson(v);
1761
+ void fire('ui-input', face, v);
1762
+ });
1763
+ const events = get(face, 'events');
1764
+ if (events.t === K.Block) {
1765
+ for (const w of events.s.data) {
1766
+ const name = w.t === K.Word ? spell((w as WordCell).sym).toLowerCase() : '';
1767
+ if (!name.startsWith('on-') || FACE_EVENTS.has(name)) continue;
1768
+ node.addEventListener(name.slice(3), ev => fireEvent(face, name, [['detail', fromJs((ev as CustomEvent).detail)]]));
1769
+ }
1770
+ }
1771
+ control.append(node, error);
1772
+ wrap.append(label, control);
1773
+ m.label = label;
1774
+ m.error = error;
1775
+ m.box = node;
1776
+ return wrap;
1777
+ }
1778
+
1779
+ function syncWidget(m: Mounted, err: string | null): void {
1780
+ const f = m.face;
1781
+ const t = str(f, 'text') ?? '';
1782
+ m.label!.textContent = t;
1783
+ m.label!.hidden = t === '';
1784
+ m.label!.classList.toggle('tb-required', required(f));
1785
+ const node = m.box! as HTMLElement & { value?: unknown; disabled?: boolean; readOnly?: boolean };
1786
+ const set = widgetSet.get(node)!;
1787
+ const props = get(f, 'props');
1788
+ const propsJson = props.t === K.Object || props.t === K.Map ? toJson(props) : '{}';
1789
+ if (propsJson !== set.props) {
1790
+ Object.assign(node, JSON.parse(propsJson) as object);
1791
+ set.props = propsJson;
1792
+ }
1793
+ const valueJson = toJson(get(f, 'value'));
1794
+ if (valueJson !== set.value) {
1795
+ node.value = JSON.parse(valueJson) as unknown;
1796
+ set.value = valueJson;
1797
+ }
1798
+ const disabled = flag(f, 'disabled');
1799
+ node.toggleAttribute('disabled', disabled);
1800
+ if ('disabled' in node) node.disabled = disabled;
1801
+ if ('readOnly' in node) node.readOnly = flag(f, 'readonly');
1802
+ node.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
1803
+ if (t !== '') node.setAttribute('aria-label', t);
1804
+ m.error!.textContent = err ?? '';
1400
1805
  }
1401
1806
 
1402
1807
  function accepts(file: File, list: string[]): boolean {
@@ -1445,7 +1850,7 @@ function syncUpload(m: Mounted, err: string | null): void {
1445
1850
  (zone.querySelector('.tb-upload-hint') as HTMLElement).textContent = own(many ? 'drop-files' : 'drop-file');
1446
1851
  const picker = zone.querySelector('input') as HTMLInputElement;
1447
1852
  picker.multiple = many;
1448
- picker.accept = acceptList(f).map(x => (x.includes('/') || x.startsWith('.') ? x : `.${x}`)).join(',');
1853
+ picker.accept = pickerAccept(acceptList(f));
1449
1854
  m.error!.textContent = err ?? '';
1450
1855
  const v = get(f, 'value');
1451
1856
  const files = v.t === K.Block ? v.s.data.slice(v.i).filter(x => x.t === K.Object) as ObjectCell[] : [];
@@ -1490,11 +1895,7 @@ function syncUpload(m: Mounted, err: string | null): void {
1490
1895
  });
1491
1896
  m.box!.replaceChildren(...items);
1492
1897
  m.box!.hidden = items.length === 0;
1493
- const track = m.el.querySelector<HTMLElement>('.tb-upload-progress')!;
1494
- const sent = fraction(get(f, 'sent'));
1495
- track.hidden = get(f, 'sent').t === K.None;
1496
- track.setAttribute('aria-valuenow', String(Math.round((sent ?? 0) * 100)));
1497
- (track.firstChild as HTMLElement).style.width = `${(sent ?? 0) * 100}%`;
1898
+ syncSent(m);
1498
1899
  }
1499
1900
 
1500
1901
  // A lookup: a field where the user types and chooses among what on-search finds, as in
@@ -1962,6 +2363,417 @@ function drawChart(m: Mounted): void {
1962
2363
  p.table.tBodies[0]!.append(...body);
1963
2364
  }
1964
2365
 
2366
+ // --- orbits -------------------------------------------------------------------------------
2367
+
2368
+ interface OrbitVis {
2369
+ key: string;
2370
+ /** Moved and faded; `inner`, inside it, is scaled by the radius. Chrome draws a faded group of tiny units blurred, so the two stay apart. */
2371
+ g: SVGGElement;
2372
+ inner: SVGGElement;
2373
+ role: Role;
2374
+ cur: Place;
2375
+ from: Place;
2376
+ to: Place;
2377
+ dying: boolean;
2378
+ }
2379
+
2380
+ interface OrbitLine { a: string; b: string; path: SVGPathElement; text: SVGTextElement | null; curve: number }
2381
+
2382
+ interface OrbitState {
2383
+ svg: SVGSVGElement;
2384
+ defs: SVGDefsElement;
2385
+ world: SVGGElement;
2386
+ lines: SVGGElement;
2387
+ bubbles: SVGGElement;
2388
+ vis: Map<string, OrbitVis>;
2389
+ edges: OrbitLine[];
2390
+ /** What it shows: the spec as read, and a signature of it that tells when it changed. */
2391
+ spec: OrbitSpec;
2392
+ signature: string;
2393
+ /** The page of neighbours on show, and the focus it is a page of. */
2394
+ page: number;
2395
+ pageOf: string | null;
2396
+ box: Box;
2397
+ /** The bubbles of the last layout, and how many neighbours were left off its page. */
2398
+ placed: Placed[];
2399
+ left: number;
2400
+ cam: { x: number; y: number; s: number };
2401
+ camFrom: { x: number; y: number; s: number } | null;
2402
+ camTo: { x: number; y: number; s: number } | null;
2403
+ anim: number;
2404
+ /** The node the person picked last: new neighbours grow from it. */
2405
+ picked: string | null;
2406
+ /** The pick came from the keyboard: once redrawn, the focus goes back to the orbit. */
2407
+ byKey: boolean;
2408
+ dragged: boolean;
2409
+ gradients: Map<string, [string, string]>;
2410
+ width: number;
2411
+ height: number;
2412
+ }
2413
+
2414
+ let orbitCount = 0;
2415
+
2416
+ /** An orbit: an SVG the size of the face, a world the camera moves, edges under the bubbles. */
2417
+ function buildOrbit(m: Mounted): HTMLElement {
2418
+ const node = el('div', 'tb-orbit');
2419
+ const svg = document.createElementNS(SVG_NS, 'svg') as SVGSVGElement;
2420
+ svg.setAttribute('role', 'group');
2421
+ svg.setAttribute('tabindex', '-1');
2422
+ const defs = document.createElementNS(SVG_NS, 'defs') as SVGDefsElement;
2423
+ const world = document.createElementNS(SVG_NS, 'g') as SVGGElement;
2424
+ const lines = document.createElementNS(SVG_NS, 'g') as SVGGElement;
2425
+ const bubbles = document.createElementNS(SVG_NS, 'g') as SVGGElement;
2426
+ world.append(lines, bubbles);
2427
+ svg.append(defs, world);
2428
+ node.append(svg);
2429
+ const st: OrbitState = {
2430
+ svg, defs, world, lines, bubbles, vis: new Map(), edges: [], spec: readOrbit(NONE).spec, signature: '', page: 0, pageOf: null,
2431
+ box: { x0: -100, y0: -100, x1: 100, y1: 100 }, placed: [], left: 0, cam: { x: 0, y: 0, s: 1 }, camFrom: null, camTo: null, anim: 0, picked: null, byKey: false, dragged: false,
2432
+ gradients: new Map(), width: 0, height: 0,
2433
+ };
2434
+ m.kids = st;
2435
+ orbitCamera(m, st);
2436
+ orbitKeys(m, st);
2437
+ if (typeof ResizeObserver !== 'undefined') {
2438
+ new ResizeObserver(() => {
2439
+ if (svg.clientWidth === st.width && svg.clientHeight === st.height) return;
2440
+ st.width = svg.clientWidth;
2441
+ st.height = svg.clientHeight;
2442
+ // a move under way ends where the new size fits; titles take the new zoom
2443
+ const fit = fitCamera(st.width, st.height, st.box);
2444
+ if (st.camTo !== null) st.camTo = fit;
2445
+ else st.cam = fit;
2446
+ orbitDressAll(m, st, fit.s);
2447
+ orbitApplyCam(st);
2448
+ orbitDrawEdges(st);
2449
+ }).observe(svg);
2450
+ }
2451
+ return node;
2452
+ }
2453
+
2454
+ /** Drag to pan, Ctrl and the wheel (or a pinch) to zoom about the pointer, double click to fit again. */
2455
+ function orbitCamera(m: Mounted, st: OrbitState): void {
2456
+ const { svg } = st;
2457
+ let drag: { x: number; y: number; cx: number; cy: number; id: number } | null = null;
2458
+ svg.addEventListener('pointerdown', ev => {
2459
+ if (ev.button !== 0) return;
2460
+ drag = { x: ev.clientX, y: ev.clientY, cx: st.cam.x, cy: st.cam.y, id: ev.pointerId };
2461
+ st.dragged = false;
2462
+ });
2463
+ svg.addEventListener('pointermove', ev => {
2464
+ if (drag === null || ev.pointerId !== drag.id) return;
2465
+ const dx = ev.clientX - drag.x;
2466
+ const dy = ev.clientY - drag.y;
2467
+ if (!st.dragged && Math.hypot(dx, dy) > 4) {
2468
+ st.dragged = true;
2469
+ svg.setPointerCapture(ev.pointerId);
2470
+ svg.classList.add('tb-orbit-panning');
2471
+ }
2472
+ if (st.dragged) {
2473
+ st.cam = { ...st.cam, x: drag.cx + dx, y: drag.cy + dy };
2474
+ orbitApplyCam(st);
2475
+ }
2476
+ });
2477
+ const end = (): void => {
2478
+ drag = null;
2479
+ svg.classList.remove('tb-orbit-panning');
2480
+ // the click that ends a drag picks nothing
2481
+ setTimeout(() => { st.dragged = false; }, 0);
2482
+ };
2483
+ svg.addEventListener('pointerup', end);
2484
+ svg.addEventListener('pointercancel', end);
2485
+ svg.addEventListener('wheel', ev => {
2486
+ // the page scrolls past an orbit; with Ctrl (or a pinch), or when it fills the window, the wheel zooms
2487
+ if (!ev.ctrlKey && !ev.metaKey && !flag(m.face, 'fit')) return;
2488
+ ev.preventDefault();
2489
+ const box = svg.getBoundingClientRect();
2490
+ const ox = box.width / 2 + st.cam.x;
2491
+ const oy = box.height / 2 + st.cam.y;
2492
+ const s = Math.max(0.15, Math.min(4, st.cam.s * Math.exp(-ev.deltaY * (ev.ctrlKey ? 0.01 : 0.0015))));
2493
+ const px = ev.clientX - box.left;
2494
+ const py = ev.clientY - box.top;
2495
+ const wx = (px - ox) / st.cam.s;
2496
+ const wy = (py - oy) / st.cam.s;
2497
+ st.cam = { x: px - box.width / 2 - wx * s, y: py - box.height / 2 - wy * s, s };
2498
+ orbitApplyCam(st);
2499
+ }, { passive: false });
2500
+ svg.addEventListener('dblclick', ev => {
2501
+ if ((ev.target as Element).closest('.tb-orbit-node') !== null) return;
2502
+ st.camFrom = { ...st.cam };
2503
+ st.camTo = fitCamera(st.width, st.height, st.box);
2504
+ orbitAnimate(st, 500);
2505
+ });
2506
+ }
2507
+
2508
+ /** Tab goes through the neighbours, Enter or Space picks one, Escape or Backspace steps back. */
2509
+ function orbitKeys(m: Mounted, st: OrbitState): void {
2510
+ st.svg.addEventListener('keydown', ev => {
2511
+ const g = (ev.target as Element).closest('.tb-orbit-node');
2512
+ if ((ev.key === 'Enter' || ev.key === ' ') && g !== null) {
2513
+ ev.preventDefault();
2514
+ orbitPick(m, st, (g as SVGGElement).dataset['key']!, true);
2515
+ } else if ((ev.key === 'Escape' || ev.key === 'Backspace') && st.spec.trail.length > 0) {
2516
+ const back = [...st.spec.trail].reverse().find(k => st.spec.nodes.has(k));
2517
+ if (back === undefined) return;
2518
+ ev.preventDefault();
2519
+ ev.stopPropagation();
2520
+ orbitPick(m, st, back, true);
2521
+ }
2522
+ });
2523
+ }
2524
+
2525
+ /** The person picked a bubble: a neighbour enters, the trail steps back, "+N more" turns the page. */
2526
+ function orbitPick(m: Mounted, st: OrbitState, key: string, byKey: boolean): void {
2527
+ if (flag(m.face, 'disabled')) return;
2528
+ const v = st.vis.get(key);
2529
+ if (v === undefined || v.dying) return;
2530
+ if (v.role === 'more') {
2531
+ st.page++;
2532
+ st.picked = st.spec.focus;
2533
+ orbitRender(m, st);
2534
+ return;
2535
+ }
2536
+ const node = st.spec.nodes.get(key);
2537
+ if (node === undefined || v.role === 'focus') return;
2538
+ st.picked = key;
2539
+ st.byKey = byKey;
2540
+ void fire('ui-orbit', m.face, node.id, v.role === 'trail' ? TRUE : FALSE);
2541
+ }
2542
+
2543
+ function syncOrbit(m: Mounted): void {
2544
+ const st = m.kids as OrbitState;
2545
+ const { spec, error } = readOrbit(get(m.face, 'data'));
2546
+ if (error !== null) console.warn(`Trebol: ${error}`);
2547
+ const t = str(m.face, 'text');
2548
+ const focus = spec.focus === null ? undefined : spec.nodes.get(spec.focus);
2549
+ const focusTitle = focus === undefined ? '' : translate(focus.title, host.rt);
2550
+ st.svg.setAttribute('aria-label', t === null ? focusTitle : focusTitle === '' ? t : `${t}: ${focusTitle}`);
2551
+ // a repaint of the same thing in the same language keeps what is on screen, moving or not
2552
+ const signature = orbitSignature(spec);
2553
+ if (signature === st.signature) return;
2554
+ st.signature = signature;
2555
+ st.spec = spec;
2556
+ if (spec.focus !== st.pageOf) {
2557
+ st.page = 0;
2558
+ st.pageOf = spec.focus;
2559
+ }
2560
+ orbitRender(m, st);
2561
+ }
2562
+
2563
+ function orbitSignature(spec: OrbitSpec): string {
2564
+ const tx = (c: Cell | null): string => (c === null ? '' : translate(c, host.rt));
2565
+ const nodes = [...spec.nodes.values()].map(n => [n.key, tx(n.title), n.color, n.count, n.many, n.dashed, n.steps, n.at].join('\u0002'));
2566
+ const edges = spec.edges.map(e => [e.from, e.to, tx(e.label), e.look].join('\u0002'));
2567
+ return [spec.focus ?? '', nodes.join('\u0001'), edges.join('\u0001'), spec.trail.join('\u0001')].join('\u0000');
2568
+ }
2569
+
2570
+ /** The ids of the gradients of a color, made the first time it is used. */
2571
+ function orbitGradients(st: OrbitState, color: string): [string, string] {
2572
+ let ids = st.gradients.get(color);
2573
+ if (ids === undefined) {
2574
+ const n = `tb-orbit${orbitCount++}`;
2575
+ ids = [`${n}-body`, `${n}-halo`];
2576
+ st.gradients.set(color, ids);
2577
+ st.defs.append(...gradients(color, ids[0], ids[1]).map(svgNode));
2578
+ }
2579
+ return ids;
2580
+ }
2581
+
2582
+ /** Moves from what is on screen to what the spec says: bubbles that stay move, new ones grow from the one picked, the rest fade. */
2583
+ function orbitRender(m: Mounted, st: OrbitState): void {
2584
+ const { spec } = st;
2585
+ const lay = layoutOrbit(spec, st.page);
2586
+ st.box = lay.box;
2587
+ const want = new Map(lay.placed.map(p => [p.key, p]));
2588
+ for (const [k, v] of [...st.vis]) {
2589
+ if (v.dying) continue;
2590
+ const p = want.get(k);
2591
+ if (p === undefined || p.role !== v.role || p.role === 'more') {
2592
+ // gone, or something else now: it fades where it is, and a new one takes its key
2593
+ v.dying = true;
2594
+ v.from = { ...v.cur };
2595
+ v.to = { ...v.cur, r: v.cur.r * (p === undefined ? 0.4 : 1), o: 0 };
2596
+ v.g.setAttribute('tabindex', '-1');
2597
+ v.g.setAttribute('aria-hidden', 'true');
2598
+ st.vis.delete(k);
2599
+ st.vis.set(`${k}\u0000old${orbitCount++}`, v);
2600
+ if (p !== undefined) st.vis.set(k, orbitBubble(m, st, p, { ...v.cur }));
2601
+ } else {
2602
+ v.from = { ...v.cur };
2603
+ v.to = p;
2604
+ }
2605
+ }
2606
+ const was = st.picked === null ? undefined : [...st.vis.values()].find(v => v.key === st.picked);
2607
+ const spawn = was !== undefined ? was.cur : { x: 0, y: 0 };
2608
+ for (const p of lay.placed) {
2609
+ if (st.vis.has(p.key)) continue;
2610
+ st.vis.set(p.key, orbitBubble(m, st, p, { x: spawn.x, y: spawn.y, r: p.r * 0.2, o: 0 }));
2611
+ }
2612
+ st.width = st.svg.clientWidth;
2613
+ st.height = st.svg.clientHeight;
2614
+ st.camFrom = { ...st.cam };
2615
+ st.camTo = fitCamera(st.width || 600, st.height || 480, lay.box);
2616
+ st.placed = lay.placed;
2617
+ st.left = lay.left;
2618
+ orbitDressAll(m, st, st.camTo.s);
2619
+ st.bubbles.append(...lay.placed.map(p => st.vis.get(p.key)!.g));
2620
+ st.picked = null;
2621
+ orbitAnimate(st, matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 900);
2622
+ if (st.byKey) {
2623
+ st.byKey = false;
2624
+ st.svg.focus();
2625
+ }
2626
+ }
2627
+
2628
+ /** Every bubble on show drawn anew (its title, hints and size may have changed), and the edges, for the camera's zoom. */
2629
+ function orbitDressAll(m: Mounted, st: OrbitState, scale: number): void {
2630
+ for (const p of st.placed) {
2631
+ const v = st.vis.get(p.key);
2632
+ if (v !== undefined) orbitDress(m, st, v, p, st.left, scale);
2633
+ }
2634
+ orbitEdges(st, st.placed, scale);
2635
+ }
2636
+
2637
+ function orbitBubble(m: Mounted, st: OrbitState, p: Placed, start: Place): OrbitVis {
2638
+ const g = document.createElementNS(SVG_NS, 'g') as SVGGElement;
2639
+ const inner = document.createElementNS(SVG_NS, 'g') as SVGGElement;
2640
+ g.append(inner);
2641
+ g.dataset['key'] = p.key;
2642
+ g.addEventListener('click', ev => {
2643
+ if (st.dragged) return;
2644
+ ev.stopPropagation();
2645
+ orbitPick(m, st, p.key, false);
2646
+ });
2647
+ // with many neighbours, the labels of a bubble's edges show while the pointer is on it
2648
+ g.addEventListener('pointerenter', () => orbitHover(st, p.key, true));
2649
+ g.addEventListener('pointerleave', () => orbitHover(st, p.key, false));
2650
+ g.addEventListener('focus', () => orbitHover(st, p.key, true));
2651
+ g.addEventListener('blur', () => orbitHover(st, p.key, false));
2652
+ st.bubbles.append(g);
2653
+ return { key: p.key, g, inner, role: p.role, cur: start, from: { ...start }, to: p, dying: false };
2654
+ }
2655
+
2656
+ /** What a bubble shows and how it reads: a link to a neighbour, back to the trail, or the next page. */
2657
+ function orbitDress(m: Mounted, st: OrbitState, v: OrbitVis, p: Placed, left: number, scale: number): void {
2658
+ const node = st.spec.nodes.get(p.key) ?? null;
2659
+ const title = p.role === 'more' ? (left > 0 ? own('orbit-more', String(left)) : own('orbit-first')) : node === null ? '' : translate(node.title, host.rt);
2660
+ const color = p.role === 'more' ? 'var(--tb-muted)' : node?.color ?? 'var(--tb-primary)';
2661
+ const [body, halo] = orbitGradients(st, color);
2662
+ const label = p.role === 'near' ? orbitEdgeText(st.spec, p.key) : '';
2663
+ const said = p.role === 'trail' ? own('orbit-back-to', title) : label === '' ? title : `${title}, ${label}`;
2664
+ v.g.setAttribute('class', `tb-orbit-node tb-orbit-${p.role}`);
2665
+ const tip = document.createElementNS(SVG_NS, 'title');
2666
+ tip.textContent = said;
2667
+ v.g.replaceChildren(tip, v.inner);
2668
+ v.inner.replaceChildren(...bubble({ role: p.role, r: p.r, scale, above: p.role !== 'trail' && p.y < -1, title, color, body, halo, node }).map(svgNode));
2669
+ if (p.role === 'focus') {
2670
+ // Chrome stops Tab on an SVG group with a click handler unless told not to
2671
+ v.g.setAttribute('tabindex', '-1');
2672
+ v.g.removeAttribute('role');
2673
+ v.g.removeAttribute('aria-label');
2674
+ v.g.setAttribute('aria-hidden', 'true');
2675
+ } else {
2676
+ v.g.setAttribute('tabindex', '0');
2677
+ v.g.setAttribute('role', p.role === 'more' ? 'button' : 'link');
2678
+ v.g.setAttribute('aria-label', said);
2679
+ v.g.removeAttribute('aria-hidden');
2680
+ }
2681
+ if (flag(m.face, 'disabled')) v.g.setAttribute('tabindex', '-1');
2682
+ }
2683
+
2684
+ function orbitEdgeText(spec: OrbitSpec, key: string): string {
2685
+ const c = edgeLabel(spec, key);
2686
+ return c === null ? '' : translate(c, host.rt);
2687
+ }
2688
+
2689
+ function orbitEdges(st: OrbitState, placed: Placed[], scale: number): void {
2690
+ const many = placed.filter(p => p.role === 'near').length > MANY;
2691
+ st.edges = shownEdges(st.spec, placed).map(e => {
2692
+ const path = document.createElementNS(SVG_NS, 'path') as SVGPathElement;
2693
+ path.setAttribute('class', `tb-orbit-edge tb-orbit-edge-${e.trail ? 'trail' : e.look}`);
2694
+ let text: SVGTextElement | null = null;
2695
+ if (e.label !== null) {
2696
+ text = document.createElementNS(SVG_NS, 'text') as SVGTextElement;
2697
+ text.setAttribute('class', many ? 'tb-orbit-label tb-orbit-later' : 'tb-orbit-label');
2698
+ // the size of the page's small text once the camera fits
2699
+ text.style.fontSize = `${11 / scale}px`;
2700
+ text.style.strokeWidth = `${3 / scale}px`;
2701
+ text.textContent = translate(e.label, host.rt);
2702
+ }
2703
+ return { a: e.from, b: e.to, path, text, curve: e.curve };
2704
+ });
2705
+ st.lines.replaceChildren(...st.edges.flatMap(e => (e.text === null ? [e.path] : [e.path, e.text])));
2706
+ st.lines.setAttribute('aria-hidden', 'true');
2707
+ }
2708
+
2709
+ function orbitHover(st: OrbitState, key: string, on: boolean): void {
2710
+ for (const e of st.edges) if (e.text !== null && (e.a === key || e.b === key)) e.text.classList.toggle('tb-orbit-shown', on);
2711
+ }
2712
+
2713
+ function orbitApplyCam(st: OrbitState): void {
2714
+ const w = st.svg.clientWidth || st.width;
2715
+ const h = st.svg.clientHeight || st.height;
2716
+ st.world.setAttribute('transform', `translate(${w / 2 + st.cam.x},${h / 2 + st.cam.y}) scale(${st.cam.s})`);
2717
+ }
2718
+
2719
+ /** Tweens every bubble and the camera from where they are to where they go; 0 ms puts them there at once. */
2720
+ function orbitAnimate(st: OrbitState, ms: number): void {
2721
+ cancelAnimationFrame(st.anim);
2722
+ const t0 = performance.now();
2723
+ const step = (now: number): void => {
2724
+ const k = ms === 0 ? 1 : ease(Math.min(1, (now - t0) / ms));
2725
+ for (const v of st.vis.values()) {
2726
+ if (v.from !== v.to || v.dying) {
2727
+ const f = v.from;
2728
+ const t = v.to;
2729
+ v.cur = { x: f.x + (t.x - f.x) * k, y: f.y + (t.y - f.y) * k, r: f.r + (t.r - f.r) * k, o: f.o + (t.o - f.o) * k };
2730
+ }
2731
+ v.g.setAttribute('transform', `translate(${v.cur.x},${v.cur.y})`);
2732
+ v.inner.setAttribute('transform', `scale(${Math.max(v.cur.r, 0.001)})`);
2733
+ v.g.style.opacity = String(v.cur.o);
2734
+ v.g.style.pointerEvents = v.cur.o < 0.05 ? 'none' : '';
2735
+ }
2736
+ if (st.camFrom !== null && st.camTo !== null) {
2737
+ const a = st.camFrom;
2738
+ const b = st.camTo;
2739
+ st.cam = { x: a.x + (b.x - a.x) * k, y: a.y + (b.y - a.y) * k, s: a.s + (b.s - a.s) * k };
2740
+ }
2741
+ orbitApplyCam(st);
2742
+ orbitDrawEdges(st);
2743
+ if (k < 1) st.anim = requestAnimationFrame(step);
2744
+ else {
2745
+ st.camFrom = st.camTo = null;
2746
+ for (const [k2, v] of st.vis) {
2747
+ if (v.dying) {
2748
+ v.g.remove();
2749
+ st.vis.delete(k2);
2750
+ }
2751
+ }
2752
+ }
2753
+ };
2754
+ if (ms === 0) step(t0);
2755
+ else st.anim = requestAnimationFrame(step);
2756
+ }
2757
+
2758
+ function orbitDrawEdges(st: OrbitState): void {
2759
+ for (const e of st.edges) {
2760
+ const a = st.vis.get(e.a);
2761
+ const b = st.vis.get(e.b);
2762
+ if (a === undefined || b === undefined) {
2763
+ e.path.setAttribute('d', '');
2764
+ continue;
2765
+ }
2766
+ const at = edgePath(a.cur, b.cur, e.curve);
2767
+ e.path.setAttribute('d', at.d);
2768
+ const o = String(Math.min(a.cur.o, b.cur.o));
2769
+ e.path.style.opacity = o;
2770
+ if (e.text !== null) {
2771
+ e.text.setAttribute('transform', `translate(${at.x},${at.y}) rotate(${at.angle}) translate(0,-5)`);
2772
+ e.text.style.opacity = o;
2773
+ }
2774
+ }
2775
+ }
2776
+
1965
2777
 
1966
2778
  function syncIcon(m: Mounted): void {
1967
2779
  const name = iconName(m.face) ?? '';
@@ -2200,8 +3012,10 @@ function buildRich(face: ObjectCell, m: Mounted): HTMLElement {
2200
3012
  error.setAttribute('aria-live', 'polite');
2201
3013
  box.setAttribute('aria-describedby', error.id);
2202
3014
  label.addEventListener('click', () => box.focus());
3015
+ keepCarets();
2203
3016
 
2204
3017
  const changed = (): void => {
3018
+ if (inserting) return;
2205
3019
  const md = printMd(readBlocks(box));
2206
3020
  if (md === m.shown) return;
2207
3021
  m.shown = md;
@@ -2214,7 +3028,7 @@ function buildRich(face: ObjectCell, m: Mounted): HTMLElement {
2214
3028
  });
2215
3029
  box.addEventListener('drop', ev => ev.preventDefault());
2216
3030
  wrap.addEventListener('focusout', ev => {
2217
- if (!wrap.contains(ev.relatedTarget as Node | null)) void fire('ui-blur', face);
3031
+ if (!wrap.contains(ev.relatedTarget as Node | null) && !inDevtools(ev.relatedTarget)) void fire('ui-blur', face);
2218
3032
  });
2219
3033
 
2220
3034
  let saved: Range | null = null;
@@ -2337,12 +3151,78 @@ function syncRich(m: Mounted, err: string | null): void {
2337
3151
  if (md !== m.shown && document.activeElement !== box) {
2338
3152
  m.shown = md;
2339
3153
  box.replaceChildren(...blockNodes(parseMd(md)));
3154
+ richCaret.delete(box);
2340
3155
  }
2341
3156
  }
2342
3157
 
3158
+ // --- inserting text at the cursor ---------------------------------------------------
3159
+ //
3160
+ // insert-text puts text where the user's cursor was, even after a click on a button or
3161
+ // a choice took the focus away: an input keeps its selection, a rich text box has
3162
+ // its last one kept here.
3163
+
3164
+ /** Inputs that have had the focus, so a cursor of their own. */
3165
+ const hadCaret = new WeakSet<Element>();
3166
+ /** The last selection inside each rich text box. */
3167
+ const richCaret = new WeakMap<HTMLElement, Range>();
3168
+ /** While insert-text writes in a rich text box, its own input event is not the user's. */
3169
+ let inserting = false;
3170
+
3171
+ let keepingCarets = false;
3172
+
3173
+ function keepCarets(): void {
3174
+ if (keepingCarets) return;
3175
+ keepingCarets = true;
3176
+ document.addEventListener('selectionchange', () => {
3177
+ const s = getSelection();
3178
+ if (s === null || s.rangeCount === 0) return;
3179
+ const n = s.anchorNode;
3180
+ const box = (n instanceof Element ? n : n?.parentElement)?.closest<HTMLElement>('.tb-rich-box');
3181
+ if (box != null) richCaret.set(box, s.getRangeAt(0).cloneRange());
3182
+ });
3183
+ }
3184
+
3185
+ native('insert-at-caret', '["The value of a field, area or rich text with text put where its cursor was; the cursor goes after it." face [object!] text [string!]]', (_t, f) => {
3186
+ const face = f.args[0] as ObjectCell;
3187
+ const add = text(f.args[1] as StringCell);
3188
+ const rich = word(face, 'style') === 'rich';
3189
+ const was = str(face, 'value') ?? '';
3190
+ const m = byCtx.get(face.ctx);
3191
+ if (m === undefined || !m.el.isConnected) return value(string(rich ? appendText(was, add) : was + add));
3192
+ if (rich) {
3193
+ const box = m.box!;
3194
+ const at = richCaret.get(box);
3195
+ box.focus();
3196
+ const s = getSelection()!;
3197
+ if (at !== undefined && box.contains(at.commonAncestorContainer)) {
3198
+ s.removeAllRanges();
3199
+ s.addRange(at);
3200
+ } else {
3201
+ s.selectAllChildren(box);
3202
+ s.collapseToEnd();
3203
+ }
3204
+ inserting = true;
3205
+ try {
3206
+ document.execCommand('insertText', false, add);
3207
+ } finally {
3208
+ inserting = false;
3209
+ }
3210
+ const md = printMd(readBlocks(box));
3211
+ m.shown = md;
3212
+ return value(string(md));
3213
+ }
3214
+ const input = m.input as HTMLInputElement | HTMLTextAreaElement;
3215
+ const end = input.value.length;
3216
+ const [from, to] = hadCaret.has(input) ? [input.selectionStart ?? end, input.selectionEnd ?? end] : [end, end];
3217
+ input.focus();
3218
+ input.setRangeText(add, from, to, 'end');
3219
+ return value(string(input.value));
3220
+ });
3221
+
2343
3222
  // --- tables and lists ---------------------------------------------------------------
2344
3223
 
2345
- interface Column { sym: Sym; word: Cell; label: string }
3224
+ /** A column; `image` when it shows each row's picture, `round` when cut to a circle. */
3225
+ interface Column { sym: Sym; word: Cell; label: string; image: boolean; round: boolean }
2346
3226
 
2347
3227
  function columns(face: ObjectCell): Column[] {
2348
3228
  const c = get(face, 'columns');
@@ -2351,11 +3231,32 @@ function columns(face: ObjectCell): Column[] {
2351
3231
  const d = c.s.data;
2352
3232
  for (let i = c.i; i + 1 < d.length; i += 2) {
2353
3233
  const w = d[i]!;
2354
- if (w.t === K.Word) out.push({ sym: (w as WordCell).sym, word: w, label: translate(d[i + 1]!, host.rt) });
3234
+ if (w.t !== K.Word) continue;
3235
+ // a column of images keeps its label in a block with what it is: ["Photo" image round]
3236
+ const spec = d[i + 1]!;
3237
+ const parts = spec.t === K.Block ? (spec as BlockCell).s.data.slice((spec as BlockCell).i) : [spec];
3238
+ const has = (name: string): boolean => parts.some(p => p.t === K.Word && canon((p as WordCell).sym) === canon(intern(name)));
3239
+ out.push({ sym: (w as WordCell).sym, word: w, label: translate(parts[0] ?? NONE, host.rt), image: has('image'), round: has('round') });
2355
3240
  }
2356
3241
  return out;
2357
3242
  }
2358
3243
 
3244
+ /** The picture of a row in a column of images, from an address or a file; without one, an empty place for it. */
3245
+ function thumb(box: Element, v: Cell, round: boolean): void {
3246
+ const src = v.t === K.String || v.t === K.Url || v.t === K.File ? form(v) : '';
3247
+ const old = box.querySelector<HTMLElement>(':scope > .tb-thumb');
3248
+ let pic = old;
3249
+ if (src === '' ? pic?.tagName !== 'SPAN' : pic?.tagName !== 'IMG') {
3250
+ // decoration: the row's text says who or what it is
3251
+ pic = el(src === '' ? 'span' : 'img', 'tb-thumb');
3252
+ if (src !== '') (pic as HTMLImageElement).alt = '';
3253
+ if (old !== null) old.replaceWith(pic);
3254
+ else box.prepend(pic);
3255
+ }
3256
+ if (src !== '' && pic!.getAttribute('src') !== src) (pic as HTMLImageElement).src = src;
3257
+ pic!.classList.toggle('tb-round', round);
3258
+ }
3259
+
2359
3260
  function sameRow(a: Cell, b: Cell): boolean {
2360
3261
  if (a.t === K.Map && b.t === K.Map) return a.s === b.s;
2361
3262
  if (a.t === K.Object && b.t === K.Object) return a.ctx === b.ctx;
@@ -2399,7 +3300,16 @@ function buildRows(face: ObjectCell, style: string, m: Mounted): HTMLElement {
2399
3300
  const totals = newTableRow(cols);
2400
3301
  totals.className = 'tb-totals';
2401
3302
  foot.append(totals);
2402
- table.append(head, box, foot);
3303
+ // the room of the rows not drawn, above and below the ones drawn
3304
+ const room = (): HTMLElement => {
3305
+ const b = el('tbody', 'tb-room');
3306
+ b.setAttribute('aria-hidden', 'true');
3307
+ const r = el('tr');
3308
+ r.append(el('td'));
3309
+ b.append(r);
3310
+ return b;
3311
+ };
3312
+ table.append(head, room(), box, room(), foot);
2403
3313
  wrap.append(table);
2404
3314
  } else {
2405
3315
  box = el('ul', 'tb-list');
@@ -2425,35 +3335,72 @@ function buildRows(face: ObjectCell, style: string, m: Mounted): HTMLElement {
2425
3335
  return wrap;
2426
3336
  }
2427
3337
 
2428
- /** Creates, updates, moves or removes only the rows whose key changed. */
3338
+ /** The rows of a table or list in the order shown, with their keys; then draws them. */
2429
3339
  function syncRows(m: Mounted): void {
2430
3340
  const f = m.face;
2431
- const box = m.box!;
2432
- const table = box.tagName === 'TBODY';
2433
- const cols = columns(f);
2434
3341
  const data = get(f, 'data');
2435
3342
  let rows = data.t === K.Block ? data.s.data.slice(data.i) : [];
2436
- if (table) {
2437
- syncHead(f, box.parentElement as HTMLTableElement, cols);
3343
+ if (m.box!.tagName === 'TBODY') {
3344
+ syncHead(f, m.box!.parentElement as HTMLTableElement, columns(f));
2438
3345
  const order = hostSorted(f);
2439
3346
  if (order !== null) rows = sortGroups(rows, order.sym, order.desc, activeLanguage(host.rt), cellText);
2440
3347
  }
2441
3348
  const keyWord = get(f, 'key');
2442
3349
  const key = keyWord.t === K.Word || keyWord.t === K.LitWord ? (keyWord as WordCell).sym : intern('id');
3350
+ const seen = new Set<string>();
3351
+ m.items = rows.map((row, i) => {
3352
+ const group = groupRow(row);
3353
+ let k: string;
3354
+ if (group !== null) k = `${group.kind}#${i}`;
3355
+ else {
3356
+ const id = rowField(row, key);
3357
+ k = id.t === K.None ? `#${i}` : `${id.t}:${form(id)}`;
3358
+ if (seen.has(k)) k = `${k}#${i}`;
3359
+ }
3360
+ seen.add(k);
3361
+ return { row, k };
3362
+ });
3363
+ drawRows(m);
3364
+ m.empty!.textContent = str(f, 'text') ?? own('empty');
3365
+ m.empty!.hidden = rows.length > 0;
3366
+ }
3367
+
3368
+ /** Tables and lists with too many rows to draw them all. */
3369
+ const longRows = new Set<Mounted>();
3370
+ /** While printing, every row is drawn. */
3371
+ let printing = false;
3372
+
3373
+ /** The rows to draw: all of them, or those near the screen. */
3374
+ function rowsToDraw(m: Mounted): { first: number; end: number } {
3375
+ const count = m.items.length;
3376
+ if (count <= DRAW_ALL_UP_TO || printing) return { first: 0, end: count };
3377
+ // where the first row would be: the rows drawn start below the room of those that are not
3378
+ const top = m.box!.getBoundingClientRect().top - m.first * m.rowHeight;
3379
+ const now = m.end > m.first ? { first: m.first, end: m.end } : undefined;
3380
+ return rowWindow(count, m.rowHeight || 48, -top, innerHeight, now);
3381
+ }
3382
+
3383
+ /** Creates, updates, moves or removes only the rows drawn whose key changed. */
3384
+ function drawRows(m: Mounted, again = true): void {
3385
+ const f = m.face;
3386
+ const box = m.box!;
3387
+ const table = box.tagName === 'TBODY';
3388
+ const cols = columns(f);
2443
3389
  const selected = get(f, 'selected');
2444
3390
  const selectable = handlerFor(f, 'on-select');
2445
3391
  box.parentElement!.classList.toggle('tb-selectable', selectable);
3392
+ const { first, end } = rowsToDraw(m);
3393
+ const count = m.items.length;
2446
3394
  const old = m.rows!;
2447
3395
  const next = new Map<string, HTMLElement>();
2448
3396
  let cursor = box.firstChild;
2449
- rows.forEach((row, i) => {
3397
+ for (let i = first; i < end; i++) {
3398
+ const { row, k } = m.items[i]!;
2450
3399
  const group = groupRow(row);
3400
+ let item = old.get(k);
2451
3401
  if (group !== null) {
2452
3402
  // a group's head or foot: kept by its place, never chosen, dragged or sorted
2453
- const k = `${group.kind}#${i}`;
2454
- let item = old.get(k);
2455
3403
  if (item === undefined) item = group.kind === 'head' ? newGroupHead(cols, table) : table ? newTableRow(cols) : newListItem();
2456
- next.set(k, item);
2457
3404
  item.className = `tb-group-${group.kind} tb-level-${group.level}`;
2458
3405
  if (group.kind === 'head') {
2459
3406
  const t = translate(group.value, host.rt);
@@ -2461,31 +3408,116 @@ function syncRows(m: Mounted): void {
2461
3408
  if (cell.textContent !== t) cell.textContent = t;
2462
3409
  if (table) (cell as HTMLTableCellElement).colSpan = Math.max(1, cols.length);
2463
3410
  } else fillRow(item, group.value, cols, table);
2464
- if (item !== cursor) box.insertBefore(item, cursor);
2465
- else cursor = cursor.nextSibling;
2466
- return;
3411
+ } else {
3412
+ if (item === undefined) item = table ? newTableRow(cols) : newListItem();
3413
+ rowOf.set(item, row);
3414
+ fillRow(item, row, cols, table);
3415
+ if (selectable) item.tabIndex = 0;
3416
+ else item.removeAttribute('tabindex');
3417
+ const on = selected.t !== K.None && sameRow(selected, row);
3418
+ item.classList.toggle('tb-selected', on);
3419
+ if (selectable) item.setAttribute('aria-selected', on ? 'true' : 'false');
3420
+ else item.removeAttribute('aria-selected');
2467
3421
  }
2468
- const id = rowField(row, key);
2469
- let k = id.t === K.None ? `#${i}` : `${id.t}:${form(id)}`;
2470
- if (next.has(k)) k = `${k}#${i}`;
2471
- let item = old.get(k);
2472
- if (item === undefined) item = table ? newTableRow(cols) : newListItem();
2473
3422
  next.set(k, item);
2474
- rowOf.set(item, row);
2475
- fillRow(item, row, cols, table);
2476
- if (selectable) item.tabIndex = 0;
2477
- else item.removeAttribute('tabindex');
2478
- const on = selected.t !== K.None && sameRow(selected, row);
2479
- item.classList.toggle('tb-selected', on);
2480
- if (selectable) item.setAttribute('aria-selected', on ? 'true' : 'false');
2481
- else item.removeAttribute('aria-selected');
3423
+ // with rows left undrawn, each says where it is among all of them
3424
+ if (count > end - first) {
3425
+ item.setAttribute(table ? 'aria-rowindex' : 'aria-posinset', String(table ? i + 2 : i + 1));
3426
+ if (!table) item.setAttribute('aria-setsize', String(count));
3427
+ } else {
3428
+ item.removeAttribute(table ? 'aria-rowindex' : 'aria-posinset');
3429
+ item.removeAttribute('aria-setsize');
3430
+ }
2482
3431
  if (item !== cursor) box.insertBefore(item, cursor);
2483
3432
  else cursor = cursor.nextSibling;
2484
- });
3433
+ }
2485
3434
  for (const [k, item] of old) if (next.get(k) !== item) item.remove();
2486
3435
  m.rows = next;
2487
- m.empty!.textContent = str(f, 'text') ?? own('empty');
2488
- m.empty!.hidden = rows.length > 0;
3436
+ m.first = first;
3437
+ m.end = end;
3438
+ if (table) {
3439
+ if (count > end - first) box.parentElement!.setAttribute('aria-rowcount', String(count + 1));
3440
+ else box.parentElement!.removeAttribute('aria-rowcount');
3441
+ }
3442
+ if (count <= DRAW_ALL_UP_TO) {
3443
+ longRows.delete(m);
3444
+ room(m, 0, 0);
3445
+ if (table) keepColumns(box.parentElement as HTMLTableElement, false);
3446
+ return;
3447
+ }
3448
+ longRows.add(m);
3449
+ if (table) keepColumns(box.parentElement as HTMLTableElement, true);
3450
+ // how tall a row is, from those drawn; the room of the others follows it
3451
+ const drawn = end - first;
3452
+ const h = box.getBoundingClientRect().height - (table ? 0 : parseFloat(box.style.paddingTop || '0') + parseFloat(box.style.paddingBottom || '0'));
3453
+ if (drawn > 0 && h > 0) m.rowHeight = h / drawn;
3454
+ room(m, first * m.rowHeight, (count - end) * m.rowHeight);
3455
+ // a first guess of the height may have drawn the wrong rows
3456
+ if (again) {
3457
+ const want = rowsToDraw(m);
3458
+ if (want.first !== first || want.end !== end) drawRows(m, false);
3459
+ }
3460
+ }
3461
+
3462
+ /**
3463
+ * A long table keeps the widths its columns first took, as shares of its width,
3464
+ * so they do not change with the rows drawn while it scrolls.
3465
+ */
3466
+ function keepColumns(table: HTMLTableElement, keep: boolean): void {
3467
+ const ths = Array.from(table.tHead!.rows[0]!.cells);
3468
+ if (!keep) {
3469
+ table.classList.remove('tb-fixed');
3470
+ for (const th of ths) th.style.width = '';
3471
+ return;
3472
+ }
3473
+ if (table.classList.contains('tb-fixed')) return;
3474
+ const widths = ths.map(th => th.getBoundingClientRect().width);
3475
+ const all = widths.reduce((a, b) => a + b, 0);
3476
+ // on a narrow screen the rows are cards and the headers take no room: later
3477
+ if (all === 0) return;
3478
+ ths.forEach((th, i) => { th.style.width = `${(widths[i]! / all) * 100}%`; });
3479
+ table.classList.add('tb-fixed');
3480
+ }
3481
+
3482
+ /** Sets the room of the rows not drawn above and below those drawn. */
3483
+ function room(m: Mounted, above: number, below: number): void {
3484
+ const box = m.box!;
3485
+ if (box.tagName === 'TBODY') {
3486
+ for (const [b, px] of [[box.previousElementSibling, above], [box.nextElementSibling, below]] as const) {
3487
+ const td = (b as HTMLElement).querySelector('td')!;
3488
+ td.style.height = `${px}px`;
3489
+ (b as HTMLElement).hidden = px === 0;
3490
+ }
3491
+ return;
3492
+ }
3493
+ box.style.paddingTop = above > 0 ? `${above}px` : '';
3494
+ box.style.paddingBottom = below > 0 ? `${below}px` : '';
3495
+ }
3496
+
3497
+ let rowsFrame = 0;
3498
+
3499
+ /** On a scroll or a resize, the long tables and lists draw the rows now near the screen. */
3500
+ function onRowsMoved(): void {
3501
+ if (rowsFrame !== 0 || longRows.size === 0) return;
3502
+ rowsFrame = requestAnimationFrame(() => {
3503
+ rowsFrame = 0;
3504
+ for (const m of longRows) {
3505
+ if (!m.box!.isConnected) { longRows.delete(m); continue; }
3506
+ const want = rowsToDraw(m);
3507
+ if (want.first !== m.first || want.end !== m.end) drawRows(m);
3508
+ }
3509
+ });
3510
+ }
3511
+
3512
+ /** Printing draws every row, and the screen goes back to drawing some after. */
3513
+ function onPrint(on: boolean): void {
3514
+ printing = on;
3515
+ for (const m of longRows) {
3516
+ if (!m.box!.isConnected) continue;
3517
+ // all the rows cover the screen, but are not to be kept
3518
+ if (!on) m.end = m.first;
3519
+ drawRows(m);
3520
+ }
2489
3521
  }
2490
3522
 
2491
3523
  /** Headers in the active language; in a sortable table each is a button, with an arrow on the sorted one. */
@@ -2578,7 +3610,9 @@ function newTableRow(cols: Column[]): HTMLElement {
2578
3610
 
2579
3611
  function newListItem(): HTMLElement {
2580
3612
  const li = el('li');
2581
- li.append(el('span', 'tb-list-primary'), el('span', 'tb-list-secondary'));
3613
+ const texts = el('span', 'tb-list-texts');
3614
+ texts.append(el('span', 'tb-list-primary'), el('span', 'tb-list-secondary'));
3615
+ li.append(texts);
2582
3616
  return li;
2583
3617
  }
2584
3618
 
@@ -2590,15 +3624,23 @@ function fillRow(item: HTMLElement, row: Cell, cols: Column[], table: boolean):
2590
3624
  cols.forEach((c, i) => {
2591
3625
  const v = rowField(row, c.sym);
2592
3626
  const td = item.children[i]!;
3627
+ if (c.image) {
3628
+ td.classList.add('tb-thumb-cell');
3629
+ return thumb(td, v, c.round);
3630
+ }
2593
3631
  set(td, cellText(v));
2594
3632
  td.classList.toggle('tb-num', NUMERIC.has(v.t));
2595
3633
  });
2596
3634
  return;
2597
3635
  }
2598
- // a list shows its first column, then the others on a quieter line
2599
- const [first, ...rest] = cols.map(c => cellText(rowField(row, c.sym)));
2600
- set(item.children[0]!, first ?? '');
2601
- set(item.children[1]!, rest.filter(Boolean).join(' · '));
3636
+ // a list shows its picture first, then its first column, and the others on a quieter line
3637
+ const pic = cols.find(c => c.image);
3638
+ if (pic !== undefined) thumb(item, rowField(row, pic.sym), pic.round);
3639
+ else item.querySelector(':scope > .tb-thumb')?.remove();
3640
+ const [first, ...rest] = cols.filter(c => !c.image).map(c => cellText(rowField(row, c.sym)));
3641
+ const texts = item.querySelector(':scope > .tb-list-texts')!;
3642
+ set(texts.children[0]!, first ?? '');
3643
+ set(texts.children[1]!, rest.filter(Boolean).join(' · '));
2602
3644
  }
2603
3645
 
2604
3646
  function handlerFor(face: ObjectCell, name: string): boolean {
@@ -3099,6 +4141,7 @@ native('show-toast', '["Shows a short message at the edge of the screen." messag
3099
4141
  const t = el('div', kind !== null ? `tb-toast tb-${kind}` : 'tb-toast');
3100
4142
  if (kind === 'danger') t.setAttribute('role', 'alert');
3101
4143
  const message = text(f.args[0] as StringCell);
4144
+ devLog.note('toast', kind !== null ? `${kind}: ${message}` : message);
3102
4145
  const box = toasts;
3103
4146
  const dismiss = (): void => {
3104
4147
  t.remove();
@@ -3206,6 +4249,8 @@ function sync(m: Mounted): void {
3206
4249
 
3207
4250
  if (style === 'radio') return syncRadio(m, err);
3208
4251
  if (style === 'upload') return syncUpload(m, err);
4252
+ if (style === 'photo') return syncPhoto(m, err);
4253
+ if (style === 'widget') return syncWidget(m, err);
3209
4254
  if (style === 'lookup') return syncLookup(m, err);
3210
4255
  if (style === 'rich') return syncRich(m, err);
3211
4256
  if (m.input !== null) {
@@ -3280,12 +4325,19 @@ function sync(m: Mounted): void {
3280
4325
  case 'progress': syncProgress(m); return;
3281
4326
  case 'canvas': syncCanvas(m); return;
3282
4327
  case 'chart': syncChart(m); return;
4328
+ case 'orbit': syncOrbit(m); return;
3283
4329
  case 'icon': syncIcon(m); return;
4330
+ case 'video': case 'audio': syncMedia(m); return;
3284
4331
  case 'image': {
3285
4332
  const img = m.el as HTMLImageElement;
3286
4333
  const src = str(f, 'value') ?? '';
3287
4334
  if (img.getAttribute('src') !== src) img.src = src;
3288
4335
  img.alt = t ?? '';
4336
+ img.classList.toggle('tb-round', flag(f, 'round'));
4337
+ // a size, as in Red: the image fills it, cut to fit
4338
+ const ext = get(f, 'extent');
4339
+ img.style.width = ext.t === K.Pair ? `${ext.x}px` : '';
4340
+ img.style.height = ext.t === K.Pair ? `${ext.y}px` : '';
3289
4341
  return;
3290
4342
  }
3291
4343
  case 'table': case 'list': syncRows(m); return;
@@ -3297,7 +4349,7 @@ function sync(m: Mounted): void {
3297
4349
  else m.el.removeAttribute('aria-label');
3298
4350
  break;
3299
4351
  }
3300
- case 'desktop': {
4352
+ case 'desktop': case 'backdrop': {
3301
4353
  const src = str(f, 'value');
3302
4354
  m.el.style.backgroundImage = src !== null ? `url(${JSON.stringify(src)})` : '';
3303
4355
  break;
@@ -3391,6 +4443,35 @@ function setExtra(e: HTMLElement, cls: string[]): void {
3391
4443
  e.dataset['tb'] = cls.join(' ');
3392
4444
  }
3393
4445
 
4446
+ /**
4447
+ * Runs the reactions whose facets changed in this round, at once, so the repaint
4448
+ * that follows shows them: ui-react, given the faces on the page that have any.
4449
+ */
4450
+ function react(): void {
4451
+ for (const m of reactors) if (!m.el.isConnected && comingScreen?.contains(m.el) !== true) reactors.delete(m);
4452
+ if (reacting !== null || reactors.size === 0 || (dirty.length === 0 && !newReactor)) return;
4453
+ newReactor = false;
4454
+ const faces = blockOf(K.Block, [...reactors].map(m => m.face));
4455
+ const ht = runNow(host.sch, { data: [{ t: K.Word, sym: intern('ui-react'), bind: host.rt.user }, faces] }, 0);
4456
+ const warn = (t: HostTask) => {
4457
+ if (t.state !== 'done' || t.result.t !== K.Block) return;
4458
+ for (const c of (t.result as BlockCell).s.data) {
4459
+ console.warn(`Trebol: ${text(c as StringCell)}`);
4460
+ devLog.note('warning', text(c as StringCell));
4461
+ }
4462
+ };
4463
+ if (ht.state === 'done') warn(ht);
4464
+ else if (ht.state !== 'failed') {
4465
+ reacting = ht;
4466
+ ht.watchers.push(t => {
4467
+ reacting = null;
4468
+ // what changed while it waited is checked at the end of this round
4469
+ newReactor = true;
4470
+ warn(t);
4471
+ });
4472
+ }
4473
+ }
4474
+
3394
4475
  function syncDirty(): void {
3395
4476
  for (const ctx of dirty) {
3396
4477
  ctx.dirty = false;
@@ -3446,9 +4527,14 @@ function startHistory(): void {
3446
4527
  history.replaceState({ ...here }, '');
3447
4528
  }
3448
4529
 
4530
+ /** Where the page stood before the link last changed, so route-undo can return; set while it returns. */
4531
+ let before = { depth: 0, top: 0 };
4532
+ let undoing: { depth: number; top: number } | null = null;
4533
+
3449
4534
  /** 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. */
3450
4535
  function landHistory(): void {
3451
4536
  const state = history.state as { depth?: number } | null;
4537
+ before = { ...here };
3452
4538
  if (typeof state?.depth === 'number') here = { depth: state.depth, top: here.top };
3453
4539
  else here = { depth: here.depth + 1, top: here.depth + 1 };
3454
4540
  history.replaceState({ ...here }, '');
@@ -3467,6 +4553,24 @@ native('set-route', '["Puts a screen and arguments in the address bar." route [b
3467
4553
  return value(f.args[0]!);
3468
4554
  });
3469
4555
 
4556
+ // A screen that does not let the page leave puts its link back: back for a new entry,
4557
+ // the other way for back or forward. The link that comes back is not a change of screen.
4558
+ native('route-undo', '["Puts back the link the page had before the last change." ]', () => {
4559
+ const by = before.depth - here.depth;
4560
+ if (by === 0) return value(NONE);
4561
+ undoing = before;
4562
+ history.go(by);
4563
+ return value(NONE);
4564
+ });
4565
+
4566
+ // While the screen on show has changes not saved, the browser asks before closing or
4567
+ // reloading the page, with its own words: no browser lets a page give its text.
4568
+ let unsaved = false;
4569
+ native('set-unsaved', '["Whether the browser asks before closing the page." on [logic!]]', (_t, f) => {
4570
+ unsaved = f.args[0]!.t === K.Logic && f.args[0]!.v;
4571
+ return value(f.args[0]!);
4572
+ });
4573
+
3470
4574
  native('route-steps', '["How many steps back and forward the history has." ]', () => value(blockOf(K.Block, [int(here.depth), int(here.top - here.depth)])));
3471
4575
 
3472
4576
  native('route-back', '["Goes one step back in the history." ]', () => {
@@ -3580,11 +4684,34 @@ native('apply-theme', '["Changes the look of the whole screen." spec [object!]]'
3580
4684
  // --- boot --------------------------------------------------------------------------
3581
4685
 
3582
4686
  async function boot(): Promise<void> {
4687
+ // a page of trebol build has the app's files inside, by their path from the page, and its own fonts
4688
+ const files = document.getElementById('trebol-files');
4689
+ if (files !== null) {
4690
+ for (const [path, src] of Object.entries(JSON.parse(files.textContent ?? '{}') as Record<string, string>)) {
4691
+ addBuiltIn(new URL(path, location.href).href, src);
4692
+ }
4693
+ }
4694
+ if (document.querySelector('style[data-tb-fonts]') === null) {
4695
+ const fonts = el('style');
4696
+ fonts.dataset['tbFonts'] = '';
4697
+ fonts.textContent = interCss(file => new URL(`fonts/${file}`, import.meta.url).href);
4698
+ document.head.append(fonts);
4699
+ }
3583
4700
  setTheme(DEFAULT_THEME);
3584
- host = startHost();
3585
- host.sch.afterPump = syncDirty;
4701
+ host = startHost({ onError: e => showError(report(e)) });
4702
+ host.sch.afterPump = () => {
4703
+ react();
4704
+ syncDirty();
4705
+ devLog.repainted();
4706
+ };
3586
4707
  document.addEventListener('keydown', onKeyDown, true);
3587
4708
  document.addEventListener('keydown', onReorderKey);
4709
+ // a scroll anywhere: the page, a scroll face, a dialog
4710
+ document.addEventListener('scroll', onRowsMoved, { capture: true, passive: true });
4711
+ addEventListener('resize', onRowsMoved);
4712
+ addEventListener('beforeunload', ev => { if (unsaved) ev.preventDefault(); });
4713
+ addEventListener('beforeprint', () => onPrint(true));
4714
+ addEventListener('afterprint', () => onPrint(false));
3588
4715
  document.addEventListener('pointerdown', onPointerDown);
3589
4716
  document.addEventListener('pointermove', onPointerMove, { passive: false });
3590
4717
  document.addEventListener('pointerup', () => endDrag(true));
@@ -3593,8 +4720,33 @@ async function boot(): Promise<void> {
3593
4720
  // a touch drag must not scroll the page
3594
4721
  document.addEventListener('touchmove', ev => { if (dragging?.on) ev.preventDefault(); }, { passive: false });
3595
4722
  document.addEventListener('keydown', onViewKey);
4723
+ const devMark = document.querySelector('meta[name="trebol-dev"]');
4724
+ if (devMark !== null) {
4725
+ startDevtools({
4726
+ host,
4727
+ root: devMark.getAttribute('content'),
4728
+ faceOf: e => {
4729
+ const m = byNode.get(e);
4730
+ return m !== undefined && m.el === e ? m.face : null;
4731
+ },
4732
+ faceAt: e => {
4733
+ const m = mountedAbove(e);
4734
+ return m === undefined ? null : { face: m.face, el: m.el };
4735
+ },
4736
+ nodeOf: face => {
4737
+ const e = byCtx.get(face.ctx)?.el;
4738
+ return e?.isConnected === true ? e : null;
4739
+ },
4740
+ });
4741
+ }
3596
4742
  startHistory();
3597
4743
  window.addEventListener('hashchange', () => {
4744
+ if (undoing !== null) {
4745
+ here = undoing;
4746
+ undoing = null;
4747
+ history.replaceState({ ...here }, '');
4748
+ return;
4749
+ }
3598
4750
  landHistory();
3599
4751
  if (screensFace !== null) void fire('ui-route', screensFace, routeBlock());
3600
4752
  });
@@ -3602,11 +4754,11 @@ async function boot(): Promise<void> {
3602
4754
  for (const s of Array.from(document.querySelectorAll<HTMLScriptElement>('script[type="text/trebol"]'))) {
3603
4755
  const src = s.getAttribute('src');
3604
4756
  const url = src !== null ? new URL(src, location.href).href : location.href;
3605
- const code = src !== null ? await (await fetch(url)).text() : s.textContent ?? '';
4757
+ const code = src !== null ? builtInText(url) ?? await (await fetch(url)).text() : s.textContent ?? '';
3606
4758
  try {
3607
4759
  await runSource(host, code, url);
3608
4760
  } catch (e) {
3609
- console.error(e instanceof Error ? e.message : report(e as ObjectCell));
4761
+ showError(e instanceof Error ? e.message : report(e as ObjectCell));
3610
4762
  }
3611
4763
  }
3612
4764
  }