trebol 0.1.1 → 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 (84) hide show
  1. package/README.md +10 -1
  2. package/dist/cli.js +13747 -11409
  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/boot.js +2 -1
  12. package/dist/lib/core/func.d.ts +4 -0
  13. package/dist/lib/core/natives/control.js +1 -1
  14. package/dist/lib/core/natives/series.js +11 -1
  15. package/dist/lib/core/natives/text.js +3 -0
  16. package/dist/lib/host/browser.js +951 -58
  17. package/dist/lib/host/devlog.d.ts +11 -0
  18. package/dist/lib/host/devlog.js +13 -0
  19. package/dist/lib/host/devtools.d.ts +23 -0
  20. package/dist/lib/host/devtools.js +626 -0
  21. package/dist/lib/host/fonts/OFL.txt +93 -0
  22. package/dist/lib/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  23. package/dist/lib/host/fonts/inter-cyrillic.woff2 +0 -0
  24. package/dist/lib/host/fonts/inter-greek-ext.woff2 +0 -0
  25. package/dist/lib/host/fonts/inter-greek.woff2 +0 -0
  26. package/dist/lib/host/fonts/inter-latin-ext.woff2 +0 -0
  27. package/dist/lib/host/fonts/inter-latin.woff2 +0 -0
  28. package/dist/lib/host/fonts/inter-vietnamese.woff2 +0 -0
  29. package/dist/lib/host/fonts.d.ts +11 -0
  30. package/dist/lib/host/fonts.js +29 -0
  31. package/dist/lib/host/index.d.ts +2 -0
  32. package/dist/lib/host/index.js +3 -1
  33. package/dist/lib/host/js.d.ts +5 -0
  34. package/dist/lib/host/js.js +130 -0
  35. package/dist/lib/host/markdown.d.ts +2 -0
  36. package/dist/lib/host/markdown.js +10 -0
  37. package/dist/lib/host/modules.d.ts +4 -0
  38. package/dist/lib/host/modules.js +39 -1
  39. package/dist/lib/host/net.js +9 -1
  40. package/dist/lib/host/orbit.d.ts +121 -0
  41. package/dist/lib/host/orbit.js +374 -0
  42. package/dist/lib/host/rows.d.ts +14 -0
  43. package/dist/lib/host/rows.js +29 -0
  44. package/dist/lib/host/scheduler.d.ts +6 -0
  45. package/dist/lib/host/scheduler.js +60 -36
  46. package/dist/lib/host/theme.js +207 -2
  47. package/dist/lib/ui/i18n.trb +6 -0
  48. package/dist/lib/ui/test.trb +565 -0
  49. package/dist/lib/ui/ui.trb +523 -82
  50. package/dist/trebol.js +1346 -124
  51. package/editors/vscode/README.md +15 -0
  52. package/editors/vscode/language-configuration.json +28 -0
  53. package/editors/vscode/package.json +42 -0
  54. package/editors/vscode/syntaxes/trebol.tmLanguage.json +237 -0
  55. package/package.json +7 -3
  56. package/src/core/boot.ts +1 -1
  57. package/src/core/func.ts +4 -0
  58. package/src/core/natives/control.ts +1 -1
  59. package/src/core/natives/series.ts +9 -1
  60. package/src/core/natives/text.ts +2 -0
  61. package/src/host/browser.ts +962 -51
  62. package/src/host/devlog.ts +16 -0
  63. package/src/host/devtools.ts +641 -0
  64. package/src/host/fonts/OFL.txt +93 -0
  65. package/src/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  66. package/src/host/fonts/inter-cyrillic.woff2 +0 -0
  67. package/src/host/fonts/inter-greek-ext.woff2 +0 -0
  68. package/src/host/fonts/inter-greek.woff2 +0 -0
  69. package/src/host/fonts/inter-latin-ext.woff2 +0 -0
  70. package/src/host/fonts/inter-latin.woff2 +0 -0
  71. package/src/host/fonts/inter-vietnamese.woff2 +0 -0
  72. package/src/host/fonts.ts +39 -0
  73. package/src/host/index.ts +3 -1
  74. package/src/host/js.ts +127 -0
  75. package/src/host/markdown.ts +9 -0
  76. package/src/host/modules.ts +33 -1
  77. package/src/host/net.ts +9 -1
  78. package/src/host/orbit.ts +432 -0
  79. package/src/host/rows.ts +30 -0
  80. package/src/host/scheduler.ts +62 -36
  81. package/src/host/theme.ts +207 -2
  82. package/src/ui/i18n.trb +6 -0
  83. package/src/ui/test.trb +565 -0
  84. package/src/ui/ui.trb +523 -82
@@ -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, handleOf } 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)) {
@@ -246,6 +324,8 @@ function build(face: ObjectCell): HTMLElement {
246
324
  node = buildUpload(face, m);
247
325
  } else if (style === 'photo') {
248
326
  node = buildPhoto(face, m);
327
+ } else if (style === 'widget') {
328
+ node = buildWidget(face, m);
249
329
  } else if (style === 'lookup') {
250
330
  node = buildLookup(face, m);
251
331
  } else if (style === 'rich') {
@@ -337,6 +417,7 @@ function build(face: ObjectCell): HTMLElement {
337
417
  }
338
418
  case 'canvas': node = buildCanvas(m); break;
339
419
  case 'chart': node = buildChart(m); break;
420
+ case 'orbit': node = buildOrbit(m); break;
340
421
  case 'icon': node = el('span', 'tb-icon-face'); break;
341
422
  case 'table': case 'list': node = buildRows(face, style, m); break;
342
423
  case 'tree': node = buildTree(face, m); break;
@@ -373,6 +454,10 @@ function build(face: ObjectCell): HTMLElement {
373
454
  if (m.input !== null) byNode.set(m.input, m);
374
455
  byCtx.set(face.ctx, m);
375
456
  face.ctx.watch = dirty;
457
+ if (get(face, 'reactions').t === K.Block) {
458
+ reactors.add(m);
459
+ newReactor = true;
460
+ }
376
461
  listen(m, style);
377
462
  sync(m);
378
463
  return node;
@@ -521,6 +606,11 @@ function sourceAt(start: Element): Source | null {
521
606
  const reorder = flag(m.face, 'reorder') && hostSorted(m.face) === null;
522
607
  if (!flag(m.face, 'drag') && !reorder) return null;
523
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
+ }
524
614
  const index = Array.prototype.indexOf.call(group.children, e);
525
615
  return { face: m.face, el: e as HTMLElement, payload: row, within: reorder ? m : null, index, group };
526
616
  }
@@ -561,7 +651,12 @@ function insertionAt(m: Mounted, x: number, y: number): number {
561
651
  const r = e.getBoundingClientRect();
562
652
  if ((across ? x : y) > (across ? r.left + r.width / 2 : r.top + r.height / 2)) i++;
563
653
  }
564
- 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;
565
660
  }
566
661
 
567
662
  let line: HTMLElement | null = null;
@@ -586,8 +681,9 @@ function indicate(t: Target | null): void {
586
681
  const across = horizontal(t.m);
587
682
  const all = t.group !== undefined ? Array.from(t.group.children) : slots(t.m);
588
683
  const box = (t.group ?? t.m.box ?? t.m.el).getBoundingClientRect();
589
- const before = all[t.index]?.getBoundingClientRect();
590
- 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();
591
687
  line.classList.toggle('tb-across', across);
592
688
  if (across) {
593
689
  const at = before && after ? (after.right + before.left) / 2 : before ? before.left - 3 : after ? after.right + 3 : box.left + 8;
@@ -618,7 +714,7 @@ async function reorder(m: Mounted, from: number, to: number, group?: HTMLElement
618
714
  await fire('ui-reorder', m.face, int(from + 1), int(to + 1), parent);
619
715
  syncDirty();
620
716
  if (!had) return;
621
- 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];
622
718
  const focusable = e?.matches('[tabindex], button, a, input, textarea, select') ? e : e?.querySelector<HTMLElement>('[tabindex], button, a, input, textarea, select');
623
719
  (focusable ?? null)?.focus();
624
720
  }
@@ -633,7 +729,7 @@ function moveTargets(face: ObjectCell, payload: Cell): MenuEntry[] {
633
729
  if (str(z.face, 'text') === null && z.el.querySelector('.tb-drop-zone') !== null) continue;
634
730
  out.push({
635
731
  text: str(z.face, 'text') ?? word(z.face, 'style') ?? '',
636
- 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),
637
733
  });
638
734
  }
639
735
  return out;
@@ -708,13 +804,14 @@ function onPointerMove(ev: PointerEvent): void {
708
804
 
709
805
  /** Alt+Up and Alt+Down move the focused row or child inside a reorderable container. */
710
806
  function onReorderKey(ev: KeyboardEvent): void {
807
+ if (inDevtools(ev.target)) return;
711
808
  if (!ev.altKey || ev.ctrlKey || ev.metaKey || (ev.key !== 'ArrowUp' && ev.key !== 'ArrowDown')) return;
712
809
  const at = document.activeElement;
713
810
  if (at === null) return;
714
811
  const src = sourceAt(at);
715
812
  if (src === null || src.within === null) return;
716
813
  const to = src.index + (ev.key === 'ArrowUp' ? -1 : 1);
717
- 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;
718
815
  ev.preventDefault();
719
816
  seenKeys.add(ev);
720
817
  const group = src.group ?? undefined;
@@ -1130,6 +1227,7 @@ function shortcutLabel(spec: string): string {
1130
1227
 
1131
1228
  /** Shortcuts beat the browser's own keys; the view's on-key gets keys nobody handled. */
1132
1229
  function onKeyDown(ev: KeyboardEvent): void {
1230
+ if (inDevtools(ev.target)) return;
1133
1231
  const modal = Array.from(document.querySelectorAll('dialog[open]')).pop();
1134
1232
  for (const m of shortcuts) {
1135
1233
  if (!m.el.isConnected) { shortcuts.delete(m); continue; }
@@ -1145,6 +1243,7 @@ function onKeyDown(ev: KeyboardEvent): void {
1145
1243
  }
1146
1244
 
1147
1245
  function onViewKey(ev: KeyboardEvent): void {
1246
+ if (inDevtools(ev.target)) return;
1148
1247
  if (viewKeys === null || seenKeys.has(ev) || keyCell(ev) === null) return;
1149
1248
  fireEvent(viewKeys, 'on-key', keyWords(ev));
1150
1249
  }
@@ -1219,6 +1318,7 @@ function buildInput(face: ObjectCell, style: string, m: Mounted): HTMLElement {
1219
1318
  if (style === 'password') i.autocomplete = 'new-password';
1220
1319
  input = i;
1221
1320
  }
1321
+ input.addEventListener('focus', () => hadCaret.add(input));
1222
1322
  input.id = id;
1223
1323
  const error = el('div', 'tb-error');
1224
1324
  error.id = `${id}-error`;
@@ -1242,7 +1342,8 @@ function buildInput(face: ObjectCell, style: string, m: Mounted): HTMLElement {
1242
1342
  if (style === 'money') input.addEventListener('focus', () => {
1243
1343
  if (!flag(face, 'readonly')) input.value = editLocal(get(face, 'value'), activeLanguage(host.rt));
1244
1344
  });
1245
- 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); });
1246
1347
  const iconWord = style === 'area' || style === 'choice' ? null : iconName(face);
1247
1348
  const svg = iconWord !== null ? icon(iconWord) : null;
1248
1349
  if (style === 'date') {
@@ -1605,6 +1706,104 @@ function syncPhoto(m: Mounted, err: string | null): void {
1605
1706
  syncSent(m);
1606
1707
  }
1607
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 ?? '';
1805
+ }
1806
+
1608
1807
  function accepts(file: File, list: string[]): boolean {
1609
1808
  if (list.length === 0) return true;
1610
1809
  const name = file.name.toLowerCase();
@@ -2164,6 +2363,417 @@ function drawChart(m: Mounted): void {
2164
2363
  p.table.tBodies[0]!.append(...body);
2165
2364
  }
2166
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
+
2167
2777
 
2168
2778
  function syncIcon(m: Mounted): void {
2169
2779
  const name = iconName(m.face) ?? '';
@@ -2402,8 +3012,10 @@ function buildRich(face: ObjectCell, m: Mounted): HTMLElement {
2402
3012
  error.setAttribute('aria-live', 'polite');
2403
3013
  box.setAttribute('aria-describedby', error.id);
2404
3014
  label.addEventListener('click', () => box.focus());
3015
+ keepCarets();
2405
3016
 
2406
3017
  const changed = (): void => {
3018
+ if (inserting) return;
2407
3019
  const md = printMd(readBlocks(box));
2408
3020
  if (md === m.shown) return;
2409
3021
  m.shown = md;
@@ -2416,7 +3028,7 @@ function buildRich(face: ObjectCell, m: Mounted): HTMLElement {
2416
3028
  });
2417
3029
  box.addEventListener('drop', ev => ev.preventDefault());
2418
3030
  wrap.addEventListener('focusout', ev => {
2419
- 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);
2420
3032
  });
2421
3033
 
2422
3034
  let saved: Range | null = null;
@@ -2539,9 +3151,74 @@ function syncRich(m: Mounted, err: string | null): void {
2539
3151
  if (md !== m.shown && document.activeElement !== box) {
2540
3152
  m.shown = md;
2541
3153
  box.replaceChildren(...blockNodes(parseMd(md)));
3154
+ richCaret.delete(box);
2542
3155
  }
2543
3156
  }
2544
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
+
2545
3222
  // --- tables and lists ---------------------------------------------------------------
2546
3223
 
2547
3224
  /** A column; `image` when it shows each row's picture, `round` when cut to a circle. */
@@ -2623,7 +3300,16 @@ function buildRows(face: ObjectCell, style: string, m: Mounted): HTMLElement {
2623
3300
  const totals = newTableRow(cols);
2624
3301
  totals.className = 'tb-totals';
2625
3302
  foot.append(totals);
2626
- 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);
2627
3313
  wrap.append(table);
2628
3314
  } else {
2629
3315
  box = el('ul', 'tb-list');
@@ -2649,35 +3335,72 @@ function buildRows(face: ObjectCell, style: string, m: Mounted): HTMLElement {
2649
3335
  return wrap;
2650
3336
  }
2651
3337
 
2652
- /** 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. */
2653
3339
  function syncRows(m: Mounted): void {
2654
3340
  const f = m.face;
2655
- const box = m.box!;
2656
- const table = box.tagName === 'TBODY';
2657
- const cols = columns(f);
2658
3341
  const data = get(f, 'data');
2659
3342
  let rows = data.t === K.Block ? data.s.data.slice(data.i) : [];
2660
- if (table) {
2661
- syncHead(f, box.parentElement as HTMLTableElement, cols);
3343
+ if (m.box!.tagName === 'TBODY') {
3344
+ syncHead(f, m.box!.parentElement as HTMLTableElement, columns(f));
2662
3345
  const order = hostSorted(f);
2663
3346
  if (order !== null) rows = sortGroups(rows, order.sym, order.desc, activeLanguage(host.rt), cellText);
2664
3347
  }
2665
3348
  const keyWord = get(f, 'key');
2666
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);
2667
3389
  const selected = get(f, 'selected');
2668
3390
  const selectable = handlerFor(f, 'on-select');
2669
3391
  box.parentElement!.classList.toggle('tb-selectable', selectable);
3392
+ const { first, end } = rowsToDraw(m);
3393
+ const count = m.items.length;
2670
3394
  const old = m.rows!;
2671
3395
  const next = new Map<string, HTMLElement>();
2672
3396
  let cursor = box.firstChild;
2673
- rows.forEach((row, i) => {
3397
+ for (let i = first; i < end; i++) {
3398
+ const { row, k } = m.items[i]!;
2674
3399
  const group = groupRow(row);
3400
+ let item = old.get(k);
2675
3401
  if (group !== null) {
2676
3402
  // a group's head or foot: kept by its place, never chosen, dragged or sorted
2677
- const k = `${group.kind}#${i}`;
2678
- let item = old.get(k);
2679
3403
  if (item === undefined) item = group.kind === 'head' ? newGroupHead(cols, table) : table ? newTableRow(cols) : newListItem();
2680
- next.set(k, item);
2681
3404
  item.className = `tb-group-${group.kind} tb-level-${group.level}`;
2682
3405
  if (group.kind === 'head') {
2683
3406
  const t = translate(group.value, host.rt);
@@ -2685,31 +3408,116 @@ function syncRows(m: Mounted): void {
2685
3408
  if (cell.textContent !== t) cell.textContent = t;
2686
3409
  if (table) (cell as HTMLTableCellElement).colSpan = Math.max(1, cols.length);
2687
3410
  } else fillRow(item, group.value, cols, table);
2688
- if (item !== cursor) box.insertBefore(item, cursor);
2689
- else cursor = cursor.nextSibling;
2690
- 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');
2691
3421
  }
2692
- const id = rowField(row, key);
2693
- let k = id.t === K.None ? `#${i}` : `${id.t}:${form(id)}`;
2694
- if (next.has(k)) k = `${k}#${i}`;
2695
- let item = old.get(k);
2696
- if (item === undefined) item = table ? newTableRow(cols) : newListItem();
2697
3422
  next.set(k, item);
2698
- rowOf.set(item, row);
2699
- fillRow(item, row, cols, table);
2700
- if (selectable) item.tabIndex = 0;
2701
- else item.removeAttribute('tabindex');
2702
- const on = selected.t !== K.None && sameRow(selected, row);
2703
- item.classList.toggle('tb-selected', on);
2704
- if (selectable) item.setAttribute('aria-selected', on ? 'true' : 'false');
2705
- 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
+ }
2706
3431
  if (item !== cursor) box.insertBefore(item, cursor);
2707
3432
  else cursor = cursor.nextSibling;
2708
- });
3433
+ }
2709
3434
  for (const [k, item] of old) if (next.get(k) !== item) item.remove();
2710
3435
  m.rows = next;
2711
- m.empty!.textContent = str(f, 'text') ?? own('empty');
2712
- 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
+ }
2713
3521
  }
2714
3522
 
2715
3523
  /** Headers in the active language; in a sortable table each is a button, with an arrow on the sorted one. */
@@ -3333,6 +4141,7 @@ native('show-toast', '["Shows a short message at the edge of the screen." messag
3333
4141
  const t = el('div', kind !== null ? `tb-toast tb-${kind}` : 'tb-toast');
3334
4142
  if (kind === 'danger') t.setAttribute('role', 'alert');
3335
4143
  const message = text(f.args[0] as StringCell);
4144
+ devLog.note('toast', kind !== null ? `${kind}: ${message}` : message);
3336
4145
  const box = toasts;
3337
4146
  const dismiss = (): void => {
3338
4147
  t.remove();
@@ -3441,6 +4250,7 @@ function sync(m: Mounted): void {
3441
4250
  if (style === 'radio') return syncRadio(m, err);
3442
4251
  if (style === 'upload') return syncUpload(m, err);
3443
4252
  if (style === 'photo') return syncPhoto(m, err);
4253
+ if (style === 'widget') return syncWidget(m, err);
3444
4254
  if (style === 'lookup') return syncLookup(m, err);
3445
4255
  if (style === 'rich') return syncRich(m, err);
3446
4256
  if (m.input !== null) {
@@ -3515,6 +4325,7 @@ function sync(m: Mounted): void {
3515
4325
  case 'progress': syncProgress(m); return;
3516
4326
  case 'canvas': syncCanvas(m); return;
3517
4327
  case 'chart': syncChart(m); return;
4328
+ case 'orbit': syncOrbit(m); return;
3518
4329
  case 'icon': syncIcon(m); return;
3519
4330
  case 'video': case 'audio': syncMedia(m); return;
3520
4331
  case 'image': {
@@ -3632,6 +4443,35 @@ function setExtra(e: HTMLElement, cls: string[]): void {
3632
4443
  e.dataset['tb'] = cls.join(' ');
3633
4444
  }
3634
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
+
3635
4475
  function syncDirty(): void {
3636
4476
  for (const ctx of dirty) {
3637
4477
  ctx.dirty = false;
@@ -3687,9 +4527,14 @@ function startHistory(): void {
3687
4527
  history.replaceState({ ...here }, '');
3688
4528
  }
3689
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
+
3690
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. */
3691
4535
  function landHistory(): void {
3692
4536
  const state = history.state as { depth?: number } | null;
4537
+ before = { ...here };
3693
4538
  if (typeof state?.depth === 'number') here = { depth: state.depth, top: here.top };
3694
4539
  else here = { depth: here.depth + 1, top: here.depth + 1 };
3695
4540
  history.replaceState({ ...here }, '');
@@ -3708,6 +4553,24 @@ native('set-route', '["Puts a screen and arguments in the address bar." route [b
3708
4553
  return value(f.args[0]!);
3709
4554
  });
3710
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
+
3711
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)])));
3712
4575
 
3713
4576
  native('route-back', '["Goes one step back in the history." ]', () => {
@@ -3821,11 +4684,34 @@ native('apply-theme', '["Changes the look of the whole screen." spec [object!]]'
3821
4684
  // --- boot --------------------------------------------------------------------------
3822
4685
 
3823
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
+ }
3824
4700
  setTheme(DEFAULT_THEME);
3825
- host = startHost();
3826
- host.sch.afterPump = syncDirty;
4701
+ host = startHost({ onError: e => showError(report(e)) });
4702
+ host.sch.afterPump = () => {
4703
+ react();
4704
+ syncDirty();
4705
+ devLog.repainted();
4706
+ };
3827
4707
  document.addEventListener('keydown', onKeyDown, true);
3828
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));
3829
4715
  document.addEventListener('pointerdown', onPointerDown);
3830
4716
  document.addEventListener('pointermove', onPointerMove, { passive: false });
3831
4717
  document.addEventListener('pointerup', () => endDrag(true));
@@ -3834,8 +4720,33 @@ async function boot(): Promise<void> {
3834
4720
  // a touch drag must not scroll the page
3835
4721
  document.addEventListener('touchmove', ev => { if (dragging?.on) ev.preventDefault(); }, { passive: false });
3836
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
+ }
3837
4742
  startHistory();
3838
4743
  window.addEventListener('hashchange', () => {
4744
+ if (undoing !== null) {
4745
+ here = undoing;
4746
+ undoing = null;
4747
+ history.replaceState({ ...here }, '');
4748
+ return;
4749
+ }
3839
4750
  landHistory();
3840
4751
  if (screensFace !== null) void fire('ui-route', screensFace, routeBlock());
3841
4752
  });
@@ -3843,11 +4754,11 @@ async function boot(): Promise<void> {
3843
4754
  for (const s of Array.from(document.querySelectorAll<HTMLScriptElement>('script[type="text/trebol"]'))) {
3844
4755
  const src = s.getAttribute('src');
3845
4756
  const url = src !== null ? new URL(src, location.href).href : location.href;
3846
- 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 ?? '';
3847
4758
  try {
3848
4759
  await runSource(host, code, url);
3849
4760
  } catch (e) {
3850
- console.error(e instanceof Error ? e.message : report(e as ObjectCell));
4761
+ showError(e instanceof Error ? e.message : report(e as ObjectCell));
3851
4762
  }
3852
4763
  }
3853
4764
  }