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
@@ -14,16 +14,21 @@
14
14
  // nodes, so `total/text: "42"` shows up without any explicit refresh.
15
15
  // Changing a series in place (`append f/text "x"`) does not mark the face:
16
16
  // set the field again to repaint it.
17
- import { logic, K, NONE, TRUE, FALSE, native, value, string, form, money, decToNumber, decFromNumber, ctxFind, intern, spell, text, canon, blockOf, wordOf, char, compare, UNSET, throwError, } from "../core/index.js";
17
+ import { logic, K, NONE, TRUE, FALSE, native, value, string, form, money, decToNumber, decFromNumber, ctxFind, intern, spell, text, canon, blockOf, wordOf, char, compare, UNSET, throwError, toJson, parseJson, } from "../core/index.js";
18
18
  import { mapAt, startHost, startUi, runSource, report, shown, translate, uiText, activeLanguage, editLocal, readLocal, readDate, weekStart, fileSize, LOCAL_KINDS } from "./index.js";
19
- import { spawn, taskResult, handleOf } from "./scheduler.js";
19
+ import { spawn, runNow, taskResult, handleOf } from "./scheduler.js";
20
20
  import { themeCss, DEFAULT_THEME, LOOKS, THEME_WORDS } from "./theme.js";
21
21
  import { iconNode } from "./icons.js";
22
- import { parseMd, printMd, safeHref } from "./markdown.js";
22
+ import { interCss } from "./fonts.js";
23
+ import { addBuiltIn, builtInText } from "./modules.js";
24
+ import { parseMd, printMd, appendText, safeHref } from "./markdown.js";
23
25
  import { fileHandle } from "./net.js";
24
26
  import { drawSvg } from "./draw.js";
25
- import { rowField, groupRow, sortGroups } from "./rows.js";
27
+ import { rowField, groupRow, sortGroups, rowWindow, DRAW_ALL_UP_TO } from "./rows.js";
26
28
  import { chartSvg, SERIES_COLORS, pieColor } from "./chart.js";
29
+ import { readOrbit, layoutOrbit, shownEdges, edgeLabel, bubble, gradients, edgePath, ease, fitCamera, MANY } from "./orbit.js";
30
+ import { devLog } from "./devlog.js";
31
+ import { startDevtools, inDevtools, faceRef } from "./devtools.js";
27
32
  // --- reading faces -----------------------------------------------------------------
28
33
  function get(face, name) {
29
34
  const i = ctxFind(face.ctx, intern(name));
@@ -160,16 +165,83 @@ const rowOf = new WeakMap();
160
165
  const byCtx = new WeakMap();
161
166
  /** Contexts of mounted faces written since the last repaint (filled by the core). */
162
167
  const dirty = [];
168
+ /** Mounted faces with react, is or calc; and whether one came since reactions last ran. */
169
+ const reactors = new Set();
170
+ let newReactor = false;
171
+ /** The ui-react still running because a reaction waits (a fetch); the next one waits for it. */
172
+ let reacting = null;
163
173
  let nextId = 1;
164
174
  const ACTIVE = new Set([K.Word, K.SetWord, K.GetWord, K.Paren, K.Path, K.SetPath, K.GetPath, K.Function, K.Native]);
165
- /** Runs a UI event function (ui-input, ui-blur, ui-click) as a new task. */
175
+ /** The handler each UI event function runs, to name it in an error; the others go by their own name. */
176
+ const HANDLERS = {
177
+ 'ui-click': 'action', 'ui-input': 'on-change', 'ui-files': 'on-change', 'ui-remove-file': 'on-change',
178
+ 'ui-lookup-pick': 'on-change', 'ui-lookup-remove': 'on-change', 'ui-lookup-search': 'on-search',
179
+ 'ui-select': 'on-select', 'ui-sort': 'on-sort', 'ui-drop': 'on-drop', 'ui-menu': 'on-menu',
180
+ 'ui-reorder': 'on-reorder', 'ui-expand': 'on-expand', 'ui-close': 'on-close',
181
+ };
182
+ /**
183
+ * An error of a UI event function says where in the app it happened: `action of button "Save"`, not the
184
+ * name of Trebol's own function (ui-click) that ran it.
185
+ */
186
+ function whereInApp(e, fn, face, args) {
187
+ const i = ctxFind(e.ctx, intern('where'));
188
+ const w = i < 0 ? null : e.ctx.vals[i];
189
+ if (w === null || w.t !== K.Word || spell(w.sym) !== fn)
190
+ return;
191
+ const ev = fn === 'ui-event' && args[0] !== undefined && args[0].t === K.LitWord ? spell(args[0].sym) : null;
192
+ e.ctx.vals[i] = string(`${ev ?? HANDLERS[fn] ?? fn.replace(/^ui-/, '')} of ${faceRef(face, host.rt)}`);
193
+ }
194
+ /**
195
+ * Runs a UI event function (ui-input, ui-blur, ui-click) as a new task. An error is shown and gives none, so
196
+ * what the caller does next (focus the first problem, blur) still runs and nothing is left unhandled.
197
+ */
166
198
  function fire(fn, face, ...args) {
167
199
  // a word, path or paren given as data (a dropped `date`) is quoted, so it is passed, not evaluated
168
200
  const quote = { t: K.Word, sym: intern('quote'), bind: host.rt.lib };
169
201
  const call = [{ t: K.Word, sym: intern(fn), bind: host.rt.user }, face, ...args.flatMap(a => ACTIVE.has(a.t) ? [quote, a] : [a])];
170
- const t = taskResult(spawn(host.sch, { data: call }, 0));
171
- t.catch(e => console.error(report(e)));
172
- return t;
202
+ devLog.event(fn, face, args);
203
+ return taskResult(spawn(host.sch, { data: call }, 0)).catch((e) => {
204
+ if (e.t === K.Error)
205
+ whereInApp(e, fn, face, args);
206
+ showError(report(e));
207
+ return NONE;
208
+ });
209
+ }
210
+ /** The panel of errors trebol dev shows on the page; null until the first one. */
211
+ let devErrors = null;
212
+ /**
213
+ * An error nobody caught: in the console and, when trebol dev serves the page (it adds
214
+ * `<meta name="trebol-dev">`), also on the page, so a broken app is not a blank page.
215
+ */
216
+ function showError(message) {
217
+ console.error(message);
218
+ devLog.note('error', message);
219
+ if (document.querySelector('meta[name="trebol-dev"]') === null)
220
+ return;
221
+ if (devErrors === null || !devErrors.isConnected) {
222
+ // a manual popover sits in the top layer, above open dialogs
223
+ const panel = el('section', 'tb-dev-errors');
224
+ panel.popover = 'manual';
225
+ panel.setAttribute('role', 'alert');
226
+ panel.setAttribute('aria-label', 'Trebol error');
227
+ const head = el('header');
228
+ const title = el('span');
229
+ title.textContent = 'Trebol error';
230
+ const close = el('button', 'tb-button');
231
+ close.type = 'button';
232
+ close.textContent = 'Close';
233
+ close.addEventListener('click', () => panel.remove());
234
+ panel.addEventListener('keydown', ev => { if (ev.key === 'Escape')
235
+ panel.remove(); });
236
+ head.append(title, close);
237
+ panel.append(head);
238
+ document.body.append(panel);
239
+ panel.showPopover();
240
+ devErrors = panel;
241
+ }
242
+ const pre = el('pre');
243
+ pre.textContent = message;
244
+ devErrors.append(pre);
173
245
  }
174
246
  function el(tag, cls) {
175
247
  const e = document.createElement(tag);
@@ -183,7 +255,7 @@ function build(face) {
183
255
  const m = {
184
256
  face, el: null, input: null, label: null, error: null, kids: get(face, 'pane'),
185
257
  box: null, rows: null, empty: null, button: null, radios: null, open: null, shown: undefined,
186
- typing: 0, typed: null,
258
+ typing: 0, typed: null, items: [], first: 0, end: 0, rowHeight: 0,
187
259
  };
188
260
  let node;
189
261
  if (INPUTS.has(style)) {
@@ -201,6 +273,9 @@ function build(face) {
201
273
  else if (style === 'photo') {
202
274
  node = buildPhoto(face, m);
203
275
  }
276
+ else if (style === 'widget') {
277
+ node = buildWidget(face, m);
278
+ }
204
279
  else if (style === 'lookup') {
205
280
  node = buildLookup(face, m);
206
281
  }
@@ -331,6 +406,9 @@ function build(face) {
331
406
  case 'chart':
332
407
  node = buildChart(m);
333
408
  break;
409
+ case 'orbit':
410
+ node = buildOrbit(m);
411
+ break;
334
412
  case 'icon':
335
413
  node = el('span', 'tb-icon-face');
336
414
  break;
@@ -383,6 +461,10 @@ function build(face) {
383
461
  byNode.set(m.input, m);
384
462
  byCtx.set(face.ctx, m);
385
463
  face.ctx.watch = dirty;
464
+ if (get(face, 'reactions').t === K.Block) {
465
+ reactors.add(m);
466
+ newReactor = true;
467
+ }
386
468
  listen(m, style);
387
469
  sync(m);
388
470
  return node;
@@ -521,6 +603,11 @@ function sourceAt(start) {
521
603
  if (!flag(m.face, 'drag') && !reorder)
522
604
  return null;
523
605
  const group = e.parentElement;
606
+ if (m.open === null) {
607
+ // a table or list may not draw its first rows
608
+ const index = m.first + Array.prototype.indexOf.call(group.children, e);
609
+ return { face: m.face, el: e, payload: row, within: reorder ? m : null, index, group: null };
610
+ }
524
611
  const index = Array.prototype.indexOf.call(group.children, e);
525
612
  return { face: m.face, el: e, payload: row, within: reorder ? m : null, index, group };
526
613
  }
@@ -561,7 +648,11 @@ function insertionAt(m, x, y) {
561
648
  if ((across ? x : y) > (across ? r.left + r.width / 2 : r.top + r.height / 2))
562
649
  i++;
563
650
  }
564
- return i;
651
+ return m.first + i;
652
+ }
653
+ /** How many things a container places: all the rows of a table or list, drawn or not. */
654
+ function slotCount(m) {
655
+ return isData(m) && m.open === null ? m.items.length : slots(m).length;
565
656
  }
566
657
  let line = null;
567
658
  /** Shows where a drop would land: a line between slots, and the target outlined. */
@@ -588,8 +679,9 @@ function indicate(t) {
588
679
  const across = horizontal(t.m);
589
680
  const all = t.group !== undefined ? Array.from(t.group.children) : slots(t.m);
590
681
  const box = (t.group ?? t.m.box ?? t.m.el).getBoundingClientRect();
591
- const before = all[t.index]?.getBoundingClientRect();
592
- const after = all[t.index - 1]?.getBoundingClientRect();
682
+ const at = t.group !== undefined ? t.index : t.index - t.m.first;
683
+ const before = all[at]?.getBoundingClientRect();
684
+ const after = all[at - 1]?.getBoundingClientRect();
593
685
  line.classList.toggle('tb-across', across);
594
686
  if (across) {
595
687
  const at = before && after ? (after.right + before.left) / 2 : before ? before.left - 3 : after ? after.right + 3 : box.left + 8;
@@ -621,7 +713,7 @@ async function reorder(m, from, to, group, parent = NONE) {
621
713
  syncDirty();
622
714
  if (!had)
623
715
  return;
624
- const e = (group !== undefined ? Array.from(group.children) : slots(m))[to];
716
+ const e = group !== undefined ? group.children[to] : slots(m)[to - m.first];
625
717
  const focusable = e?.matches('[tabindex], button, a, input, textarea, select') ? e : e?.querySelector('[tabindex], button, a, input, textarea, select');
626
718
  (focusable ?? null)?.focus();
627
719
  }
@@ -640,7 +732,7 @@ function moveTargets(face, payload) {
640
732
  continue;
641
733
  out.push({
642
734
  text: str(z.face, 'text') ?? word(z.face, 'style') ?? '',
643
- run: () => void fire('ui-drop', z.face, payload, face, int(slots(z).length + 1), NONE),
735
+ run: () => void fire('ui-drop', z.face, payload, face, int(slotCount(z) + 1), NONE),
644
736
  });
645
737
  }
646
738
  return out;
@@ -716,6 +808,8 @@ function onPointerMove(ev) {
716
808
  }
717
809
  /** Alt+Up and Alt+Down move the focused row or child inside a reorderable container. */
718
810
  function onReorderKey(ev) {
811
+ if (inDevtools(ev.target))
812
+ return;
719
813
  if (!ev.altKey || ev.ctrlKey || ev.metaKey || (ev.key !== 'ArrowUp' && ev.key !== 'ArrowDown'))
720
814
  return;
721
815
  const at = document.activeElement;
@@ -725,7 +819,7 @@ function onReorderKey(ev) {
725
819
  if (src === null || src.within === null)
726
820
  return;
727
821
  const to = src.index + (ev.key === 'ArrowUp' ? -1 : 1);
728
- if (to < 0 || to >= (src.group !== null ? src.group.children.length : slots(src.within).length))
822
+ if (to < 0 || to >= (src.group !== null ? src.group.children.length : slotCount(src.within)))
729
823
  return;
730
824
  ev.preventDefault();
731
825
  seenKeys.add(ev);
@@ -1143,6 +1237,8 @@ function shortcutLabel(spec) {
1143
1237
  }
1144
1238
  /** Shortcuts beat the browser's own keys; the view's on-key gets keys nobody handled. */
1145
1239
  function onKeyDown(ev) {
1240
+ if (inDevtools(ev.target))
1241
+ return;
1146
1242
  const modal = Array.from(document.querySelectorAll('dialog[open]')).pop();
1147
1243
  for (const m of shortcuts) {
1148
1244
  if (!m.el.isConnected) {
@@ -1162,6 +1258,8 @@ function onKeyDown(ev) {
1162
1258
  }
1163
1259
  }
1164
1260
  function onViewKey(ev) {
1261
+ if (inDevtools(ev.target))
1262
+ return;
1165
1263
  if (viewKeys === null || seenKeys.has(ev) || keyCell(ev) === null)
1166
1264
  return;
1167
1265
  fireEvent(viewKeys, 'on-key', keyWords(ev));
@@ -1242,6 +1340,7 @@ function buildInput(face, style, m) {
1242
1340
  i.autocomplete = 'new-password';
1243
1341
  input = i;
1244
1342
  }
1343
+ input.addEventListener('focus', () => hadCaret.add(input));
1245
1344
  input.id = id;
1246
1345
  const error = el('div', 'tb-error');
1247
1346
  error.id = `${id}-error`;
@@ -1268,7 +1367,9 @@ function buildInput(face, style, m) {
1268
1367
  if (!flag(face, 'readonly'))
1269
1368
  input.value = editLocal(get(face, 'value'), activeLanguage(host.rt));
1270
1369
  });
1271
- input.addEventListener('blur', () => void fire('ui-blur', face));
1370
+ // going to the dev tools is not leaving the field: it shows no error for it
1371
+ input.addEventListener('blur', ev => { if (!inDevtools(ev.relatedTarget))
1372
+ void fire('ui-blur', face); });
1272
1373
  const iconWord = style === 'area' || style === 'choice' ? null : iconName(face);
1273
1374
  const svg = iconWord !== null ? icon(iconWord) : null;
1274
1375
  if (style === 'date') {
@@ -1641,6 +1742,106 @@ function syncPhoto(m, err) {
1641
1742
  m.error.textContent = err ?? '';
1642
1743
  syncSent(m);
1643
1744
  }
1745
+ // --- widget: an element the page's JavaScript defines ----------------------------
1746
+ //
1747
+ // The element is made by its tag, once the page has defined it (import %geo-map.js).
1748
+ // The face's value is the element's value property, both ways, as JSON; its props set
1749
+ // properties. Its change event gives the value back, and any other on-xxx of the face
1750
+ // listens to the element's event xxx, with the event's detail. The theme's custom
1751
+ // properties (--tb-*) reach it, as they reach every element of the page.
1752
+ /** What was last given to or taken from each widget, as JSON, so a repaint sets only what changed. */
1753
+ const widgetSet = new WeakMap();
1754
+ /** Events every face has, which the host listens to itself. */
1755
+ const FACE_EVENTS = new Set(['on-change', 'on-focus', 'on-unfocus', 'on-over', 'on-dbl-click', 'on-key', 'on-end',
1756
+ 'on-drop', 'on-reorder', 'on-menu', 'on-select']);
1757
+ /** A JavaScript value as Trebol's, as JSON carries it; none for what JSON cannot write. */
1758
+ function fromJs(x) {
1759
+ let json;
1760
+ try {
1761
+ json = JSON.stringify(x);
1762
+ }
1763
+ catch {
1764
+ json = undefined;
1765
+ }
1766
+ if (json === undefined)
1767
+ return NONE;
1768
+ const v = parseJson(json);
1769
+ return typeof v === 'string' ? NONE : v;
1770
+ }
1771
+ function buildWidget(face, m) {
1772
+ const id = `tb-${nextId++}`;
1773
+ const wrap = el('div', 'tb-field');
1774
+ const label = el('label', 'tb-label');
1775
+ label.htmlFor = id;
1776
+ const control = el('div', 'tb-control');
1777
+ let node;
1778
+ try {
1779
+ node = document.createElement(str(face, 'tag') ?? 'div');
1780
+ }
1781
+ catch {
1782
+ // a tag that is no element's name
1783
+ node = el('div');
1784
+ }
1785
+ node.classList.add('tb-widget');
1786
+ node.id = id;
1787
+ const error = el('div', 'tb-error');
1788
+ error.id = `${id}-error`;
1789
+ error.setAttribute('aria-live', 'polite');
1790
+ node.setAttribute('aria-describedby', error.id);
1791
+ widgetSet.set(node, { value: '', props: '' });
1792
+ node.addEventListener('change', ev => {
1793
+ if (ev.target !== node)
1794
+ return;
1795
+ const v = fromJs(node.value);
1796
+ widgetSet.get(node).value = toJson(v);
1797
+ void fire('ui-input', face, v);
1798
+ });
1799
+ const events = get(face, 'events');
1800
+ if (events.t === K.Block) {
1801
+ for (const w of events.s.data) {
1802
+ const name = w.t === K.Word ? spell(w.sym).toLowerCase() : '';
1803
+ if (!name.startsWith('on-') || FACE_EVENTS.has(name))
1804
+ continue;
1805
+ node.addEventListener(name.slice(3), ev => fireEvent(face, name, [['detail', fromJs(ev.detail)]]));
1806
+ }
1807
+ }
1808
+ control.append(node, error);
1809
+ wrap.append(label, control);
1810
+ m.label = label;
1811
+ m.error = error;
1812
+ m.box = node;
1813
+ return wrap;
1814
+ }
1815
+ function syncWidget(m, err) {
1816
+ const f = m.face;
1817
+ const t = str(f, 'text') ?? '';
1818
+ m.label.textContent = t;
1819
+ m.label.hidden = t === '';
1820
+ m.label.classList.toggle('tb-required', required(f));
1821
+ const node = m.box;
1822
+ const set = widgetSet.get(node);
1823
+ const props = get(f, 'props');
1824
+ const propsJson = props.t === K.Object || props.t === K.Map ? toJson(props) : '{}';
1825
+ if (propsJson !== set.props) {
1826
+ Object.assign(node, JSON.parse(propsJson));
1827
+ set.props = propsJson;
1828
+ }
1829
+ const valueJson = toJson(get(f, 'value'));
1830
+ if (valueJson !== set.value) {
1831
+ node.value = JSON.parse(valueJson);
1832
+ set.value = valueJson;
1833
+ }
1834
+ const disabled = flag(f, 'disabled');
1835
+ node.toggleAttribute('disabled', disabled);
1836
+ if ('disabled' in node)
1837
+ node.disabled = disabled;
1838
+ if ('readOnly' in node)
1839
+ node.readOnly = flag(f, 'readonly');
1840
+ node.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
1841
+ if (t !== '')
1842
+ node.setAttribute('aria-label', t);
1843
+ m.error.textContent = err ?? '';
1844
+ }
1644
1845
  function accepts(file, list) {
1645
1846
  if (list.length === 0)
1646
1847
  return true;
@@ -2210,6 +2411,378 @@ function drawChart(m) {
2210
2411
  p.table.tHead.append(head);
2211
2412
  p.table.tBodies[0].append(...body);
2212
2413
  }
2414
+ let orbitCount = 0;
2415
+ /** An orbit: an SVG the size of the face, a world the camera moves, edges under the bubbles. */
2416
+ function buildOrbit(m) {
2417
+ const node = el('div', 'tb-orbit');
2418
+ const svg = document.createElementNS(SVG_NS, 'svg');
2419
+ svg.setAttribute('role', 'group');
2420
+ svg.setAttribute('tabindex', '-1');
2421
+ const defs = document.createElementNS(SVG_NS, 'defs');
2422
+ const world = document.createElementNS(SVG_NS, 'g');
2423
+ const lines = document.createElementNS(SVG_NS, 'g');
2424
+ const bubbles = document.createElementNS(SVG_NS, 'g');
2425
+ world.append(lines, bubbles);
2426
+ svg.append(defs, world);
2427
+ node.append(svg);
2428
+ const st = {
2429
+ svg, defs, world, lines, bubbles, vis: new Map(), edges: [], spec: readOrbit(NONE).spec, signature: '', page: 0, pageOf: null,
2430
+ 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,
2431
+ gradients: new Map(), width: 0, height: 0,
2432
+ };
2433
+ m.kids = st;
2434
+ orbitCamera(m, st);
2435
+ orbitKeys(m, st);
2436
+ if (typeof ResizeObserver !== 'undefined') {
2437
+ new ResizeObserver(() => {
2438
+ if (svg.clientWidth === st.width && svg.clientHeight === st.height)
2439
+ 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)
2445
+ st.camTo = fit;
2446
+ else
2447
+ st.cam = fit;
2448
+ orbitDressAll(m, st, fit.s);
2449
+ orbitApplyCam(st);
2450
+ orbitDrawEdges(st);
2451
+ }).observe(svg);
2452
+ }
2453
+ return node;
2454
+ }
2455
+ /** Drag to pan, Ctrl and the wheel (or a pinch) to zoom about the pointer, double click to fit again. */
2456
+ function orbitCamera(m, st) {
2457
+ const { svg } = st;
2458
+ let drag = null;
2459
+ svg.addEventListener('pointerdown', ev => {
2460
+ if (ev.button !== 0)
2461
+ return;
2462
+ drag = { x: ev.clientX, y: ev.clientY, cx: st.cam.x, cy: st.cam.y, id: ev.pointerId };
2463
+ st.dragged = false;
2464
+ });
2465
+ svg.addEventListener('pointermove', ev => {
2466
+ if (drag === null || ev.pointerId !== drag.id)
2467
+ return;
2468
+ const dx = ev.clientX - drag.x;
2469
+ const dy = ev.clientY - drag.y;
2470
+ if (!st.dragged && Math.hypot(dx, dy) > 4) {
2471
+ st.dragged = true;
2472
+ svg.setPointerCapture(ev.pointerId);
2473
+ svg.classList.add('tb-orbit-panning');
2474
+ }
2475
+ if (st.dragged) {
2476
+ st.cam = { ...st.cam, x: drag.cx + dx, y: drag.cy + dy };
2477
+ orbitApplyCam(st);
2478
+ }
2479
+ });
2480
+ const end = () => {
2481
+ drag = null;
2482
+ svg.classList.remove('tb-orbit-panning');
2483
+ // the click that ends a drag picks nothing
2484
+ setTimeout(() => { st.dragged = false; }, 0);
2485
+ };
2486
+ svg.addEventListener('pointerup', end);
2487
+ svg.addEventListener('pointercancel', end);
2488
+ svg.addEventListener('wheel', ev => {
2489
+ // the page scrolls past an orbit; with Ctrl (or a pinch), or when it fills the window, the wheel zooms
2490
+ if (!ev.ctrlKey && !ev.metaKey && !flag(m.face, 'fit'))
2491
+ return;
2492
+ ev.preventDefault();
2493
+ const box = svg.getBoundingClientRect();
2494
+ const ox = box.width / 2 + st.cam.x;
2495
+ const oy = box.height / 2 + st.cam.y;
2496
+ const s = Math.max(0.15, Math.min(4, st.cam.s * Math.exp(-ev.deltaY * (ev.ctrlKey ? 0.01 : 0.0015))));
2497
+ const px = ev.clientX - box.left;
2498
+ const py = ev.clientY - box.top;
2499
+ const wx = (px - ox) / st.cam.s;
2500
+ const wy = (py - oy) / st.cam.s;
2501
+ st.cam = { x: px - box.width / 2 - wx * s, y: py - box.height / 2 - wy * s, s };
2502
+ orbitApplyCam(st);
2503
+ }, { passive: false });
2504
+ svg.addEventListener('dblclick', ev => {
2505
+ if (ev.target.closest('.tb-orbit-node') !== null)
2506
+ return;
2507
+ st.camFrom = { ...st.cam };
2508
+ st.camTo = fitCamera(st.width, st.height, st.box);
2509
+ orbitAnimate(st, 500);
2510
+ });
2511
+ }
2512
+ /** Tab goes through the neighbours, Enter or Space picks one, Escape or Backspace steps back. */
2513
+ function orbitKeys(m, st) {
2514
+ st.svg.addEventListener('keydown', ev => {
2515
+ const g = ev.target.closest('.tb-orbit-node');
2516
+ if ((ev.key === 'Enter' || ev.key === ' ') && g !== null) {
2517
+ ev.preventDefault();
2518
+ orbitPick(m, st, g.dataset['key'], true);
2519
+ }
2520
+ else if ((ev.key === 'Escape' || ev.key === 'Backspace') && st.spec.trail.length > 0) {
2521
+ const back = [...st.spec.trail].reverse().find(k => st.spec.nodes.has(k));
2522
+ if (back === undefined)
2523
+ return;
2524
+ ev.preventDefault();
2525
+ ev.stopPropagation();
2526
+ orbitPick(m, st, back, true);
2527
+ }
2528
+ });
2529
+ }
2530
+ /** The person picked a bubble: a neighbour enters, the trail steps back, "+N more" turns the page. */
2531
+ function orbitPick(m, st, key, byKey) {
2532
+ if (flag(m.face, 'disabled'))
2533
+ return;
2534
+ const v = st.vis.get(key);
2535
+ if (v === undefined || v.dying)
2536
+ return;
2537
+ if (v.role === 'more') {
2538
+ st.page++;
2539
+ st.picked = st.spec.focus;
2540
+ orbitRender(m, st);
2541
+ return;
2542
+ }
2543
+ const node = st.spec.nodes.get(key);
2544
+ if (node === undefined || v.role === 'focus')
2545
+ return;
2546
+ st.picked = key;
2547
+ st.byKey = byKey;
2548
+ void fire('ui-orbit', m.face, node.id, v.role === 'trail' ? TRUE : FALSE);
2549
+ }
2550
+ function syncOrbit(m) {
2551
+ const st = m.kids;
2552
+ const { spec, error } = readOrbit(get(m.face, 'data'));
2553
+ if (error !== null)
2554
+ console.warn(`Trebol: ${error}`);
2555
+ const t = str(m.face, 'text');
2556
+ const focus = spec.focus === null ? undefined : spec.nodes.get(spec.focus);
2557
+ const focusTitle = focus === undefined ? '' : translate(focus.title, host.rt);
2558
+ st.svg.setAttribute('aria-label', t === null ? focusTitle : focusTitle === '' ? t : `${t}: ${focusTitle}`);
2559
+ // a repaint of the same thing in the same language keeps what is on screen, moving or not
2560
+ const signature = orbitSignature(spec);
2561
+ if (signature === st.signature)
2562
+ return;
2563
+ st.signature = signature;
2564
+ st.spec = spec;
2565
+ if (spec.focus !== st.pageOf) {
2566
+ st.page = 0;
2567
+ st.pageOf = spec.focus;
2568
+ }
2569
+ orbitRender(m, st);
2570
+ }
2571
+ function orbitSignature(spec) {
2572
+ const tx = (c) => (c === null ? '' : translate(c, host.rt));
2573
+ 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'));
2574
+ const edges = spec.edges.map(e => [e.from, e.to, tx(e.label), e.look].join('\u0002'));
2575
+ return [spec.focus ?? '', nodes.join('\u0001'), edges.join('\u0001'), spec.trail.join('\u0001')].join('\u0000');
2576
+ }
2577
+ /** The ids of the gradients of a color, made the first time it is used. */
2578
+ function orbitGradients(st, color) {
2579
+ let ids = st.gradients.get(color);
2580
+ if (ids === undefined) {
2581
+ const n = `tb-orbit${orbitCount++}`;
2582
+ ids = [`${n}-body`, `${n}-halo`];
2583
+ st.gradients.set(color, ids);
2584
+ st.defs.append(...gradients(color, ids[0], ids[1]).map(svgNode));
2585
+ }
2586
+ return ids;
2587
+ }
2588
+ /** 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. */
2589
+ function orbitRender(m, st) {
2590
+ const { spec } = st;
2591
+ const lay = layoutOrbit(spec, st.page);
2592
+ st.box = lay.box;
2593
+ const want = new Map(lay.placed.map(p => [p.key, p]));
2594
+ for (const [k, v] of [...st.vis]) {
2595
+ if (v.dying)
2596
+ continue;
2597
+ const p = want.get(k);
2598
+ if (p === undefined || p.role !== v.role || p.role === 'more') {
2599
+ // gone, or something else now: it fades where it is, and a new one takes its key
2600
+ v.dying = true;
2601
+ v.from = { ...v.cur };
2602
+ v.to = { ...v.cur, r: v.cur.r * (p === undefined ? 0.4 : 1), o: 0 };
2603
+ v.g.setAttribute('tabindex', '-1');
2604
+ v.g.setAttribute('aria-hidden', 'true');
2605
+ st.vis.delete(k);
2606
+ st.vis.set(`${k}\u0000old${orbitCount++}`, v);
2607
+ if (p !== undefined)
2608
+ st.vis.set(k, orbitBubble(m, st, p, { ...v.cur }));
2609
+ }
2610
+ else {
2611
+ v.from = { ...v.cur };
2612
+ v.to = p;
2613
+ }
2614
+ }
2615
+ const was = st.picked === null ? undefined : [...st.vis.values()].find(v => v.key === st.picked);
2616
+ const spawn = was !== undefined ? was.cur : { x: 0, y: 0 };
2617
+ for (const p of lay.placed) {
2618
+ if (st.vis.has(p.key))
2619
+ continue;
2620
+ st.vis.set(p.key, orbitBubble(m, st, p, { x: spawn.x, y: spawn.y, r: p.r * 0.2, o: 0 }));
2621
+ }
2622
+ st.width = st.svg.clientWidth;
2623
+ st.height = st.svg.clientHeight;
2624
+ st.camFrom = { ...st.cam };
2625
+ st.camTo = fitCamera(st.width || 600, st.height || 480, lay.box);
2626
+ st.placed = lay.placed;
2627
+ st.left = lay.left;
2628
+ orbitDressAll(m, st, st.camTo.s);
2629
+ st.bubbles.append(...lay.placed.map(p => st.vis.get(p.key).g));
2630
+ st.picked = null;
2631
+ orbitAnimate(st, matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 900);
2632
+ if (st.byKey) {
2633
+ st.byKey = false;
2634
+ st.svg.focus();
2635
+ }
2636
+ }
2637
+ /** Every bubble on show drawn anew (its title, hints and size may have changed), and the edges, for the camera's zoom. */
2638
+ function orbitDressAll(m, st, scale) {
2639
+ for (const p of st.placed) {
2640
+ const v = st.vis.get(p.key);
2641
+ if (v !== undefined)
2642
+ orbitDress(m, st, v, p, st.left, scale);
2643
+ }
2644
+ orbitEdges(st, st.placed, scale);
2645
+ }
2646
+ function orbitBubble(m, st, p, start) {
2647
+ const g = document.createElementNS(SVG_NS, 'g');
2648
+ const inner = document.createElementNS(SVG_NS, 'g');
2649
+ g.append(inner);
2650
+ g.dataset['key'] = p.key;
2651
+ g.addEventListener('click', ev => {
2652
+ if (st.dragged)
2653
+ return;
2654
+ ev.stopPropagation();
2655
+ orbitPick(m, st, p.key, false);
2656
+ });
2657
+ // with many neighbours, the labels of a bubble's edges show while the pointer is on it
2658
+ g.addEventListener('pointerenter', () => orbitHover(st, p.key, true));
2659
+ g.addEventListener('pointerleave', () => orbitHover(st, p.key, false));
2660
+ g.addEventListener('focus', () => orbitHover(st, p.key, true));
2661
+ g.addEventListener('blur', () => orbitHover(st, p.key, false));
2662
+ st.bubbles.append(g);
2663
+ return { key: p.key, g, inner, role: p.role, cur: start, from: { ...start }, to: p, dying: false };
2664
+ }
2665
+ /** What a bubble shows and how it reads: a link to a neighbour, back to the trail, or the next page. */
2666
+ function orbitDress(m, st, v, p, left, scale) {
2667
+ const node = st.spec.nodes.get(p.key) ?? null;
2668
+ const title = p.role === 'more' ? (left > 0 ? own('orbit-more', String(left)) : own('orbit-first')) : node === null ? '' : translate(node.title, host.rt);
2669
+ const color = p.role === 'more' ? 'var(--tb-muted)' : node?.color ?? 'var(--tb-primary)';
2670
+ const [body, halo] = orbitGradients(st, color);
2671
+ const label = p.role === 'near' ? orbitEdgeText(st.spec, p.key) : '';
2672
+ const said = p.role === 'trail' ? own('orbit-back-to', title) : label === '' ? title : `${title}, ${label}`;
2673
+ v.g.setAttribute('class', `tb-orbit-node tb-orbit-${p.role}`);
2674
+ const tip = document.createElementNS(SVG_NS, 'title');
2675
+ tip.textContent = said;
2676
+ v.g.replaceChildren(tip, v.inner);
2677
+ 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));
2678
+ if (p.role === 'focus') {
2679
+ // Chrome stops Tab on an SVG group with a click handler unless told not to
2680
+ v.g.setAttribute('tabindex', '-1');
2681
+ v.g.removeAttribute('role');
2682
+ v.g.removeAttribute('aria-label');
2683
+ v.g.setAttribute('aria-hidden', 'true');
2684
+ }
2685
+ else {
2686
+ v.g.setAttribute('tabindex', '0');
2687
+ v.g.setAttribute('role', p.role === 'more' ? 'button' : 'link');
2688
+ v.g.setAttribute('aria-label', said);
2689
+ v.g.removeAttribute('aria-hidden');
2690
+ }
2691
+ if (flag(m.face, 'disabled'))
2692
+ v.g.setAttribute('tabindex', '-1');
2693
+ }
2694
+ function orbitEdgeText(spec, key) {
2695
+ const c = edgeLabel(spec, key);
2696
+ return c === null ? '' : translate(c, host.rt);
2697
+ }
2698
+ function orbitEdges(st, placed, scale) {
2699
+ const many = placed.filter(p => p.role === 'near').length > MANY;
2700
+ st.edges = shownEdges(st.spec, placed).map(e => {
2701
+ const path = document.createElementNS(SVG_NS, 'path');
2702
+ path.setAttribute('class', `tb-orbit-edge tb-orbit-edge-${e.trail ? 'trail' : e.look}`);
2703
+ let text = null;
2704
+ if (e.label !== null) {
2705
+ text = document.createElementNS(SVG_NS, 'text');
2706
+ text.setAttribute('class', many ? 'tb-orbit-label tb-orbit-later' : 'tb-orbit-label');
2707
+ // the size of the page's small text once the camera fits
2708
+ text.style.fontSize = `${11 / scale}px`;
2709
+ text.style.strokeWidth = `${3 / scale}px`;
2710
+ text.textContent = translate(e.label, host.rt);
2711
+ }
2712
+ return { a: e.from, b: e.to, path, text, curve: e.curve };
2713
+ });
2714
+ st.lines.replaceChildren(...st.edges.flatMap(e => (e.text === null ? [e.path] : [e.path, e.text])));
2715
+ st.lines.setAttribute('aria-hidden', 'true');
2716
+ }
2717
+ function orbitHover(st, key, on) {
2718
+ for (const e of st.edges)
2719
+ if (e.text !== null && (e.a === key || e.b === key))
2720
+ e.text.classList.toggle('tb-orbit-shown', on);
2721
+ }
2722
+ function orbitApplyCam(st) {
2723
+ const w = st.svg.clientWidth || st.width;
2724
+ const h = st.svg.clientHeight || st.height;
2725
+ st.world.setAttribute('transform', `translate(${w / 2 + st.cam.x},${h / 2 + st.cam.y}) scale(${st.cam.s})`);
2726
+ }
2727
+ /** Tweens every bubble and the camera from where they are to where they go; 0 ms puts them there at once. */
2728
+ function orbitAnimate(st, ms) {
2729
+ cancelAnimationFrame(st.anim);
2730
+ const t0 = performance.now();
2731
+ const step = (now) => {
2732
+ const k = ms === 0 ? 1 : ease(Math.min(1, (now - t0) / ms));
2733
+ for (const v of st.vis.values()) {
2734
+ if (v.from !== v.to || v.dying) {
2735
+ const f = v.from;
2736
+ const t = v.to;
2737
+ 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 };
2738
+ }
2739
+ v.g.setAttribute('transform', `translate(${v.cur.x},${v.cur.y})`);
2740
+ v.inner.setAttribute('transform', `scale(${Math.max(v.cur.r, 0.001)})`);
2741
+ v.g.style.opacity = String(v.cur.o);
2742
+ v.g.style.pointerEvents = v.cur.o < 0.05 ? 'none' : '';
2743
+ }
2744
+ if (st.camFrom !== null && st.camTo !== null) {
2745
+ const a = st.camFrom;
2746
+ const b = st.camTo;
2747
+ 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 };
2748
+ }
2749
+ orbitApplyCam(st);
2750
+ orbitDrawEdges(st);
2751
+ if (k < 1)
2752
+ st.anim = requestAnimationFrame(step);
2753
+ else {
2754
+ st.camFrom = st.camTo = null;
2755
+ for (const [k2, v] of st.vis) {
2756
+ if (v.dying) {
2757
+ v.g.remove();
2758
+ st.vis.delete(k2);
2759
+ }
2760
+ }
2761
+ }
2762
+ };
2763
+ if (ms === 0)
2764
+ step(t0);
2765
+ else
2766
+ st.anim = requestAnimationFrame(step);
2767
+ }
2768
+ function orbitDrawEdges(st) {
2769
+ for (const e of st.edges) {
2770
+ const a = st.vis.get(e.a);
2771
+ const b = st.vis.get(e.b);
2772
+ if (a === undefined || b === undefined) {
2773
+ e.path.setAttribute('d', '');
2774
+ continue;
2775
+ }
2776
+ const at = edgePath(a.cur, b.cur, e.curve);
2777
+ e.path.setAttribute('d', at.d);
2778
+ const o = String(Math.min(a.cur.o, b.cur.o));
2779
+ e.path.style.opacity = o;
2780
+ if (e.text !== null) {
2781
+ e.text.setAttribute('transform', `translate(${at.x},${at.y}) rotate(${at.angle}) translate(0,-5)`);
2782
+ e.text.style.opacity = o;
2783
+ }
2784
+ }
2785
+ }
2213
2786
  function syncIcon(m) {
2214
2787
  const name = iconName(m.face) ?? '';
2215
2788
  const label = str(m.face, 'text');
@@ -2466,7 +3039,10 @@ function buildRich(face, m) {
2466
3039
  error.setAttribute('aria-live', 'polite');
2467
3040
  box.setAttribute('aria-describedby', error.id);
2468
3041
  label.addEventListener('click', () => box.focus());
3042
+ keepCarets();
2469
3043
  const changed = () => {
3044
+ if (inserting)
3045
+ return;
2470
3046
  const md = printMd(readBlocks(box));
2471
3047
  if (md === m.shown)
2472
3048
  return;
@@ -2480,7 +3056,7 @@ function buildRich(face, m) {
2480
3056
  });
2481
3057
  box.addEventListener('drop', ev => ev.preventDefault());
2482
3058
  wrap.addEventListener('focusout', ev => {
2483
- if (!wrap.contains(ev.relatedTarget))
3059
+ if (!wrap.contains(ev.relatedTarget) && !inDevtools(ev.relatedTarget))
2484
3060
  void fire('ui-blur', face);
2485
3061
  });
2486
3062
  let saved = null;
@@ -2616,8 +3192,74 @@ function syncRich(m, err) {
2616
3192
  if (md !== m.shown && document.activeElement !== box) {
2617
3193
  m.shown = md;
2618
3194
  box.replaceChildren(...blockNodes(parseMd(md)));
3195
+ richCaret.delete(box);
2619
3196
  }
2620
3197
  }
3198
+ // --- inserting text at the cursor ---------------------------------------------------
3199
+ //
3200
+ // insert-text puts text where the user's cursor was, even after a click on a button or
3201
+ // a choice took the focus away: an input keeps its selection, a rich text box has
3202
+ // its last one kept here.
3203
+ /** Inputs that have had the focus, so a cursor of their own. */
3204
+ const hadCaret = new WeakSet();
3205
+ /** The last selection inside each rich text box. */
3206
+ const richCaret = new WeakMap();
3207
+ /** While insert-text writes in a rich text box, its own input event is not the user's. */
3208
+ let inserting = false;
3209
+ let keepingCarets = false;
3210
+ function keepCarets() {
3211
+ if (keepingCarets)
3212
+ return;
3213
+ keepingCarets = true;
3214
+ document.addEventListener('selectionchange', () => {
3215
+ const s = getSelection();
3216
+ if (s === null || s.rangeCount === 0)
3217
+ return;
3218
+ const n = s.anchorNode;
3219
+ const box = (n instanceof Element ? n : n?.parentElement)?.closest('.tb-rich-box');
3220
+ if (box != null)
3221
+ richCaret.set(box, s.getRangeAt(0).cloneRange());
3222
+ });
3223
+ }
3224
+ 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) => {
3225
+ const face = f.args[0];
3226
+ const add = text(f.args[1]);
3227
+ const rich = word(face, 'style') === 'rich';
3228
+ const was = str(face, 'value') ?? '';
3229
+ const m = byCtx.get(face.ctx);
3230
+ if (m === undefined || !m.el.isConnected)
3231
+ return value(string(rich ? appendText(was, add) : was + add));
3232
+ if (rich) {
3233
+ const box = m.box;
3234
+ const at = richCaret.get(box);
3235
+ box.focus();
3236
+ const s = getSelection();
3237
+ if (at !== undefined && box.contains(at.commonAncestorContainer)) {
3238
+ s.removeAllRanges();
3239
+ s.addRange(at);
3240
+ }
3241
+ else {
3242
+ s.selectAllChildren(box);
3243
+ s.collapseToEnd();
3244
+ }
3245
+ inserting = true;
3246
+ try {
3247
+ document.execCommand('insertText', false, add);
3248
+ }
3249
+ finally {
3250
+ inserting = false;
3251
+ }
3252
+ const md = printMd(readBlocks(box));
3253
+ m.shown = md;
3254
+ return value(string(md));
3255
+ }
3256
+ const input = m.input;
3257
+ const end = input.value.length;
3258
+ const [from, to] = hadCaret.has(input) ? [input.selectionStart ?? end, input.selectionEnd ?? end] : [end, end];
3259
+ input.focus();
3260
+ input.setRangeText(add, from, to, 'end');
3261
+ return value(string(input.value));
3262
+ });
2621
3263
  function columns(face) {
2622
3264
  const c = get(face, 'columns');
2623
3265
  if (c.t !== K.Block)
@@ -2700,7 +3342,16 @@ function buildRows(face, style, m) {
2700
3342
  const totals = newTableRow(cols);
2701
3343
  totals.className = 'tb-totals';
2702
3344
  foot.append(totals);
2703
- table.append(head, box, foot);
3345
+ // the room of the rows not drawn, above and below the ones drawn
3346
+ const room = () => {
3347
+ const b = el('tbody', 'tb-room');
3348
+ b.setAttribute('aria-hidden', 'true');
3349
+ const r = el('tr');
3350
+ r.append(el('td'));
3351
+ b.append(r);
3352
+ return b;
3353
+ };
3354
+ table.append(head, room(), box, room(), foot);
2704
3355
  wrap.append(table);
2705
3356
  }
2706
3357
  else {
@@ -2727,37 +3378,74 @@ function buildRows(face, style, m) {
2727
3378
  m.empty = empty;
2728
3379
  return wrap;
2729
3380
  }
2730
- /** Creates, updates, moves or removes only the rows whose key changed. */
3381
+ /** The rows of a table or list in the order shown, with their keys; then draws them. */
2731
3382
  function syncRows(m) {
2732
3383
  const f = m.face;
2733
- const box = m.box;
2734
- const table = box.tagName === 'TBODY';
2735
- const cols = columns(f);
2736
3384
  const data = get(f, 'data');
2737
3385
  let rows = data.t === K.Block ? data.s.data.slice(data.i) : [];
2738
- if (table) {
2739
- syncHead(f, box.parentElement, cols);
3386
+ if (m.box.tagName === 'TBODY') {
3387
+ syncHead(f, m.box.parentElement, columns(f));
2740
3388
  const order = hostSorted(f);
2741
3389
  if (order !== null)
2742
3390
  rows = sortGroups(rows, order.sym, order.desc, activeLanguage(host.rt), cellText);
2743
3391
  }
2744
3392
  const keyWord = get(f, 'key');
2745
3393
  const key = keyWord.t === K.Word || keyWord.t === K.LitWord ? keyWord.sym : intern('id');
3394
+ const seen = new Set();
3395
+ m.items = rows.map((row, i) => {
3396
+ const group = groupRow(row);
3397
+ let k;
3398
+ if (group !== null)
3399
+ k = `${group.kind}#${i}`;
3400
+ else {
3401
+ const id = rowField(row, key);
3402
+ k = id.t === K.None ? `#${i}` : `${id.t}:${form(id)}`;
3403
+ if (seen.has(k))
3404
+ k = `${k}#${i}`;
3405
+ }
3406
+ seen.add(k);
3407
+ return { row, k };
3408
+ });
3409
+ drawRows(m);
3410
+ m.empty.textContent = str(f, 'text') ?? own('empty');
3411
+ m.empty.hidden = rows.length > 0;
3412
+ }
3413
+ /** Tables and lists with too many rows to draw them all. */
3414
+ const longRows = new Set();
3415
+ /** While printing, every row is drawn. */
3416
+ let printing = false;
3417
+ /** The rows to draw: all of them, or those near the screen. */
3418
+ function rowsToDraw(m) {
3419
+ const count = m.items.length;
3420
+ if (count <= DRAW_ALL_UP_TO || printing)
3421
+ return { first: 0, end: count };
3422
+ // where the first row would be: the rows drawn start below the room of those that are not
3423
+ const top = m.box.getBoundingClientRect().top - m.first * m.rowHeight;
3424
+ const now = m.end > m.first ? { first: m.first, end: m.end } : undefined;
3425
+ return rowWindow(count, m.rowHeight || 48, -top, innerHeight, now);
3426
+ }
3427
+ /** Creates, updates, moves or removes only the rows drawn whose key changed. */
3428
+ function drawRows(m, again = true) {
3429
+ const f = m.face;
3430
+ const box = m.box;
3431
+ const table = box.tagName === 'TBODY';
3432
+ const cols = columns(f);
2746
3433
  const selected = get(f, 'selected');
2747
3434
  const selectable = handlerFor(f, 'on-select');
2748
3435
  box.parentElement.classList.toggle('tb-selectable', selectable);
3436
+ const { first, end } = rowsToDraw(m);
3437
+ const count = m.items.length;
2749
3438
  const old = m.rows;
2750
3439
  const next = new Map();
2751
3440
  let cursor = box.firstChild;
2752
- rows.forEach((row, i) => {
3441
+ for (let i = first; i < end; i++) {
3442
+ const { row, k } = m.items[i];
2753
3443
  const group = groupRow(row);
3444
+ let item = old.get(k);
2754
3445
  if (group !== null) {
2755
3446
  // a group's head or foot: kept by its place, never chosen, dragged or sorted
2756
- const k = `${group.kind}#${i}`;
2757
- let item = old.get(k);
2758
3447
  if (item === undefined)
2759
3448
  item = group.kind === 'head' ? newGroupHead(cols, table) : table ? newTableRow(cols) : newListItem();
2760
- next.set(k, item);
2761
3449
  item.className = `tb-group-${group.kind} tb-level-${group.level}`;
2762
3450
  if (group.kind === 'head') {
2763
3451
  const t = translate(group.value, host.rt);
@@ -2769,43 +3457,139 @@ function syncRows(m) {
2769
3457
  }
2770
3458
  else
2771
3459
  fillRow(item, group.value, cols, table);
2772
- if (item !== cursor)
2773
- box.insertBefore(item, cursor);
3460
+ }
3461
+ else {
3462
+ if (item === undefined)
3463
+ item = table ? newTableRow(cols) : newListItem();
3464
+ rowOf.set(item, row);
3465
+ fillRow(item, row, cols, table);
3466
+ if (selectable)
3467
+ item.tabIndex = 0;
2774
3468
  else
2775
- cursor = cursor.nextSibling;
2776
- return;
3469
+ item.removeAttribute('tabindex');
3470
+ const on = selected.t !== K.None && sameRow(selected, row);
3471
+ item.classList.toggle('tb-selected', on);
3472
+ if (selectable)
3473
+ item.setAttribute('aria-selected', on ? 'true' : 'false');
3474
+ else
3475
+ item.removeAttribute('aria-selected');
2777
3476
  }
2778
- const id = rowField(row, key);
2779
- let k = id.t === K.None ? `#${i}` : `${id.t}:${form(id)}`;
2780
- if (next.has(k))
2781
- k = `${k}#${i}`;
2782
- let item = old.get(k);
2783
- if (item === undefined)
2784
- item = table ? newTableRow(cols) : newListItem();
2785
3477
  next.set(k, item);
2786
- rowOf.set(item, row);
2787
- fillRow(item, row, cols, table);
2788
- if (selectable)
2789
- item.tabIndex = 0;
2790
- else
2791
- item.removeAttribute('tabindex');
2792
- const on = selected.t !== K.None && sameRow(selected, row);
2793
- item.classList.toggle('tb-selected', on);
2794
- if (selectable)
2795
- item.setAttribute('aria-selected', on ? 'true' : 'false');
2796
- else
2797
- item.removeAttribute('aria-selected');
3478
+ // with rows left undrawn, each says where it is among all of them
3479
+ if (count > end - first) {
3480
+ item.setAttribute(table ? 'aria-rowindex' : 'aria-posinset', String(table ? i + 2 : i + 1));
3481
+ if (!table)
3482
+ item.setAttribute('aria-setsize', String(count));
3483
+ }
3484
+ else {
3485
+ item.removeAttribute(table ? 'aria-rowindex' : 'aria-posinset');
3486
+ item.removeAttribute('aria-setsize');
3487
+ }
2798
3488
  if (item !== cursor)
2799
3489
  box.insertBefore(item, cursor);
2800
3490
  else
2801
3491
  cursor = cursor.nextSibling;
2802
- });
3492
+ }
2803
3493
  for (const [k, item] of old)
2804
3494
  if (next.get(k) !== item)
2805
3495
  item.remove();
2806
3496
  m.rows = next;
2807
- m.empty.textContent = str(f, 'text') ?? own('empty');
2808
- m.empty.hidden = rows.length > 0;
3497
+ m.first = first;
3498
+ m.end = end;
3499
+ if (table) {
3500
+ if (count > end - first)
3501
+ box.parentElement.setAttribute('aria-rowcount', String(count + 1));
3502
+ else
3503
+ box.parentElement.removeAttribute('aria-rowcount');
3504
+ }
3505
+ if (count <= DRAW_ALL_UP_TO) {
3506
+ longRows.delete(m);
3507
+ room(m, 0, 0);
3508
+ if (table)
3509
+ keepColumns(box.parentElement, false);
3510
+ return;
3511
+ }
3512
+ longRows.add(m);
3513
+ if (table)
3514
+ keepColumns(box.parentElement, true);
3515
+ // how tall a row is, from those drawn; the room of the others follows it
3516
+ const drawn = end - first;
3517
+ const h = box.getBoundingClientRect().height - (table ? 0 : parseFloat(box.style.paddingTop || '0') + parseFloat(box.style.paddingBottom || '0'));
3518
+ if (drawn > 0 && h > 0)
3519
+ m.rowHeight = h / drawn;
3520
+ room(m, first * m.rowHeight, (count - end) * m.rowHeight);
3521
+ // a first guess of the height may have drawn the wrong rows
3522
+ if (again) {
3523
+ const want = rowsToDraw(m);
3524
+ if (want.first !== first || want.end !== end)
3525
+ drawRows(m, false);
3526
+ }
3527
+ }
3528
+ /**
3529
+ * A long table keeps the widths its columns first took, as shares of its width,
3530
+ * so they do not change with the rows drawn while it scrolls.
3531
+ */
3532
+ function keepColumns(table, keep) {
3533
+ const ths = Array.from(table.tHead.rows[0].cells);
3534
+ if (!keep) {
3535
+ table.classList.remove('tb-fixed');
3536
+ for (const th of ths)
3537
+ th.style.width = '';
3538
+ return;
3539
+ }
3540
+ if (table.classList.contains('tb-fixed'))
3541
+ return;
3542
+ const widths = ths.map(th => th.getBoundingClientRect().width);
3543
+ const all = widths.reduce((a, b) => a + b, 0);
3544
+ // on a narrow screen the rows are cards and the headers take no room: later
3545
+ if (all === 0)
3546
+ return;
3547
+ ths.forEach((th, i) => { th.style.width = `${(widths[i] / all) * 100}%`; });
3548
+ table.classList.add('tb-fixed');
3549
+ }
3550
+ /** Sets the room of the rows not drawn above and below those drawn. */
3551
+ function room(m, above, below) {
3552
+ const box = m.box;
3553
+ if (box.tagName === 'TBODY') {
3554
+ for (const [b, px] of [[box.previousElementSibling, above], [box.nextElementSibling, below]]) {
3555
+ const td = b.querySelector('td');
3556
+ td.style.height = `${px}px`;
3557
+ b.hidden = px === 0;
3558
+ }
3559
+ return;
3560
+ }
3561
+ box.style.paddingTop = above > 0 ? `${above}px` : '';
3562
+ box.style.paddingBottom = below > 0 ? `${below}px` : '';
3563
+ }
3564
+ let rowsFrame = 0;
3565
+ /** On a scroll or a resize, the long tables and lists draw the rows now near the screen. */
3566
+ function onRowsMoved() {
3567
+ if (rowsFrame !== 0 || longRows.size === 0)
3568
+ return;
3569
+ rowsFrame = requestAnimationFrame(() => {
3570
+ rowsFrame = 0;
3571
+ for (const m of longRows) {
3572
+ if (!m.box.isConnected) {
3573
+ longRows.delete(m);
3574
+ continue;
3575
+ }
3576
+ const want = rowsToDraw(m);
3577
+ if (want.first !== m.first || want.end !== m.end)
3578
+ drawRows(m);
3579
+ }
3580
+ });
3581
+ }
3582
+ /** Printing draws every row, and the screen goes back to drawing some after. */
3583
+ function onPrint(on) {
3584
+ printing = on;
3585
+ for (const m of longRows) {
3586
+ if (!m.box.isConnected)
3587
+ continue;
3588
+ // all the rows cover the screen, but are not to be kept
3589
+ if (!on)
3590
+ m.end = m.first;
3591
+ drawRows(m);
3592
+ }
2809
3593
  }
2810
3594
  /** Headers in the active language; in a sortable table each is a button, with an arrow on the sorted one. */
2811
3595
  function syncHead(f, table, cols) {
@@ -3472,6 +4256,7 @@ native('show-toast', '["Shows a short message at the edge of the screen." messag
3472
4256
  if (kind === 'danger')
3473
4257
  t.setAttribute('role', 'alert');
3474
4258
  const message = text(f.args[0]);
4259
+ devLog.note('toast', kind !== null ? `${kind}: ${message}` : message);
3475
4260
  const box = toasts;
3476
4261
  const dismiss = () => {
3477
4262
  t.remove();
@@ -3594,6 +4379,8 @@ function sync(m) {
3594
4379
  return syncUpload(m, err);
3595
4380
  if (style === 'photo')
3596
4381
  return syncPhoto(m, err);
4382
+ if (style === 'widget')
4383
+ return syncWidget(m, err);
3597
4384
  if (style === 'lookup')
3598
4385
  return syncLookup(m, err);
3599
4386
  if (style === 'rich')
@@ -3693,6 +4480,9 @@ function sync(m) {
3693
4480
  case 'chart':
3694
4481
  syncChart(m);
3695
4482
  return;
4483
+ case 'orbit':
4484
+ syncOrbit(m);
4485
+ return;
3696
4486
  case 'icon':
3697
4487
  syncIcon(m);
3698
4488
  return;
@@ -3848,6 +4638,39 @@ function setExtra(e, cls) {
3848
4638
  e.classList.add(c);
3849
4639
  e.dataset['tb'] = cls.join(' ');
3850
4640
  }
4641
+ /**
4642
+ * Runs the reactions whose facets changed in this round, at once, so the repaint
4643
+ * that follows shows them: ui-react, given the faces on the page that have any.
4644
+ */
4645
+ function react() {
4646
+ for (const m of reactors)
4647
+ if (!m.el.isConnected && comingScreen?.contains(m.el) !== true)
4648
+ reactors.delete(m);
4649
+ if (reacting !== null || reactors.size === 0 || (dirty.length === 0 && !newReactor))
4650
+ return;
4651
+ newReactor = false;
4652
+ const faces = blockOf(K.Block, [...reactors].map(m => m.face));
4653
+ const ht = runNow(host.sch, { data: [{ t: K.Word, sym: intern('ui-react'), bind: host.rt.user }, faces] }, 0);
4654
+ const warn = (t) => {
4655
+ if (t.state !== 'done' || t.result.t !== K.Block)
4656
+ return;
4657
+ for (const c of t.result.s.data) {
4658
+ console.warn(`Trebol: ${text(c)}`);
4659
+ devLog.note('warning', text(c));
4660
+ }
4661
+ };
4662
+ if (ht.state === 'done')
4663
+ warn(ht);
4664
+ else if (ht.state !== 'failed') {
4665
+ reacting = ht;
4666
+ ht.watchers.push(t => {
4667
+ reacting = null;
4668
+ // what changed while it waited is checked at the end of this round
4669
+ newReactor = true;
4670
+ warn(t);
4671
+ });
4672
+ }
4673
+ }
3851
4674
  function syncDirty() {
3852
4675
  for (const ctx of dirty) {
3853
4676
  ctx.dirty = false;
@@ -3904,9 +4727,13 @@ function startHistory() {
3904
4727
  here = { depth: state.depth, top: state.top ?? state.depth };
3905
4728
  history.replaceState({ ...here }, '');
3906
4729
  }
4730
+ /** Where the page stood before the link last changed, so route-undo can return; set while it returns. */
4731
+ let before = { depth: 0, top: 0 };
4732
+ let undoing = null;
3907
4733
  /** The link changed: back or forward lands on an entry the page made; a link or a typed address makes a new one, a step ahead. */
3908
4734
  function landHistory() {
3909
4735
  const state = history.state;
4736
+ before = { ...here };
3910
4737
  if (typeof state?.depth === 'number')
3911
4738
  here = { depth: state.depth, top: here.top };
3912
4739
  else
@@ -3925,6 +4752,23 @@ native('set-route', '["Puts a screen and arguments in the address bar." route [b
3925
4752
  history.pushState({ ...here }, '', href);
3926
4753
  return value(f.args[0]);
3927
4754
  });
4755
+ // A screen that does not let the page leave puts its link back: back for a new entry,
4756
+ // the other way for back or forward. The link that comes back is not a change of screen.
4757
+ native('route-undo', '["Puts back the link the page had before the last change." ]', () => {
4758
+ const by = before.depth - here.depth;
4759
+ if (by === 0)
4760
+ return value(NONE);
4761
+ undoing = before;
4762
+ history.go(by);
4763
+ return value(NONE);
4764
+ });
4765
+ // While the screen on show has changes not saved, the browser asks before closing or
4766
+ // reloading the page, with its own words: no browser lets a page give its text.
4767
+ let unsaved = false;
4768
+ native('set-unsaved', '["Whether the browser asks before closing the page." on [logic!]]', (_t, f) => {
4769
+ unsaved = f.args[0].t === K.Logic && f.args[0].v;
4770
+ return value(f.args[0]);
4771
+ });
3928
4772
  native('route-steps', '["How many steps back and forward the history has." ]', () => value(blockOf(K.Block, [int(here.depth), int(here.top - here.depth)])));
3929
4773
  native('route-back', '["Goes one step back in the history." ]', () => {
3930
4774
  if (here.depth === 0)
@@ -4041,11 +4885,35 @@ native('apply-theme', '["Changes the look of the whole screen." spec [object!]]'
4041
4885
  });
4042
4886
  // --- boot --------------------------------------------------------------------------
4043
4887
  async function boot() {
4888
+ // a page of trebol build has the app's files inside, by their path from the page, and its own fonts
4889
+ const files = document.getElementById('trebol-files');
4890
+ if (files !== null) {
4891
+ for (const [path, src] of Object.entries(JSON.parse(files.textContent ?? '{}'))) {
4892
+ addBuiltIn(new URL(path, location.href).href, src);
4893
+ }
4894
+ }
4895
+ if (document.querySelector('style[data-tb-fonts]') === null) {
4896
+ const fonts = el('style');
4897
+ fonts.dataset['tbFonts'] = '';
4898
+ fonts.textContent = interCss(file => new URL(`fonts/${file}`, import.meta.url).href);
4899
+ document.head.append(fonts);
4900
+ }
4044
4901
  setTheme(DEFAULT_THEME);
4045
- host = startHost();
4046
- host.sch.afterPump = syncDirty;
4902
+ host = startHost({ onError: e => showError(report(e)) });
4903
+ host.sch.afterPump = () => {
4904
+ react();
4905
+ syncDirty();
4906
+ devLog.repainted();
4907
+ };
4047
4908
  document.addEventListener('keydown', onKeyDown, true);
4048
4909
  document.addEventListener('keydown', onReorderKey);
4910
+ // a scroll anywhere: the page, a scroll face, a dialog
4911
+ document.addEventListener('scroll', onRowsMoved, { capture: true, passive: true });
4912
+ addEventListener('resize', onRowsMoved);
4913
+ addEventListener('beforeunload', ev => { if (unsaved)
4914
+ ev.preventDefault(); });
4915
+ addEventListener('beforeprint', () => onPrint(true));
4916
+ addEventListener('afterprint', () => onPrint(false));
4049
4917
  document.addEventListener('pointerdown', onPointerDown);
4050
4918
  document.addEventListener('pointermove', onPointerMove, { passive: false });
4051
4919
  document.addEventListener('pointerup', () => endDrag(true));
@@ -4059,8 +4927,33 @@ async function boot() {
4059
4927
  document.addEventListener('touchmove', ev => { if (dragging?.on)
4060
4928
  ev.preventDefault(); }, { passive: false });
4061
4929
  document.addEventListener('keydown', onViewKey);
4930
+ const devMark = document.querySelector('meta[name="trebol-dev"]');
4931
+ if (devMark !== null) {
4932
+ startDevtools({
4933
+ host,
4934
+ root: devMark.getAttribute('content'),
4935
+ faceOf: e => {
4936
+ const m = byNode.get(e);
4937
+ return m !== undefined && m.el === e ? m.face : null;
4938
+ },
4939
+ faceAt: e => {
4940
+ const m = mountedAbove(e);
4941
+ return m === undefined ? null : { face: m.face, el: m.el };
4942
+ },
4943
+ nodeOf: face => {
4944
+ const e = byCtx.get(face.ctx)?.el;
4945
+ return e?.isConnected === true ? e : null;
4946
+ },
4947
+ });
4948
+ }
4062
4949
  startHistory();
4063
4950
  window.addEventListener('hashchange', () => {
4951
+ if (undoing !== null) {
4952
+ here = undoing;
4953
+ undoing = null;
4954
+ history.replaceState({ ...here }, '');
4955
+ return;
4956
+ }
4064
4957
  landHistory();
4065
4958
  if (screensFace !== null)
4066
4959
  void fire('ui-route', screensFace, routeBlock());
@@ -4069,12 +4962,12 @@ async function boot() {
4069
4962
  for (const s of Array.from(document.querySelectorAll('script[type="text/trebol"]'))) {
4070
4963
  const src = s.getAttribute('src');
4071
4964
  const url = src !== null ? new URL(src, location.href).href : location.href;
4072
- const code = src !== null ? await (await fetch(url)).text() : s.textContent ?? '';
4965
+ const code = src !== null ? builtInText(url) ?? await (await fetch(url)).text() : s.textContent ?? '';
4073
4966
  try {
4074
4967
  await runSource(host, code, url);
4075
4968
  }
4076
4969
  catch (e) {
4077
- console.error(e instanceof Error ? e.message : report(e));
4970
+ showError(e instanceof Error ? e.message : report(e));
4078
4971
  }
4079
4972
  }
4080
4973
  }