trebol 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/README.md +2 -0
  2. package/dist/cli.js +10040 -7519
  3. package/dist/lib/core/boot.js +10 -7
  4. package/dist/lib/core/eval.js +2 -2
  5. package/dist/lib/core/machine/checks.d.ts +1 -0
  6. package/dist/lib/core/machine/checks.js +250 -0
  7. package/dist/lib/core/machine/events.d.ts +1 -0
  8. package/dist/lib/core/machine/events.js +365 -0
  9. package/dist/lib/core/machine/running.d.ts +1 -0
  10. package/dist/lib/core/machine/running.js +180 -0
  11. package/dist/lib/core/machine/shared.d.ts +1 -0
  12. package/dist/lib/core/machine/shared.js +123 -0
  13. package/dist/lib/core/machine/snapshot.d.ts +1 -0
  14. package/dist/lib/core/machine/snapshot.js +244 -0
  15. package/dist/lib/core/machine/spec.d.ts +1 -0
  16. package/dist/lib/core/machine/spec.js +274 -0
  17. package/dist/lib/core/machine/words.d.ts +1 -0
  18. package/dist/lib/core/machine/words.js +98 -0
  19. package/dist/lib/core/machine.d.ts +1 -0
  20. package/dist/lib/core/machine.js +17 -0
  21. package/dist/lib/core/mezz.js +31 -0
  22. package/dist/lib/core/natives/control.js +1 -1
  23. package/dist/lib/core/natives/data.js +6 -1
  24. package/dist/lib/core/natives/series.js +49 -9
  25. package/dist/lib/core/natives/text.js +0 -1
  26. package/dist/lib/host/browser/calendar.d.ts +34 -0
  27. package/dist/lib/host/browser/calendar.js +268 -0
  28. package/dist/lib/host/browser/count.d.ts +15 -0
  29. package/dist/lib/host/browser/count.js +48 -0
  30. package/dist/lib/host/browser/dialogs.d.ts +39 -0
  31. package/dist/lib/host/browser/dialogs.js +443 -0
  32. package/dist/lib/host/browser/drag.d.ts +70 -0
  33. package/dist/lib/host/browser/drag.js +268 -0
  34. package/dist/lib/host/browser/drawings.d.ts +30 -0
  35. package/dist/lib/host/browser/drawings.js +176 -0
  36. package/dist/lib/host/browser/events.d.ts +16 -0
  37. package/dist/lib/host/browser/events.js +125 -0
  38. package/dist/lib/host/browser/faces.d.ts +35 -0
  39. package/dist/lib/host/browser/faces.js +131 -0
  40. package/dist/lib/host/browser/fields.d.ts +16 -0
  41. package/dist/lib/host/browser/fields.js +322 -0
  42. package/dist/lib/host/browser/keys.d.ts +29 -0
  43. package/dist/lib/host/browser/keys.js +151 -0
  44. package/dist/lib/host/browser/lookup.d.ts +25 -0
  45. package/dist/lib/host/browser/lookup.js +275 -0
  46. package/dist/lib/host/browser/menus.d.ts +20 -0
  47. package/dist/lib/host/browser/menus.js +149 -0
  48. package/dist/lib/host/browser/mount.d.ts +92 -0
  49. package/dist/lib/host/browser/mount.js +448 -0
  50. package/dist/lib/host/browser/orbits.d.ts +90 -0
  51. package/dist/lib/host/browser/orbits.js +379 -0
  52. package/dist/lib/host/browser/page.d.ts +13 -0
  53. package/dist/lib/host/browser/page.js +35 -0
  54. package/dist/lib/host/browser/richtext.d.ts +19 -0
  55. package/dist/lib/host/browser/richtext.js +379 -0
  56. package/dist/lib/host/browser/row-faces.d.ts +5 -0
  57. package/dist/lib/host/browser/row-faces.js +74 -0
  58. package/dist/lib/host/browser/screens.d.ts +37 -0
  59. package/dist/lib/host/browser/screens.js +140 -0
  60. package/dist/lib/host/browser/swipe.d.ts +31 -0
  61. package/dist/lib/host/browser/swipe.js +178 -0
  62. package/dist/lib/host/browser/sync.d.ts +24 -0
  63. package/dist/lib/host/browser/sync.js +450 -0
  64. package/dist/lib/host/browser/tables.d.ts +65 -0
  65. package/dist/lib/host/browser/tables.js +505 -0
  66. package/dist/lib/host/browser/times.d.ts +14 -0
  67. package/dist/lib/host/browser/times.js +114 -0
  68. package/dist/lib/host/browser/toolbars.d.ts +17 -0
  69. package/dist/lib/host/browser/toolbars.js +129 -0
  70. package/dist/lib/host/browser/trees.d.ts +20 -0
  71. package/dist/lib/host/browser/trees.js +235 -0
  72. package/dist/lib/host/browser/uploads.d.ts +29 -0
  73. package/dist/lib/host/browser/uploads.js +370 -0
  74. package/dist/lib/host/browser/widget.d.ts +13 -0
  75. package/dist/lib/host/browser/widget.js +105 -0
  76. package/dist/lib/host/browser.d.ts +25 -0
  77. package/dist/lib/host/browser.js +84 -4812
  78. package/dist/lib/host/devtools/console.d.ts +9 -0
  79. package/dist/lib/host/devtools/console.js +104 -0
  80. package/dist/lib/host/devtools/faces.d.ts +25 -0
  81. package/dist/lib/host/devtools/faces.js +169 -0
  82. package/dist/lib/host/devtools/log.d.ts +3 -0
  83. package/dist/lib/host/devtools/log.js +32 -0
  84. package/dist/lib/host/devtools/machines.d.ts +34 -0
  85. package/dist/lib/host/devtools/machines.js +212 -0
  86. package/dist/lib/host/devtools/read.d.ts +13 -0
  87. package/dist/lib/host/devtools/read.js +52 -0
  88. package/dist/lib/host/devtools/state.d.ts +90 -0
  89. package/dist/lib/host/devtools/state.js +123 -0
  90. package/dist/lib/host/devtools.d.ts +15 -19
  91. package/dist/lib/host/devtools.js +39 -427
  92. package/dist/lib/host/fonts.js +4 -3
  93. package/dist/lib/host/icons.js +4 -0
  94. package/dist/lib/host/index.d.ts +3 -1
  95. package/dist/lib/host/index.js +107 -4
  96. package/dist/lib/host/locale.d.ts +18 -0
  97. package/dist/lib/host/locale.js +75 -5
  98. package/dist/lib/host/markdown.d.ts +4 -0
  99. package/dist/lib/host/markdown.js +8 -0
  100. package/dist/lib/host/modules.js +118 -19
  101. package/dist/lib/host/motion.d.ts +32 -0
  102. package/dist/lib/host/motion.js +190 -0
  103. package/dist/lib/host/net.js +5 -2
  104. package/dist/lib/host/palette.d.ts +17 -0
  105. package/dist/lib/host/palette.js +131 -0
  106. package/dist/lib/host/scheduler.d.ts +2 -0
  107. package/dist/lib/host/scheduler.js +4 -0
  108. package/dist/lib/host/share.d.ts +31 -0
  109. package/dist/lib/host/share.js +134 -0
  110. package/dist/lib/host/theme/classic.d.ts +1 -0
  111. package/dist/lib/host/theme/classic.js +120 -0
  112. package/dist/lib/host/theme/cupertino.d.ts +1 -0
  113. package/dist/lib/host/theme/cupertino.js +65 -0
  114. package/dist/lib/host/theme/data.d.ts +1 -0
  115. package/dist/lib/host/theme/data.js +109 -0
  116. package/dist/lib/host/theme/devtools.d.ts +1 -0
  117. package/dist/lib/host/theme/devtools.js +166 -0
  118. package/dist/lib/host/theme/dialogs.d.ts +1 -0
  119. package/dist/lib/host/theme/dialogs.js +63 -0
  120. package/dist/lib/host/theme/fluent.d.ts +1 -0
  121. package/dist/lib/host/theme/fluent.js +64 -0
  122. package/dist/lib/host/theme/forms.d.ts +1 -0
  123. package/dist/lib/host/theme/forms.js +239 -0
  124. package/dist/lib/host/theme/fusion.d.ts +1 -0
  125. package/dist/lib/host/theme/fusion.js +66 -0
  126. package/dist/lib/host/theme/layout.d.ts +1 -0
  127. package/dist/lib/host/theme/layout.js +166 -0
  128. package/dist/lib/host/theme/media.d.ts +1 -0
  129. package/dist/lib/host/theme/media.js +106 -0
  130. package/dist/lib/host/theme/navigation.d.ts +1 -0
  131. package/dist/lib/host/theme/navigation.js +36 -0
  132. package/dist/lib/host/theme/panes.d.ts +1 -0
  133. package/dist/lib/host/theme/panes.js +99 -0
  134. package/dist/lib/host/theme/popups.d.ts +1 -0
  135. package/dist/lib/host/theme/popups.js +149 -0
  136. package/dist/lib/host/theme/responsive.d.ts +1 -0
  137. package/dist/lib/host/theme/responsive.js +103 -0
  138. package/dist/lib/host/theme/toasts.d.ts +1 -0
  139. package/dist/lib/host/theme/toasts.js +62 -0
  140. package/dist/lib/host/theme.js +19 -1384
  141. package/dist/lib/ui/dialect/events.trb +276 -0
  142. package/dist/lib/ui/dialect/faces.trb +135 -0
  143. package/dist/lib/ui/dialect/layout.trb +283 -0
  144. package/dist/lib/ui/dialect/palette.trb +87 -0
  145. package/dist/lib/ui/dialect/problems.trb +174 -0
  146. package/dist/lib/ui/dialect/reactions.trb +198 -0
  147. package/dist/lib/ui/dialect/rows.trb +208 -0
  148. package/dist/lib/ui/dialect/screens.trb +293 -0
  149. package/dist/lib/ui/dialect/steps.trb +203 -0
  150. package/dist/lib/ui/dialect/validation.trb +137 -0
  151. package/dist/lib/ui/dialect/view.trb +110 -0
  152. package/dist/lib/ui/dialect/walking.trb +98 -0
  153. package/dist/lib/ui/dialect/words.trb +70 -0
  154. package/dist/lib/ui/i18n.trb +17 -0
  155. package/dist/lib/ui/test.trb +3 -556
  156. package/dist/lib/ui/testing/actions.trb +421 -0
  157. package/dist/lib/ui/testing/faces.trb +148 -0
  158. package/dist/lib/ui/testing/server.trb +73 -0
  159. package/dist/lib/ui/ui.trb +25 -1675
  160. package/dist/trebol.js +4463 -1891
  161. package/package.json +1 -1
  162. package/src/core/boot.ts +9 -6
  163. package/src/core/eval.ts +2 -2
  164. package/src/core/machine/checks.ts +251 -0
  165. package/src/core/machine/events.ts +366 -0
  166. package/src/core/machine/running.ts +181 -0
  167. package/src/core/machine/shared.ts +124 -0
  168. package/src/core/machine/snapshot.ts +245 -0
  169. package/src/core/machine/spec.ts +275 -0
  170. package/src/core/machine/words.ts +99 -0
  171. package/src/core/machine.ts +20 -0
  172. package/src/core/mezz.ts +31 -0
  173. package/src/core/natives/control.ts +1 -1
  174. package/src/core/natives/data.ts +6 -1
  175. package/src/core/natives/parse.ts +1 -1
  176. package/src/core/natives/series.ts +47 -11
  177. package/src/core/natives/text.ts +0 -1
  178. package/src/host/browser/calendar.ts +264 -0
  179. package/src/host/browser/count.ts +48 -0
  180. package/src/host/browser/dialogs.ts +439 -0
  181. package/src/host/browser/drag.ts +278 -0
  182. package/src/host/browser/drawings.ts +178 -0
  183. package/src/host/browser/events.ts +117 -0
  184. package/src/host/browser/faces.ts +143 -0
  185. package/src/host/browser/fields.ts +315 -0
  186. package/src/host/browser/keys.ts +145 -0
  187. package/src/host/browser/lookup.ts +262 -0
  188. package/src/host/browser/menus.ts +146 -0
  189. package/src/host/browser/mount.ts +420 -0
  190. package/src/host/browser/orbits.ts +418 -0
  191. package/src/host/browser/page.ts +43 -0
  192. package/src/host/browser/richtext.ts +346 -0
  193. package/src/host/browser/row-faces.ts +75 -0
  194. package/src/host/browser/screens.ts +142 -0
  195. package/src/host/browser/swipe.ts +168 -0
  196. package/src/host/browser/sync.ts +354 -0
  197. package/src/host/browser/tables.ts +461 -0
  198. package/src/host/browser/times.ts +115 -0
  199. package/src/host/browser/toolbars.ts +126 -0
  200. package/src/host/browser/trees.ts +205 -0
  201. package/src/host/browser/uploads.ts +367 -0
  202. package/src/host/browser/widget.ts +103 -0
  203. package/src/host/browser.ts +82 -4612
  204. package/src/host/devtools/console.ts +102 -0
  205. package/src/host/devtools/faces.ts +160 -0
  206. package/src/host/devtools/log.ts +34 -0
  207. package/src/host/devtools/machines.ts +208 -0
  208. package/src/host/devtools/read.ts +58 -0
  209. package/src/host/devtools/state.ts +148 -0
  210. package/src/host/devtools.ts +39 -442
  211. package/src/host/fonts.ts +4 -3
  212. package/src/host/icons.ts +4 -0
  213. package/src/host/index.ts +107 -4
  214. package/src/host/locale.ts +71 -5
  215. package/src/host/markdown.ts +9 -0
  216. package/src/host/modules.ts +117 -21
  217. package/src/host/motion.ts +204 -0
  218. package/src/host/net.ts +4 -2
  219. package/src/host/palette.ts +139 -0
  220. package/src/host/scheduler.ts +5 -0
  221. package/src/host/share.ts +168 -0
  222. package/src/host/theme/classic.ts +121 -0
  223. package/src/host/theme/cupertino.ts +66 -0
  224. package/src/host/theme/data.ts +110 -0
  225. package/src/host/theme/devtools.ts +167 -0
  226. package/src/host/theme/dialogs.ts +64 -0
  227. package/src/host/theme/fluent.ts +65 -0
  228. package/src/host/theme/forms.ts +240 -0
  229. package/src/host/theme/fusion.ts +67 -0
  230. package/src/host/theme/layout.ts +167 -0
  231. package/src/host/theme/media.ts +107 -0
  232. package/src/host/theme/navigation.ts +37 -0
  233. package/src/host/theme/panes.ts +100 -0
  234. package/src/host/theme/popups.ts +150 -0
  235. package/src/host/theme/responsive.ts +104 -0
  236. package/src/host/theme/toasts.ts +63 -0
  237. package/src/host/theme.ts +19 -1384
  238. package/src/ui/dialect/events.trb +276 -0
  239. package/src/ui/dialect/faces.trb +135 -0
  240. package/src/ui/dialect/layout.trb +283 -0
  241. package/src/ui/dialect/palette.trb +87 -0
  242. package/src/ui/dialect/problems.trb +174 -0
  243. package/src/ui/dialect/reactions.trb +198 -0
  244. package/src/ui/dialect/rows.trb +208 -0
  245. package/src/ui/dialect/screens.trb +293 -0
  246. package/src/ui/dialect/steps.trb +203 -0
  247. package/src/ui/dialect/validation.trb +137 -0
  248. package/src/ui/dialect/view.trb +110 -0
  249. package/src/ui/dialect/walking.trb +98 -0
  250. package/src/ui/dialect/words.trb +70 -0
  251. package/src/ui/i18n.trb +17 -0
  252. package/src/ui/test.trb +3 -556
  253. package/src/ui/testing/actions.trb +421 -0
  254. package/src/ui/testing/faces.trb +148 -0
  255. package/src/ui/testing/server.trb +73 -0
  256. package/src/ui/ui.trb +25 -1675
@@ -14,4598 +14,67 @@
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
-
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, toJson, parseJson,
20
- type Cell, type MapCell, type ObjectCell, type BlockCell, type WordCell, type StringCell, type Ctx, type Sym,
21
- } from '../core/index.ts';
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, runNow, taskResult, handleOf, type HostTask } from './scheduler.ts';
24
- import { themeCss, DEFAULT_THEME, LOOKS, THEME_WORDS, type ThemeParams } from './theme.ts';
25
- import { iconNode } from './icons.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';
29
- import { fileHandle } from './net.ts';
30
- import { drawSvg, type El } from './draw.ts';
31
- import { rowField, groupRow, sortGroups, rowWindow, DRAW_ALL_UP_TO } from './rows.ts';
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';
36
-
37
- // --- reading faces -----------------------------------------------------------------
38
-
39
- function get(face: ObjectCell, name: string): Cell {
40
- const i = ctxFind(face.ctx, intern(name));
41
- return i < 0 ? NONE : face.ctx.vals[i]!;
42
- }
43
-
44
- function str(face: ObjectCell, name: string): string | null {
45
- const v = get(face, name);
46
- if (v.t === K.None) return null;
47
- // a text per language, or a word of the dictionary: in the active language
48
- if (v.t === K.Map || ((name === 'text' || name === 'hint') && v.t === K.Word)) return translate(v, host.rt);
49
- return form(v);
50
- }
51
-
52
- /** What a choice or radio option is worth: itself, or the `value` of a map #(value: .. text: ..). */
53
- function optionValue(o: Cell): string {
54
- const v = o.t === K.Map ? mapAt(o as MapCell, 'value') : null;
55
- return form(v ?? o);
56
- }
57
-
58
- /** What a choice or radio option shows, in the active language. */
59
- function optionText(o: Cell): string {
60
- const t = o.t === K.Map ? mapAt(o as MapCell, 'text') : null;
61
- return t !== null ? translate(t, host.rt) : optionValue(o);
62
- }
63
-
64
- /** A group of options: its title and its options. */
65
- interface OptionGroup { title: Cell; options: Cell[] }
66
-
67
- /** The options of a choice or radio as written: options and groups, a title followed by a block. */
68
- function entriesOf(face: ObjectCell): (Cell | OptionGroup)[] {
69
- const opts = get(face, 'options');
70
- if (opts.t !== K.Block) return [];
71
- const data = opts.s.data.slice(opts.i);
72
- const out: (Cell | OptionGroup)[] = [];
73
- for (let i = 0; i < data.length; i++) {
74
- const next = data[i + 1];
75
- if (next !== undefined && next.t === K.Block && data[i]!.t !== K.Block) {
76
- out.push({ title: data[i]!, options: next.s.data.slice(next.i) });
77
- i++;
78
- } else if (data[i]!.t !== K.Block) out.push(data[i]!);
79
- }
80
- return out;
81
- }
82
-
83
- function isGroup(e: Cell | OptionGroup): e is OptionGroup {
84
- return 'options' in e;
85
- }
86
-
87
- /** The options of a choice or radio, those of its groups included, in order. */
88
- function optionsOf(face: ObjectCell): Cell[] {
89
- return entriesOf(face).flatMap(e => isGroup(e) ? e.options : [e]);
90
- }
91
-
92
- /** What tells apart two sets of options: their values and where each group starts. */
93
- function optionsKey(face: ObjectCell): string {
94
- return entriesOf(face).map(e => isGroup(e) ? `\u0001${e.options.map(optionValue).join('\0')}` : optionValue(e)).join('\0');
95
- }
96
-
97
- /** Writes the options of a select: an empty one first, then those of the face, each group in an optgroup. */
98
- function fillSelect(sel: HTMLSelectElement, face: ObjectCell): void {
99
- const first = el('option');
100
- first.value = '';
101
- sel.replaceChildren(first);
102
- const option = (o: Cell): HTMLOptionElement => {
103
- const opt = el('option');
104
- opt.value = optionValue(o);
105
- opt.textContent = optionText(o);
106
- return opt;
107
- };
108
- for (const e of entriesOf(face)) {
109
- if (isGroup(e)) {
110
- const group = el('optgroup');
111
- group.label = translate(e.title, host.rt);
112
- group.append(...e.options.map(option));
113
- sel.append(group);
114
- } else sel.append(option(e));
115
- }
116
- sel.dataset.options = optionsKey(face);
117
- }
118
-
119
- /** One of Trebol's own texts (`i18n/ui`) in the active language. */
120
- function own(key: string, ...args: string[]): string {
121
- return uiText(host.rt, key, ...args);
122
- }
123
-
124
- /** Gives a node built once one of Trebol's own texts (its text or an attribute); `repaint` keeps it in the active language. */
125
- function keepOwn(node: HTMLElement, key: string, attr?: string): void {
126
- node.dataset.tbOwn = attr === undefined ? key : `${attr} ${key}`;
127
- showOwn(node);
128
- }
129
-
130
- function showOwn(node: HTMLElement): void {
131
- const [a, k] = node.dataset.tbOwn!.split(' ');
132
- if (k === undefined) node.textContent = own(a!);
133
- else node.setAttribute(a!, own(k));
134
- }
135
-
136
- /** A value as it shows on screen: dates, numbers and money in the active language. */
137
- function display(v: Cell): string {
138
- return LOCAL_KINDS.has(v.t) ? shown(v, activeLanguage(host.rt)) : form(v);
139
- }
140
-
141
- function flag(face: ObjectCell, name: string): boolean {
142
- const v = get(face, name);
143
- return !(v.t === K.None || (v.t === K.Logic && !v.v));
144
- }
145
-
146
- function word(face: ObjectCell, name: string): string | null {
147
- const v = get(face, name);
148
- return v.t === K.Word || v.t === K.LitWord ? spell((v as WordCell).sym).toLowerCase() : null;
149
- }
150
-
151
- function children(face: ObjectCell): ObjectCell[] {
152
- const c = get(face, 'pane');
153
- if (c.t !== K.Block) return [];
154
- return c.s.data.slice(c.i).filter(x => x.t === K.Object) as ObjectCell[];
155
- }
156
-
157
- /** The name of a face's icon (`#search` -> "search"). */
158
- function iconName(face: ObjectCell): string | null {
159
- const v = get(face, 'icon');
160
- return v.t === K.Issue ? spell((v as WordCell).sym).toLowerCase() : null;
161
- }
162
-
163
- function icon(name: string, label: string | null = null): SVGSVGElement | null {
164
- const svg = iconNode(name, label);
165
- if (svg === null) console.warn(`Trebol: unknown icon #${name}`);
166
- return svg;
167
- }
168
-
169
- function hasRule(face: ObjectCell, rule: string): boolean {
170
- const rules = get(face, 'rules');
171
- if (rules.t !== K.Block) return false;
172
- return rules.s.data.some(r => r.t === K.Block && r.s.data[0]?.t === K.Word && spell((r.s.data[0] as WordCell).sym) === rule);
173
- }
174
-
175
- // --- mounting ----------------------------------------------------------------------
176
-
177
- /** What the host keeps for each mounted face. */
178
- interface Mounted {
179
- face: ObjectCell;
180
- el: HTMLElement;
181
- input: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null;
182
- label: HTMLElement | null;
183
- error: HTMLElement | null;
184
- kids: unknown;
185
- /** Where children or rows go, when it is not `el`. */
186
- box: HTMLElement | null;
187
- /** Rows of a table or list, by key. */
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;
195
- /** Shown instead of the rows when there are none. */
196
- empty: HTMLElement | null;
197
- /** The tab button of a tab face. */
198
- button: HTMLButtonElement | null;
199
- /** The options of a radio. */
200
- radios: HTMLInputElement[] | null;
201
- /** The keys of the open nodes of a tree. */
202
- open: Set<string> | null;
203
- /** Rows: what the rows were last checked against. Rich text: the Markdown on screen. */
204
- shown: unknown;
205
- /** An input: what the user typed still on its way to the face. */
206
- typing: number;
207
- /** An input: the value the user's typing gave the face; code that sets another one is shown even with the focus. */
208
- typed: Cell | null;
209
- }
210
-
211
- let host: Host;
212
- /** Mounted faces by their node and by their input. */
213
- const byNode = new WeakMap<Element, Mounted>();
214
- /** The row cell each table row or list item shows. */
215
- const rowOf = new WeakMap<Element, Cell>();
216
- /** Mounted faces by context; a face rebuilt in a new container replaces its entry. */
217
- const byCtx = new WeakMap<Ctx, Mounted>();
218
- /** Contexts of mounted faces written since the last repaint (filled by the core). */
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;
225
- let nextId = 1;
226
-
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]);
228
-
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
- */
253
- function fire(fn: string, face: ObjectCell, ...args: Cell[]): Promise<Cell> {
254
- // a word, path or paren given as data (a dropped `date`) is quoted, so it is passed, not evaluated
255
- const quote: Cell = { t: K.Word, sym: intern('quote'), bind: host.rt.lib };
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])];
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);
299
- }
300
-
301
- function el<T extends keyof HTMLElementTagNameMap>(tag: T, cls?: string): HTMLElementTagNameMap[T] {
302
- const e = document.createElement(tag);
303
- if (cls) e.className = cls;
304
- return e;
305
- }
306
-
307
- const INPUTS = new Set(['field', 'password', 'number', 'money', 'date', 'area', 'choice']);
308
-
309
- function build(face: ObjectCell): HTMLElement {
310
- const style = word(face, 'style') ?? 'face';
311
- const m: Mounted = {
312
- face, el: null!, input: null, label: null, error: null, kids: get(face, 'pane'),
313
- box: null, rows: null, empty: null, button: null, radios: null, open: null, shown: undefined,
314
- typing: 0, typed: null, items: [], first: 0, end: 0, rowHeight: 0,
315
- };
316
- let node: HTMLElement;
317
- if (INPUTS.has(style)) {
318
- node = buildInput(face, style, m);
319
- } else if (style === 'check' || style === 'toggle') {
320
- node = buildCheck(face, m, style === 'toggle');
321
- } else if (style === 'radio') {
322
- node = buildRadio(face, m);
323
- } else if (style === 'upload') {
324
- node = buildUpload(face, m);
325
- } else if (style === 'photo') {
326
- node = buildPhoto(face, m);
327
- } else if (style === 'widget') {
328
- node = buildWidget(face, m);
329
- } else if (style === 'lookup') {
330
- node = buildLookup(face, m);
331
- } else if (style === 'rich') {
332
- node = buildRich(face, m);
333
- } else {
334
- switch (style) {
335
- case 'view': node = el('main', 'tb-view'); break;
336
- case 'column': node = el('div', 'tb-column'); break;
337
- case 'row': node = el('div', 'tb-row'); break;
338
- case 'toolbar': node = buildToolbar(); break;
339
- case 'breadcrumb': node = buildBreadcrumb(m); break;
340
- case 'rows': node = buildRowsField(m); break;
341
- case 'entry': {
342
- node = el('div', 'tb-entry');
343
- node.setAttribute('role', 'group');
344
- break;
345
- }
346
- case 'grid': node = el('div', 'tb-grid'); break;
347
- case 'desktop': node = el('div', 'tb-desktop'); break;
348
- case 'scroll': {
349
- // focusable, so keyboard users can scroll it too
350
- node = el('div', 'tb-scroll');
351
- node.tabIndex = 0;
352
- node.setAttribute('role', 'region');
353
- break;
354
- }
355
- case 'panel': node = el('section', 'tb-panel'); break;
356
- case 'form': {
357
- const f = el('form', 'tb-form');
358
- f.noValidate = true;
359
- // Enter in a field clicks the submit button, which handles it
360
- f.addEventListener('submit', ev => ev.preventDefault());
361
- node = f;
362
- break;
363
- }
364
- case 'title': node = el('h1', 'tb-title'); break;
365
- case 'heading': node = el('h2', 'tb-heading'); break;
366
- case 'text': node = el('p', 'tb-text'); break;
367
- case 'divider': node = el('hr', 'tb-divider'); break;
368
- case 'link': {
369
- const a = el('a', 'tb-link');
370
- a.href = screenHref(get(face, 'value')) ?? str(face, 'value') ?? '#';
371
- withIcon(a, face, m);
372
- a.addEventListener('click', ev => {
373
- if (get(face, 'action').t === K.Block) {
374
- ev.preventDefault();
375
- void fire('ui-click', face);
376
- }
377
- });
378
- node = a;
379
- break;
380
- }
381
- case 'button': {
382
- const b = el('button', 'tb-button');
383
- const submit = flag(face, 'submit');
384
- b.type = submit ? 'submit' : 'button';
385
- b.addEventListener('click', ev => {
386
- if (!submit) return void fire('ui-click', face);
387
- ev.preventDefault();
388
- clickSubmit(face, b.closest<HTMLElement>('form, .tb-view') ?? document.body);
389
- });
390
- withIcon(b, face, m);
391
- node = b;
392
- break;
393
- }
394
- case 'tile': {
395
- const b = el('button', flag(face, 'linked') ? 'tb-tile tb-tile-linked' : 'tb-tile');
396
- b.type = 'button';
397
- b.addEventListener('click', () => void fire('ui-click', face));
398
- withIcon(b, face, m);
399
- node = b;
400
- break;
401
- }
402
- case 'progress': node = buildProgress(m); break;
403
- case 'image': node = el('img', 'tb-image'); break;
404
- case 'video': case 'audio': {
405
- const media = el(style, `tb-${style}`) as HTMLMediaElement;
406
- media.controls = true;
407
- media.preload = 'metadata';
408
- if (media instanceof HTMLVideoElement) media.playsInline = true;
409
- node = media;
410
- break;
411
- }
412
- case 'backdrop': {
413
- // decoration behind its container: screen readers skip it
414
- node = el('div', 'tb-backdrop');
415
- node.setAttribute('aria-hidden', 'true');
416
- break;
417
- }
418
- case 'canvas': node = buildCanvas(m); break;
419
- case 'chart': node = buildChart(m); break;
420
- case 'orbit': node = buildOrbit(m); break;
421
- case 'icon': node = el('span', 'tb-icon-face'); break;
422
- case 'table': case 'list': node = buildRows(face, style, m); break;
423
- case 'tree': node = buildTree(face, m); break;
424
- case 'dialog': node = buildDialog(face, m); break;
425
- case 'tabs': node = buildTabs(face, m); break;
426
- case 'split': node = buildSplit(face, m); break;
427
- case 'screens': {
428
- node = el('div', 'tb-screens');
429
- screensFace = face;
430
- break;
431
- }
432
- case 'screen': {
433
- node = el('section', 'tb-screen');
434
- const t = str(face, 'text');
435
- if (t !== null) {
436
- node.setAttribute('aria-label', t);
437
- document.title = t;
438
- titleFace = face;
439
- }
440
- break;
441
- }
442
- case 'tab': {
443
- node = el('div', 'tb-tab-panel');
444
- node.setAttribute('role', 'tabpanel');
445
- break;
446
- }
447
- default: node = el('div');
448
- }
449
- if (style === 'screens') placeScreen(m, node);
450
- else if (children(face).length > 0 && style !== 'tabs' && style !== 'split') appendChildren(m.box ?? node, face, style);
451
- }
452
- m.el = node;
453
- byNode.set(node, m);
454
- if (m.input !== null) byNode.set(m.input, m);
455
- byCtx.set(face.ctx, m);
456
- face.ctx.watch = dirty;
457
- if (get(face, 'reactions').t === K.Block) {
458
- reactors.add(m);
459
- newReactor = true;
460
- }
461
- listen(m, style);
462
- sync(m);
463
- return node;
464
- }
465
-
466
- // --- general events ------------------------------------------------------------------
467
-
468
- /** Runs a face's on-xxx handler; `words` are the event's own [word: value ...]. */
469
- function fireEvent(face: ObjectCell, name: string, words: [string, Cell][] = []): void {
470
- const extra = words.flatMap(([w, v]) => [wordOf(K.SetWord, w), v]);
471
- void fire('ui-event', face, wordOf(K.LitWord, name), blockOf(K.Block, extra));
472
- }
473
-
474
- /** Keydown events some face's on-key already saw; the view gets the rest. */
475
- const seenKeys = new WeakSet<Event>();
476
- /** The view with an on-key handler, if any. */
477
- let viewKeys: ObjectCell | null = null;
478
- /** Mounted buttons and links with a shortcut. */
479
- const shortcuts = new Set<Mounted>();
480
-
481
- function listen(m: Mounted, style: string): void {
482
- const f = m.face;
483
- const node = m.el;
484
- const left = (ev: FocusEvent): boolean => !node.contains(ev.relatedTarget as Node | null);
485
- if (handlerFor(f, 'on-focus')) node.addEventListener('focusin', ev => { if (left(ev)) fireEvent(f, 'on-focus'); });
486
- if (handlerFor(f, 'on-unfocus')) node.addEventListener('focusout', ev => { if (left(ev)) fireEvent(f, 'on-unfocus'); });
487
- if (handlerFor(f, 'on-over')) {
488
- // as in Red, event/away? is true when the pointer leaves
489
- node.addEventListener('pointerenter', () => fireEvent(f, 'on-over', [['away?', FALSE]]));
490
- node.addEventListener('pointerleave', () => fireEvent(f, 'on-over', [['away?', TRUE]]));
491
- }
492
- if (handlerFor(f, 'on-dbl-click')) node.addEventListener('dblclick', () => fireEvent(f, 'on-dbl-click'));
493
- if (handlerFor(f, 'on-end')) node.addEventListener('ended', () => fireEvent(f, 'on-end'));
494
- if (handlerFor(f, 'on-key')) {
495
- if (style === 'view') viewKeys = f;
496
- else node.addEventListener('keydown', ev => {
497
- if (seenKeys.has(ev) || keyCell(ev) === null) return;
498
- seenKeys.add(ev);
499
- fireEvent(f, 'on-key', keyWords(ev));
500
- });
501
- }
502
- if (str(f, 'shortcut') !== null) shortcuts.add(m);
503
- if (flag(f, 'drop')) dropZones.add(m);
504
- const menu = get(f, 'menu');
505
- // a button or link without an action opens its menu; anything else has it as its context menu
506
- if (menu.t === K.Block && (style === 'button' || style === 'link') && get(f, 'action').t !== K.Block) {
507
- node.setAttribute('aria-haspopup', 'menu');
508
- node.setAttribute('aria-expanded', 'false');
509
- // a chevron after the text (or alone after the icon) says it opens a menu; it turns up while open
510
- if (m.label === null) {
511
- m.label = el('span');
512
- node.prepend(m.label);
513
- }
514
- const chevron = icon('chevron-down');
515
- if (chevron !== null) {
516
- chevron.classList.add('tb-menu-chevron');
517
- node.append(chevron);
518
- }
519
- node.addEventListener('click', ev => {
520
- ev.preventDefault();
521
- const r = node.getBoundingClientRect();
522
- openMenu(trebolEntries(f, menu as BlockCell, NONE), r.left, r.bottom + 4, node);
523
- });
524
- } else if (menu.t === K.Block || flag(f, 'drag')) {
525
- node.addEventListener('contextmenu', ev => {
526
- const target = ev.target as Element;
527
- const data = style === 'table' || style === 'list' || style === 'tree';
528
- const item = data ? target.closest(style === 'tree' ? '[role="treeitem"]' : 'tr, li') : null;
529
- if (item === null && data && menu.t !== K.Block) return;
530
- const row = item !== null ? rowOf.get(item) ?? NONE : NONE;
531
- const entries = menu.t === K.Block ? trebolEntries(f, menu as BlockCell, row) : [];
532
- // faces you can drag can also be moved to a drop zone from the menu, without a mouse
533
- if (flag(f, 'drag')) {
534
- const zones = moveTargets(f, item !== null ? row : get(f, 'value'));
535
- if (zones.length > 0) {
536
- if (entries.length > 0) entries.push({ text: '', divider: true });
537
- entries.push({ text: own('move-to'), sub: zones });
538
- }
539
- }
540
- if (entries.length === 0) return;
541
- ev.preventDefault();
542
- ev.stopPropagation();
543
- // from the keyboard (Menu key, Shift+F10) there is no pointer: open by the focused element
544
- let { clientX: x, clientY: y } = ev;
545
- if (x === 0 && y === 0) {
546
- const r = (item ?? (document.activeElement && node.contains(document.activeElement) ? document.activeElement : node)).getBoundingClientRect();
547
- x = r.left + 8;
548
- y = r.top + Math.min(r.height, 40);
549
- }
550
- openMenu(entries, x, y, (item as HTMLElement | null) ?? (target as HTMLElement));
551
- });
552
- }
553
- }
554
-
555
- // --- drag and drop -----------------------------------------------------------------
556
- //
557
- // Pointer events rather than HTML drag and drop, so it also works with touch
558
- // (after a long press) and shows the theme's own indicator.
559
-
560
- /** Mounted faces that accept drops. */
561
- const dropZones = new Set<Mounted>();
562
-
563
- /** What is being dragged: a face, or a row of a table, list or tree. */
564
- interface Source {
565
- face: ObjectCell;
566
- el: HTMLElement;
567
- payload: Cell;
568
- /** The container it can be reordered in, and its position there (0-based). */
569
- within: Mounted | null;
570
- index: number;
571
- /** The element holding a row and its siblings (a tree has one per level). */
572
- group: HTMLElement | null;
573
- }
574
-
575
- /**
576
- * Where a drag would land. In a tree, `group` holds the siblings it goes
577
- * between, `parent` is their node (none at the root) and `into` the row of a
578
- * folder it goes into, at the end.
579
- */
580
- interface Target { m: Mounted; index: number; reorder: boolean; group?: HTMLElement; parent?: Cell; into?: HTMLElement }
581
-
582
- const isData = (m: Mounted): boolean => m.rows !== null;
583
-
584
- /** The elements a drop target places things between: rows, or child faces. */
585
- function slots(m: Mounted): HTMLElement[] {
586
- if (isData(m)) return Array.from(m.box!.children) as HTMLElement[];
587
- return children(m.face).map(c => byCtx.get(c.ctx)?.el).filter((e): e is HTMLElement => e !== undefined && e.isConnected);
588
- }
589
-
590
- function mountedAbove(e: Element | null): Mounted | undefined {
591
- for (let x = e; x !== null; x = x.parentElement) {
592
- const m = byNode.get(x);
593
- if (m !== undefined && m.el === x) return m;
594
- }
595
- return undefined;
596
- }
597
-
598
- /** The drag source at an element: a draggable face, a row, or a child of a reorderable container. */
599
- function sourceAt(start: Element): Source | null {
600
- if (start.closest('input, textarea, select, [contenteditable], .tb-split-handle, .tb-menu') !== null) return null;
601
- for (let e: Element | null = start; e !== null; e = e.parentElement) {
602
- const row = rowOf.get(e);
603
- if (row !== undefined) {
604
- const m = mountedAbove(e)!;
605
- // rows the host sorted are not in the order of data, so they cannot be moved
606
- const reorder = flag(m.face, 'reorder') && hostSorted(m.face) === null;
607
- if (!flag(m.face, 'drag') && !reorder) return null;
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
- }
614
- const index = Array.prototype.indexOf.call(group.children, e);
615
- return { face: m.face, el: e as HTMLElement, payload: row, within: reorder ? m : null, index, group };
616
- }
617
- const m = byNode.get(e);
618
- if (m === undefined || m.el !== e) continue;
619
- const parent = mountedAbove(e.parentElement);
620
- const reorder = parent !== undefined && !isData(parent) && flag(parent.face, 'reorder');
621
- if (flag(m.face, 'drag') && !isData(m) || reorder) {
622
- const index = reorder ? slots(parent!).indexOf(e as HTMLElement) : -1;
623
- return { face: m.face, el: e as HTMLElement, payload: get(m.face, 'value'), within: reorder ? parent! : null, index, group: null };
624
- }
625
- }
626
- return null;
627
- }
628
-
629
- /** The drop target under a point, and the insertion index there. */
630
- function targetAt(src: Source, x: number, y: number): Target | null {
631
- for (let m = mountedAbove(document.elementFromPoint(x, y)); m !== undefined; m = mountedAbove(m.el.parentElement)) {
632
- if (m.open !== null) {
633
- const t = treeTarget(m, src, x, y);
634
- if (t !== null) return t;
635
- continue;
636
- }
637
- const reorder = m === src.within;
638
- if ((reorder || flag(m.face, 'drop')) && m.el !== src.el && !src.el.contains(m.el)) {
639
- return { m, index: insertionAt(m, x, y), reorder };
640
- }
641
- }
642
- return null;
643
- }
644
-
645
- const horizontal = (m: Mounted): boolean => word(m.face, 'style') === 'row';
646
-
647
- function insertionAt(m: Mounted, x: number, y: number): number {
648
- const across = horizontal(m);
649
- let i = 0;
650
- for (const e of slots(m)) {
651
- const r = e.getBoundingClientRect();
652
- if ((across ? x : y) > (across ? r.left + r.width / 2 : r.top + r.height / 2)) i++;
653
- }
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;
660
- }
661
-
662
- let line: HTMLElement | null = null;
663
-
664
- /** Shows where a drop would land: a line between slots, and the target outlined. */
665
- function indicate(t: Target | null): void {
666
- document.querySelectorAll('.tb-drop-over').forEach(e => e.classList.remove('tb-drop-over'));
667
- if (t === null) { line?.remove(); line = null; return; }
668
- if (t.into !== undefined) {
669
- // into a folder: outline its row instead of drawing a line
670
- t.into.querySelector(':scope > .tb-tree-row')!.classList.add('tb-drop-over');
671
- line?.remove();
672
- line = null;
673
- return;
674
- }
675
- t.m.el.classList.add('tb-drop-over');
676
- if (line === null) {
677
- line = el('div', 'tb-drop-line');
678
- line.setAttribute('aria-hidden', 'true');
679
- document.body.append(line);
680
- }
681
- const across = horizontal(t.m);
682
- const all = t.group !== undefined ? Array.from(t.group.children) : slots(t.m);
683
- const box = (t.group ?? t.m.box ?? t.m.el).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();
687
- line.classList.toggle('tb-across', across);
688
- if (across) {
689
- const at = before && after ? (after.right + before.left) / 2 : before ? before.left - 3 : after ? after.right + 3 : box.left + 8;
690
- const r = before ?? after ?? box;
691
- Object.assign(line.style, { left: `${at - 1}px`, top: `${r.top}px`, width: '', height: `${r.height}px` });
692
- } else {
693
- const at = before && after ? (after.bottom + before.top) / 2 : before ? before.top - 3 : after ? after.bottom + 3 : box.top + 8;
694
- const r = before ?? after ?? box;
695
- Object.assign(line.style, { left: `${r.left}px`, top: `${at - 1}px`, width: `${r.width}px`, height: '' });
696
- }
697
- }
698
-
699
- /** Ends a drag on a target: a move inside its container, or a drop. */
700
- function land(src: Source, t: Target): void {
701
- if (t.reorder) {
702
- const to = t.index > src.index ? t.index - 1 : t.index;
703
- if (to !== src.index) void reorder(t.m, src.index, to, t.group, t.parent);
704
- } else {
705
- void fire('ui-drop', t.m.face, src.payload, src.face, int(t.index + 1), t.parent ?? NONE);
706
- }
707
- }
708
-
709
- const int = (n: number): Cell => ({ t: K.Integer, v: n });
710
-
711
- /** Moves a child or row and keeps the focus on it once the page is repainted. */
712
- async function reorder(m: Mounted, from: number, to: number, group?: HTMLElement, parent: Cell = NONE): Promise<void> {
713
- const had = document.activeElement !== null && document.activeElement !== document.body && m.el.contains(document.activeElement);
714
- await fire('ui-reorder', m.face, int(from + 1), int(to + 1), parent);
715
- syncDirty();
716
- if (!had) return;
717
- const e = group !== undefined ? group.children[to] as HTMLElement | undefined : slots(m)[to - m.first];
718
- const focusable = e?.matches('[tabindex], button, a, input, textarea, select') ? e : e?.querySelector<HTMLElement>('[tabindex], button, a, input, textarea, select');
719
- (focusable ?? null)?.focus();
720
- }
721
-
722
- /** "Move to" entries: the visible drop zones other than the face itself. */
723
- function moveTargets(face: ObjectCell, payload: Cell): MenuEntry[] {
724
- const out: MenuEntry[] = [];
725
- for (const z of dropZones) {
726
- if (!z.el.isConnected) { dropZones.delete(z); continue; }
727
- if (z.face.ctx === face.ctx || z.el.getClientRects().length === 0) continue;
728
- // a nameless zone around a named one is the same place
729
- if (str(z.face, 'text') === null && z.el.querySelector('.tb-drop-zone') !== null) continue;
730
- out.push({
731
- text: str(z.face, 'text') ?? word(z.face, 'style') ?? '',
732
- run: () => void fire('ui-drop', z.face, payload, face, int(slotCount(z) + 1), NONE),
733
- });
734
- }
735
- return out;
736
- }
737
-
738
- interface Dragging { src: Source; x: number; y: number; id: number; on: boolean; ghost: HTMLElement | null; target: Target | null; timer: number }
739
- let dragging: Dragging | null = null;
740
-
741
- function startDrag(d: Dragging): void {
742
- d.on = true;
743
- d.ghost = el('div', 'tb-drag-ghost');
744
- d.ghost.textContent = (d.src.el.innerText || d.src.el.textContent || '').split('\n').find(t => t.trim() !== '')?.trim() ?? '';
745
- d.ghost.setAttribute('aria-hidden', 'true');
746
- document.body.append(d.ghost);
747
- d.src.el.classList.add('tb-dragging');
748
- getSelection()?.removeAllRanges();
749
- document.documentElement.classList.add('tb-drag-active');
750
- moveDrag(d, d.x, d.y);
751
- }
752
-
753
- function moveDrag(d: Dragging, x: number, y: number): void {
754
- d.ghost!.style.transform = `translate(${x + 12}px, ${y + 12}px)`;
755
- d.target = targetAt(d.src, x, y);
756
- indicate(d.target);
757
- }
758
-
759
- function endDrag(drop: boolean): void {
760
- const d = dragging;
761
- if (d === null) return;
762
- dragging = null;
763
- clearTimeout(d.timer);
764
- if (!d.on) return;
765
- d.ghost?.remove();
766
- d.src.el.classList.remove('tb-dragging');
767
- document.documentElement.classList.remove('tb-drag-active');
768
- indicate(null);
769
- if (drop && d.target !== null) land(d.src, d.target);
770
- // the click that ends a drag is not a click
771
- addEventListener('click', swallowClick, true);
772
- setTimeout(() => removeEventListener('click', swallowClick, true), 0);
773
- }
774
-
775
- function swallowClick(ev: Event): void {
776
- ev.stopPropagation();
777
- ev.preventDefault();
778
- }
779
-
780
- function onPointerDown(ev: PointerEvent): void {
781
- if (ev.button !== 0 || dragging !== null) return;
782
- const src = sourceAt(ev.target as Element);
783
- if (src === null) return;
784
- const d: Dragging = { src, x: ev.clientX, y: ev.clientY, id: ev.pointerId, on: false, ghost: null, target: null, timer: 0 };
785
- dragging = d;
786
- // on touch a long press starts the drag, so a swipe still scrolls
787
- if (ev.pointerType === 'touch') d.timer = setTimeout(() => { if (dragging === d) startDrag(d); }, 400) as unknown as number;
788
- }
789
-
790
- function onPointerMove(ev: PointerEvent): void {
791
- const d = dragging;
792
- if (d === null || ev.pointerId !== d.id) return;
793
- if (!d.on) {
794
- const far = Math.hypot(ev.clientX - d.x, ev.clientY - d.y) > 5;
795
- if (!far) return;
796
- if (ev.pointerType === 'touch') return endDrag(false);
797
- d.x = ev.clientX;
798
- d.y = ev.clientY;
799
- startDrag(d);
800
- }
801
- ev.preventDefault();
802
- moveDrag(d, ev.clientX, ev.clientY);
803
- }
804
-
805
- /** Alt+Up and Alt+Down move the focused row or child inside a reorderable container. */
806
- function onReorderKey(ev: KeyboardEvent): void {
807
- if (inDevtools(ev.target)) return;
808
- if (!ev.altKey || ev.ctrlKey || ev.metaKey || (ev.key !== 'ArrowUp' && ev.key !== 'ArrowDown')) return;
809
- const at = document.activeElement;
810
- if (at === null) return;
811
- const src = sourceAt(at);
812
- if (src === null || src.within === null) return;
813
- const to = src.index + (ev.key === 'ArrowUp' ? -1 : 1);
814
- if (to < 0 || to >= (src.group !== null ? src.group.children.length : slotCount(src.within))) return;
815
- ev.preventDefault();
816
- seenKeys.add(ev);
817
- const group = src.group ?? undefined;
818
- void reorder(src.within, src.index, to, group, group !== undefined && src.within.open !== null ? groupParent(src.within, group) : NONE);
819
- }
820
-
821
- // --- menus ---------------------------------------------------------------------------
822
-
823
- /** The open menus, outermost first. */
824
- const menus: HTMLElement[] = [];
825
- /** Where focus goes back when the menus close. */
826
- let menuOpener: HTMLElement | null = null;
827
-
828
- function closeMenus(from = 0, refocus = true): void {
829
- for (const mn of menus.splice(from)) {
830
- mn.hidePopover?.();
831
- mn.remove();
832
- }
833
- if (from === 0) {
834
- menuOpener?.setAttribute('aria-expanded', 'false');
835
- if (!menuOpener?.hasAttribute('aria-haspopup')) menuOpener?.removeAttribute('aria-expanded');
836
- if (refocus) menuOpener?.focus();
837
- menuOpener = null;
838
- document.removeEventListener('pointerdown', outsideMenu, true);
839
- } else {
840
- (menus[from - 1]?.querySelector('[aria-expanded="true"]') as HTMLElement | null)?.setAttribute('aria-expanded', 'false');
841
- }
842
- }
843
-
844
- function outsideMenu(ev: PointerEvent): void {
845
- if (!menus.some(mn => mn.contains(ev.target as Node))) closeMenus(0, false);
846
- }
847
-
848
- function menuItems(mn: HTMLElement): HTMLElement[] {
849
- return Array.from(mn.querySelectorAll<HTMLElement>(':scope > [role="menuitem"]'));
850
- }
851
-
852
- interface MenuEntry {
853
- text: string;
854
- icon?: string | null;
855
- divider?: boolean;
856
- sub?: MenuEntry[];
857
- run?: () => void;
858
- }
859
-
860
- /** A menu block of the dialect as menu entries; choosing one runs ui-menu. */
861
- function trebolEntries(face: ObjectCell, items: BlockCell, row: Cell): MenuEntry[] {
862
- return (items.s.data.slice(items.i).filter(x => x.t === K.Object) as ObjectCell[]).map(item => {
863
- const sub = get(item, 'items');
864
- return {
865
- text: str(item, 'text') ?? '',
866
- icon: iconName(item),
867
- divider: flag(item, 'divider'),
868
- sub: sub.t === K.Block ? trebolEntries(face, sub as BlockCell, row) : undefined,
869
- run: () => void fire('ui-menu', face, item, row),
870
- };
871
- });
872
- }
873
-
874
- /** Opens a menu at x, y; level > 0 is a submenu. */
875
- function openMenu(entries: MenuEntry[], x: number, y: number, opener: HTMLElement, level = 0): void {
876
- closeMenus(level, false);
877
- if (level === 0) {
878
- menuOpener = opener;
879
- if (opener.hasAttribute('aria-haspopup')) opener.setAttribute('aria-expanded', 'true');
880
- document.addEventListener('pointerdown', outsideMenu, true);
881
- }
882
- const mn = el('div', 'tb-menu');
883
- mn.setAttribute('role', 'menu');
884
- mn.setAttribute('popover', 'manual');
885
- const label = opener.getAttribute('aria-label') ?? opener.textContent;
886
- if (label) mn.setAttribute('aria-label', label.trim());
887
- for (const item of entries) {
888
- if (item.divider) {
889
- const d = el('div', 'tb-menu-divider');
890
- d.setAttribute('role', 'separator');
891
- mn.append(d);
892
- continue;
893
- }
894
- const b = el('button', 'tb-menu-item');
895
- b.type = 'button';
896
- b.tabIndex = -1;
897
- b.setAttribute('role', 'menuitem');
898
- const svg = item.icon ? icon(item.icon) : null;
899
- const text = el('span');
900
- text.textContent = item.text;
901
- b.append(svg ?? el('span', 'tb-menu-gap'), text);
902
- const sub = item.sub;
903
- if (sub !== undefined) {
904
- b.setAttribute('aria-haspopup', 'menu');
905
- b.setAttribute('aria-expanded', 'false');
906
- const chevron = icon('chevron-right');
907
- if (chevron !== null) b.append(chevron);
908
- const openSub = (): void => {
909
- const r = b.getBoundingClientRect();
910
- openMenu(sub, r.right - 4, r.top - 5, b, level + 1);
911
- b.setAttribute('aria-expanded', 'true');
912
- };
913
- b.addEventListener('click', openSub);
914
- b.addEventListener('keydown', ev => { if (ev.key === 'ArrowRight') { ev.preventDefault(); openSub(); } });
915
- } else {
916
- b.addEventListener('click', () => {
917
- closeMenus();
918
- item.run?.();
919
- });
920
- }
921
- b.addEventListener('pointerenter', () => b.focus());
922
- mn.append(b);
923
- }
924
- mn.addEventListener('keydown', ev => {
925
- seenKeys.add(ev);
926
- const list = menuItems(mn);
927
- const at = list.indexOf(document.activeElement as HTMLElement);
928
- const n = list.length;
929
- const to = ev.key === 'ArrowDown' ? (at + 1) % n : ev.key === 'ArrowUp' ? (at - 1 + n) % n
930
- : ev.key === 'Home' ? 0 : ev.key === 'End' ? n - 1 : -1;
931
- if (to >= 0) {
932
- ev.preventDefault();
933
- list[to]?.focus();
934
- } else if (ev.key === 'Escape' || (ev.key === 'ArrowLeft' && level > 0)) {
935
- ev.preventDefault();
936
- ev.stopPropagation();
937
- if (level > 0) { closeMenus(level); opener.focus(); } else closeMenus();
938
- } else if (ev.key === 'Tab') {
939
- ev.preventDefault();
940
- closeMenus();
941
- } else if (ev.key.length === 1 && /\S/.test(ev.key)) {
942
- // type a letter to jump to the next item that starts with it
943
- const k = ev.key.toLowerCase();
944
- const next = [...list.slice(at + 1), ...list.slice(0, at + 1)].find(b => b.textContent?.trim().toLowerCase().startsWith(k));
945
- next?.focus();
946
- }
947
- });
948
- // keep the icon column only when some item has an icon
949
- if (mn.querySelector('.tb-menu-item > svg:first-child') === null) mn.querySelectorAll('.tb-menu-gap').forEach(g => g.remove());
950
- // in the top layer, so it shows above an open dialog
951
- document.body.append(mn);
952
- mn.showPopover?.();
953
- const r = mn.getBoundingClientRect();
954
- mn.style.left = `${Math.max(8, Math.min(x, innerWidth - r.width - 8))}px`;
955
- mn.style.top = `${Math.max(8, y + r.height > innerHeight - 8 ? y - r.height : y)}px`;
956
- menus.push(mn);
957
- menuItems(mn)[0]?.focus();
958
- }
959
-
960
- // --- calendar ------------------------------------------------------------------------
961
- //
962
- // The calendar of a date field: a grid of days, as in the WAI-ARIA date picker
963
- // pattern. Arrows move by days and weeks, Page Up/Down by months, Home/End to
964
- // the ends of the week, Enter or Space picks, Esc closes. Days are UTC dates.
965
-
966
- interface Calendar { face: ObjectCell; opener: HTMLButtonElement; box: HTMLElement; month: HTMLElement; at: Date }
967
- let calendar: Calendar | null = null;
968
-
969
- const DAY_MS = 86400000;
970
-
971
- /** A date! cell as a UTC date at midnight, or null. */
972
- function utcDate(v: Cell): Date | null {
973
- return v.t === K.Date ? new Date(Date.UTC(v.v.y, v.v.m - 1, v.v.d)) : null;
974
- }
975
-
976
- function isoDay(d: Date): string {
977
- return d.toISOString().slice(0, 10);
978
- }
979
-
980
- /** The date argument of a min or max rule of a face, or null. */
981
- function dateRule(face: ObjectCell, rule: string): Date | null {
982
- const rules = get(face, 'rules');
983
- if (rules.t !== K.Block) return null;
984
- for (const r of rules.s.data) {
985
- if (r.t !== K.Block || r.s.data[0]?.t !== K.Word || spell((r.s.data[0] as WordCell).sym) !== rule) continue;
986
- return utcDate(r.s.data[1] ?? NONE);
987
- }
988
- return null;
989
- }
990
-
991
- function openCalendar(face: ObjectCell, opener: HTMLButtonElement): void {
992
- closeCalendar(false);
993
- const today = new Date(Date.UTC(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()));
994
- const box = el('div', 'tb-calendar');
995
- box.setAttribute('role', 'dialog');
996
- box.setAttribute('aria-label', opener.getAttribute('aria-label') ?? own('choose-date'));
997
- box.setAttribute('popover', 'manual');
998
- const month = el('h2', 'tb-calendar-month');
999
- month.id = `tb-${nextId++}`;
1000
- month.setAttribute('aria-live', 'polite');
1001
- const step = (name: string, label: string, by: number): HTMLButtonElement => {
1002
- const b = el('button', 'tb-calendar-step');
1003
- b.type = 'button';
1004
- b.setAttribute('aria-label', label);
1005
- const svg = icon(name);
1006
- if (svg !== null) b.append(svg);
1007
- b.addEventListener('click', () => {
1008
- if (calendar === null) return;
1009
- calendar.at = addMonths(calendar.at, by);
1010
- renderCalendar();
1011
- });
1012
- return b;
1013
- };
1014
- const head = el('div', 'tb-calendar-head');
1015
- head.append(step('chevron-left', own('previous-month'), -1), month, step('chevron-right', own('next-month'), 1));
1016
- box.append(head);
1017
- calendar = { face, opener, box, month, at: utcDate(get(face, 'value')) ?? today };
1018
- opener.setAttribute('aria-expanded', 'true');
1019
- box.addEventListener('keydown', calendarKey);
1020
- box.addEventListener('focusout', ev => {
1021
- if (calendar?.box === box && !box.contains(ev.relatedTarget as Node | null) && ev.relatedTarget !== null) closeCalendar(false);
1022
- });
1023
- document.addEventListener('pointerdown', outsideCalendar, true);
1024
- document.body.append(box);
1025
- box.showPopover?.();
1026
- renderCalendar();
1027
- const r = opener.closest('.tb-date')!.getBoundingClientRect();
1028
- const c = box.getBoundingClientRect();
1029
- box.style.left = `${Math.max(8, Math.min(r.right - c.width, innerWidth - c.width - 8))}px`;
1030
- box.style.top = `${r.bottom + 4 + c.height > innerHeight - 8 ? Math.max(8, r.top - 4 - c.height) : r.bottom + 4}px`;
1031
- focusDay();
1032
- }
1033
-
1034
- function closeCalendar(refocus = true): void {
1035
- if (calendar === null) return;
1036
- const { box, opener } = calendar;
1037
- calendar = null;
1038
- box.hidePopover?.();
1039
- box.remove();
1040
- opener.setAttribute('aria-expanded', 'false');
1041
- document.removeEventListener('pointerdown', outsideCalendar, true);
1042
- if (refocus) opener.focus();
1043
- }
1044
-
1045
- function outsideCalendar(ev: PointerEvent): void {
1046
- if (calendar !== null && !calendar.box.contains(ev.target as Node) && !calendar.opener.contains(ev.target as Node)) closeCalendar(false);
1047
- }
1048
-
1049
- /** Draws the month of the focused day; the head stays. */
1050
- function renderCalendar(): void {
1051
- const cal = calendar!;
1052
- const lang = activeLanguage(host.rt);
1053
- const at = cal.at;
1054
- const min = dateRule(cal.face, 'min');
1055
- const max = dateRule(cal.face, 'max');
1056
- const chosen = utcDate(get(cal.face, 'value'));
1057
- const now = new Date();
1058
- const today = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
1059
- const fmt = (opts: Intl.DateTimeFormatOptions): Intl.DateTimeFormat => new Intl.DateTimeFormat(lang, { timeZone: 'UTC', ...opts });
1060
-
1061
- cal.month.textContent = fmt({ month: 'long', year: 'numeric' }).format(at);
1062
- const grid = el('table', 'tb-calendar-grid');
1063
- grid.setAttribute('role', 'grid');
1064
- grid.setAttribute('aria-labelledby', cal.month.id);
1065
- const first = weekStart(lang) % 7;
1066
- const names = el('tr');
1067
- for (let i = 0; i < 7; i++) {
1068
- // 4-Jan-1970 was a Sunday
1069
- const day = new Date(Date.UTC(1970, 0, 4 + ((first + i) % 7)));
1070
- const th = el('th');
1071
- th.scope = 'col';
1072
- th.abbr = fmt({ weekday: 'long' }).format(day);
1073
- th.textContent = fmt({ weekday: 'narrow' }).format(day);
1074
- names.append(th);
1075
- }
1076
- const thead = el('thead');
1077
- thead.append(names);
1078
- const body = el('tbody');
1079
- const start = Date.UTC(at.getUTCFullYear(), at.getUTCMonth(), 1);
1080
- let ms = start - ((new Date(start).getUTCDay() - first + 7) % 7) * DAY_MS;
1081
- const label = fmt({ dateStyle: 'full' });
1082
- do {
1083
- const row = el('tr');
1084
- for (let i = 0; i < 7; i++, ms += DAY_MS) {
1085
- const d = new Date(ms);
1086
- const td = el('td', 'tb-calendar-day');
1087
- td.setAttribute('role', 'gridcell');
1088
- td.textContent = String(d.getUTCDate());
1089
- td.setAttribute('aria-label', label.format(d));
1090
- td.dataset.day = isoDay(d);
1091
- td.tabIndex = ms === at.getTime() ? 0 : -1;
1092
- if (d.getUTCMonth() !== at.getUTCMonth()) td.classList.add('tb-calendar-other');
1093
- if (ms === today) td.setAttribute('aria-current', 'date');
1094
- td.setAttribute('aria-selected', chosen !== null && ms === chosen.getTime() ? 'true' : 'false');
1095
- if ((min !== null && d < min) || (max !== null && d > max)) td.setAttribute('aria-disabled', 'true');
1096
- td.addEventListener('click', () => pickDay(d));
1097
- row.append(td);
1098
- }
1099
- body.append(row);
1100
- } while (new Date(ms).getUTCMonth() === at.getUTCMonth());
1101
- grid.append(thead, body);
1102
- cal.box.querySelector('table')?.remove();
1103
- cal.box.append(grid);
1104
- }
1105
-
1106
- function addMonths(d: Date, n: number): Date {
1107
- const y = d.getUTCFullYear(), m = d.getUTCMonth() + n;
1108
- // the same day, or the last one of a shorter month
1109
- const last = new Date(Date.UTC(y, m + 1, 0)).getUTCDate();
1110
- return new Date(Date.UTC(y, m, Math.min(d.getUTCDate(), last)));
1111
- }
1112
-
1113
- function focusDay(): void {
1114
- calendar?.box.querySelector<HTMLElement>('td[tabindex="0"]')?.focus();
1115
- }
1116
-
1117
- function pickDay(d: Date): void {
1118
- const cal = calendar;
1119
- if (cal === null) return;
1120
- if (cal.box.querySelector(`td[data-day="${isoDay(d)}"]`)?.getAttribute('aria-disabled') === 'true') return;
1121
- const face = cal.face;
1122
- closeCalendar();
1123
- void fire('ui-input', face, string(isoDay(d))).then(() => fire('ui-blur', face));
1124
- }
1125
-
1126
- function calendarKey(ev: KeyboardEvent): void {
1127
- const cal = calendar;
1128
- if (cal === null) return;
1129
- seenKeys.add(ev);
1130
- if (ev.key === 'Escape') {
1131
- ev.preventDefault();
1132
- ev.stopPropagation();
1133
- closeCalendar();
1134
- return;
1135
- }
1136
- if (!(ev.target instanceof HTMLTableCellElement)) return;
1137
- const at = cal.at;
1138
- const first = weekStart(activeLanguage(host.rt)) % 7;
1139
- const back = (at.getUTCDay() - first + 7) % 7;
1140
- const days: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7, Home: -back, End: 6 - back };
1141
- let to: Date | null = null;
1142
- if (ev.key in days) to = new Date(at.getTime() + days[ev.key]! * DAY_MS);
1143
- else if (ev.key === 'PageUp' || ev.key === 'PageDown') to = addMonths(at, (ev.key === 'PageUp' ? -1 : 1) * (ev.shiftKey ? 12 : 1));
1144
- else if (ev.key === 'Enter' || ev.key === ' ') {
1145
- ev.preventDefault();
1146
- pickDay(at);
1147
- return;
1148
- }
1149
- if (to === null) return;
1150
- ev.preventDefault();
1151
- cal.at = to;
1152
- if (to.getUTCMonth() === at.getUTCMonth()) {
1153
- cal.box.querySelectorAll<HTMLElement>('td[tabindex="0"]').forEach(td => { td.tabIndex = -1; });
1154
- const td = cal.box.querySelector<HTMLElement>(`td[data-day="${isoDay(to)}"]`)!;
1155
- td.tabIndex = 0;
1156
- td.focus();
1157
- } else {
1158
- renderCalendar();
1159
- focusDay();
1160
- }
1161
- }
1162
-
1163
- const MODIFIER_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph', 'CapsLock', 'Dead', 'Unidentified']);
1164
-
1165
- /** Keys that are characters in Red's event/key. */
1166
- const KEY_CHARS: Record<string, number> = { Enter: 13, Escape: 27, Tab: 9, Backspace: 8 };
1167
- /** Keys that are words in Red's event/key. */
1168
- const KEY_WORDS: Record<string, string> = {
1169
- ArrowLeft: 'left', ArrowRight: 'right', ArrowUp: 'up', ArrowDown: 'down', Home: 'home', End: 'end',
1170
- PageUp: 'page-up', PageDown: 'page-down', Insert: 'insert', Delete: 'delete',
1171
- };
1172
-
1173
- /** A key as Red gives it in event/key: a char! (#"a", #"^M" for Enter) or a word ('left, 'F2). */
1174
- function keyCell(ev: KeyboardEvent): Cell | null {
1175
- if (MODIFIER_KEYS.has(ev.key)) return null;
1176
- const c = KEY_CHARS[ev.key];
1177
- if (c !== undefined) return char(c);
1178
- const cps = [...ev.key];
1179
- if (cps.length === 1) return char(cps[0]!.codePointAt(0)!);
1180
- if (/^F\d+$/.test(ev.key)) return wordOf(K.LitWord, ev.key);
1181
- return wordOf(K.LitWord, KEY_WORDS[ev.key] ?? ev.key.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase());
1182
- }
1183
-
1184
- function keyWords(ev: KeyboardEvent): [string, Cell][] {
1185
- const b = (x: boolean): Cell => x ? TRUE : FALSE;
1186
- return [['key', keyCell(ev)!], ['ctrl?', b(ev.ctrlKey)], ['shift?', b(ev.shiftKey)], ['alt?', b(ev.altKey)], ['meta?', b(ev.metaKey)]];
1187
- }
1188
-
1189
- const APPLE = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);
1190
- const KEY_NAMES: Record<string, string> = {
1191
- esc: 'escape', space: ' ', del: 'delete', up: 'arrowup', down: 'arrowdown', left: 'arrowleft', right: 'arrowright',
1192
- };
1193
-
1194
- interface Shortcut { key: string; ctrl: boolean; shift: boolean; alt: boolean; meta: boolean }
1195
-
1196
- /** "Ctrl+Shift+K" -> its parts; Ctrl also means Cmd on Apple devices. */
1197
- function parseShortcut(spec: string): Shortcut {
1198
- const parts = spec.toLowerCase().split('+').map(p => p.trim());
1199
- const key = parts.pop() ?? '';
1200
- const has = (...names: string[]): boolean => parts.some(p => names.includes(p));
1201
- return { key: KEY_NAMES[key] ?? key, ctrl: has('ctrl', 'control'), shift: has('shift'), alt: has('alt', 'option'), meta: has('meta', 'cmd') };
1202
- }
1203
-
1204
- function matches(ev: KeyboardEvent, s: Shortcut): boolean {
1205
- const ctrl = APPLE ? ev.metaKey || ev.ctrlKey : ev.ctrlKey;
1206
- if (ctrl !== (s.ctrl || (APPLE && s.meta)) || ev.shiftKey !== s.shift || ev.altKey !== s.alt) return false;
1207
- if (!APPLE && ev.metaKey !== s.meta) return false;
1208
- // letters and digits by physical key, so Shift or Alt do not change them
1209
- if (/^[a-z]$/.test(s.key)) return ev.code === `Key${s.key.toUpperCase()}`;
1210
- if (/^[0-9]$/.test(s.key)) return ev.code === `Digit${s.key}`;
1211
- return ev.key.toLowerCase() === s.key;
1212
- }
1213
-
1214
- /** How a shortcut is announced (aria-keyshortcuts) and shown (tooltip). */
1215
- function shortcutAria(spec: string): string {
1216
- return spec.split('+').map(p => {
1217
- const w = p.trim().toLowerCase();
1218
- if (w === 'ctrl' || w === 'control') return APPLE ? 'Meta' : 'Control';
1219
- if (w === 'cmd') return 'Meta';
1220
- return p.trim().length === 1 ? p.trim().toUpperCase() : p.trim();
1221
- }).join('+');
1222
- }
1223
-
1224
- function shortcutLabel(spec: string): string {
1225
- return APPLE ? spec.replace(/ctrl|control/i, 'Cmd') : spec;
1226
- }
1227
-
1228
- /** Shortcuts beat the browser's own keys; the view's on-key gets keys nobody handled. */
1229
- function onKeyDown(ev: KeyboardEvent): void {
1230
- if (inDevtools(ev.target)) return;
1231
- const modal = Array.from(document.querySelectorAll('dialog[open]')).pop();
1232
- for (const m of shortcuts) {
1233
- if (!m.el.isConnected) { shortcuts.delete(m); continue; }
1234
- const spec = str(m.face, 'shortcut');
1235
- if (spec === null || !matches(ev, parseShortcut(spec))) continue;
1236
- // only what the user can see: not in a hidden tab, a closed dialog or behind a modal
1237
- if (m.el.getClientRects().length === 0 || (modal !== undefined && !modal.contains(m.el))) continue;
1238
- ev.preventDefault();
1239
- seenKeys.add(ev);
1240
- m.el.click();
1241
- return;
1242
- }
1243
- }
1244
-
1245
- function onViewKey(ev: KeyboardEvent): void {
1246
- if (inDevtools(ev.target)) return;
1247
- if (viewKeys === null || seenKeys.has(ev) || keyCell(ev) === null) return;
1248
- fireEvent(viewKeys, 'on-key', keyWords(ev));
1249
- }
1250
-
1251
- /** Puts the face's icon before its caption, which then goes in `m.label`. */
1252
- function withIcon(node: HTMLElement, face: ObjectCell, m: Mounted): void {
1253
- const name = iconName(face);
1254
- const svg = name !== null ? icon(name) : null;
1255
- if (svg === null) return;
1256
- m.label = el('span');
1257
- node.append(svg, m.label);
1258
- node.classList.add('tb-has-icon');
1259
- }
1260
-
1261
- /** A face with an icon and no text is named after its icon: #arrow-left -> "Arrow left". */
1262
- function iconLabel(face: ObjectCell): string | null {
1263
- const name = iconName(face);
1264
- if (name === null || (str(face, 'text') ?? '') !== '') return null;
1265
- const hint = str(face, 'hint');
1266
- if (hint !== null) return hint;
1267
- const words = name.replace(/-/g, ' ');
1268
- return words.charAt(0).toUpperCase() + words.slice(1);
1269
- }
1270
-
1271
- /** Children of a container; consecutive buttons in a form share an action row. */
1272
- function appendChildren(node: HTMLElement, face: ObjectCell, style: string): void {
1273
- let actions: HTMLElement | null = null;
1274
- for (const c of children(face)) {
1275
- const isButton = word(c, 'style') === 'button';
1276
- if (style === 'form' && isButton) {
1277
- if (actions === null) {
1278
- actions = el('div', 'tb-actions');
1279
- node.append(actions);
1280
- }
1281
- actions.append(build(c));
1282
- } else {
1283
- actions = null;
1284
- const n = build(c);
1285
- if (style === 'toolbar' && n.tagName === 'HR') n.setAttribute('aria-orientation', 'vertical');
1286
- node.append(n);
1287
- }
1288
- }
1289
- }
1290
-
1291
- function clickSubmit(face: ObjectCell, formEl: HTMLElement): void {
1292
- void fire('ui-click', face).then(() => {
1293
- // after a failed submit, take the user to the first problem
1294
- for (const i of Array.from(formEl.querySelectorAll<HTMLElement>('input, textarea, select'))) {
1295
- const m = byNode.get(i);
1296
- if (m !== undefined && get(m.face, 'error').t === K.String) return i.focus();
1297
- }
1298
- });
1299
- }
1300
-
1301
- function buildInput(face: ObjectCell, style: string, m: Mounted): HTMLElement {
1302
- const id = `tb-${nextId++}`;
1303
- const wrap = el('div', 'tb-field');
1304
- const label = el('label', 'tb-label');
1305
- label.htmlFor = id;
1306
- const control = el('div', 'tb-control');
1307
- let input: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
1308
- if (style === 'area') {
1309
- input = el('textarea', 'tb-input');
1310
- } else if (style === 'choice') {
1311
- const sel = el('select', 'tb-input');
1312
- fillSelect(sel, face);
1313
- input = sel;
1314
- } else {
1315
- const i = el('input', 'tb-input');
1316
- i.type = style === 'password' ? 'password' : hasRule(face, 'email') ? 'email' : hasRule(face, 'url') ? 'url' : 'text';
1317
- if (style === 'number' || style === 'money' || hasRule(face, 'integer')) i.inputMode = hasRule(face, 'integer') ? 'numeric' : 'decimal';
1318
- if (style === 'password') i.autocomplete = 'new-password';
1319
- input = i;
1320
- }
1321
- input.addEventListener('focus', () => hadCaret.add(input));
1322
- input.id = id;
1323
- const error = el('div', 'tb-error');
1324
- error.id = `${id}-error`;
1325
- error.setAttribute('aria-live', 'polite');
1326
- input.setAttribute('aria-describedby', error.id);
1327
- const name = word(face, 'name');
1328
- if (name !== null) input.name = name;
1329
- input.addEventListener(style === 'choice' ? 'change' : 'input', () => {
1330
- // an amount goes to Trebol as 1234.5 and a date as 2026-11-03; what is not one goes as typed
1331
- const lang = activeLanguage(host.rt);
1332
- const typed = style === 'money' ? readLocal(input.value, lang) ?? input.value
1333
- : style === 'date' ? readDate(input.value, lang) ?? input.value : input.value;
1334
- m.typing++;
1335
- const settled = (): void => {
1336
- m.typing--;
1337
- m.typed = get(face, 'value');
1338
- };
1339
- void fire('ui-input', face, typed === '' ? NONE : string(typed)).then(settled, settled);
1340
- });
1341
- // an amount shows formatted, and is edited as a plain number of the active language
1342
- if (style === 'money') input.addEventListener('focus', () => {
1343
- if (!flag(face, 'readonly')) input.value = editLocal(get(face, 'value'), activeLanguage(host.rt));
1344
- });
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); });
1347
- const iconWord = style === 'area' || style === 'choice' ? null : iconName(face);
1348
- const svg = iconWord !== null ? icon(iconWord) : null;
1349
- if (style === 'date') {
1350
- const box = el('div', 'tb-date');
1351
- const pick = el('button', 'tb-date-button');
1352
- pick.type = 'button';
1353
- pick.setAttribute('aria-haspopup', 'dialog');
1354
- pick.setAttribute('aria-expanded', 'false');
1355
- const cal = icon('calendar');
1356
- if (cal !== null) pick.append(cal);
1357
- pick.addEventListener('click', () => (calendar?.opener === pick ? closeCalendar() : openCalendar(face, pick)));
1358
- box.append(input, pick);
1359
- control.append(box, error);
1360
- } else if (svg !== null) {
1361
- const box = el('div', 'tb-input-icon');
1362
- box.append(svg, input);
1363
- control.append(box, error);
1364
- } else {
1365
- control.append(input, error);
1366
- }
1367
- wrap.append(label, control);
1368
- m.input = input;
1369
- m.label = label;
1370
- m.error = error;
1371
- return wrap;
1372
- }
1373
-
1374
- function buildCheck(face: ObjectCell, m: Mounted, toggle: boolean): HTMLElement {
1375
- const row = el('div', 'tb-check-row tb-control');
1376
- const label = el('label', toggle ? 'tb-check tb-switch' : 'tb-check');
1377
- const box = el('input');
1378
- box.type = 'checkbox';
1379
- if (toggle) box.setAttribute('role', 'switch');
1380
- const caption = el('span');
1381
- const error = el('div', 'tb-error');
1382
- error.id = `tb-${nextId++}-error`;
1383
- error.setAttribute('aria-live', 'polite');
1384
- box.setAttribute('aria-describedby', error.id);
1385
- box.addEventListener('change', () => {
1386
- void fire('ui-input', face, box.checked ? TRUE : FALSE).then(() => fire('ui-blur', face));
1387
- });
1388
- label.append(box, caption);
1389
- row.append(label, error);
1390
- m.input = box;
1391
- m.label = caption;
1392
- m.error = error;
1393
- return row;
1394
- }
1395
-
1396
- function buildRadio(face: ObjectCell, m: Mounted): HTMLElement {
1397
- const id = `tb-${nextId++}`;
1398
- const wrap = el('div', 'tb-field');
1399
- const label = el('span', 'tb-label');
1400
- label.id = id;
1401
- const control = el('div', 'tb-control');
1402
- const group = el('div', 'tb-radios');
1403
- group.setAttribute('role', 'radiogroup');
1404
- group.setAttribute('aria-labelledby', id);
1405
- const error = el('div', 'tb-error');
1406
- error.id = `${id}-error`;
1407
- error.setAttribute('aria-live', 'polite');
1408
- group.setAttribute('aria-describedby', error.id);
1409
- m.radios = [];
1410
- const radio = (o: Cell): HTMLElement => {
1411
- const option = el('label', 'tb-check');
1412
- const r = el('input');
1413
- r.type = 'radio';
1414
- r.name = id;
1415
- r.value = optionValue(o);
1416
- r.addEventListener('change', () => {
1417
- if (r.checked) void fire('ui-input', face, string(r.value)).then(() => fire('ui-blur', face));
1418
- });
1419
- const caption = el('span');
1420
- caption.textContent = optionText(o);
1421
- option.append(r, caption);
1422
- m.radios!.push(r);
1423
- return option;
1424
- };
1425
- // a group of options: its title over them, the group named by it
1426
- for (const e of entriesOf(face)) {
1427
- if (isGroup(e)) {
1428
- const sub = el('div', 'tb-radio-group');
1429
- sub.setAttribute('role', 'group');
1430
- const title = el('span', 'tb-radio-title');
1431
- title.id = `tb-${nextId++}`;
1432
- title.textContent = translate(e.title, host.rt);
1433
- sub.setAttribute('aria-labelledby', title.id);
1434
- const items = el('div', 'tb-radios');
1435
- items.append(...e.options.map(radio));
1436
- sub.append(title, items);
1437
- group.append(sub);
1438
- } else group.append(radio(e));
1439
- }
1440
- control.append(group, error);
1441
- wrap.append(label, control);
1442
- m.label = label;
1443
- m.error = error;
1444
- return wrap;
1445
- }
1446
-
1447
- // An upload: a button that is also a place to drop files, and the list of the
1448
- // chosen ones. Files go to Trebol as handles; their bytes stay in the browser.
1449
-
1450
- function buildUpload(face: ObjectCell, m: Mounted): HTMLElement {
1451
- const id = `tb-${nextId++}`;
1452
- const wrap = el('div', 'tb-field');
1453
- const label = el('label', 'tb-label');
1454
- label.htmlFor = id;
1455
- const control = el('div', 'tb-control');
1456
- const zone = el('div', 'tb-upload');
1457
- const picker = el('input');
1458
- picker.type = 'file';
1459
- picker.hidden = true;
1460
- picker.tabIndex = -1;
1461
- const choose = el('button', 'tb-button');
1462
- choose.type = 'button';
1463
- choose.id = id;
1464
- const svg = icon('upload');
1465
- if (svg !== null) choose.append(svg);
1466
- choose.append(el('span'));
1467
- const hint = el('span', 'tb-upload-hint');
1468
- const error = el('div', 'tb-error');
1469
- error.id = `${id}-error`;
1470
- error.setAttribute('aria-live', 'polite');
1471
- choose.setAttribute('aria-describedby', error.id);
1472
- const list = el('ul', 'tb-upload-list');
1473
- const track = sentBar(label, id);
1474
- choose.addEventListener('click', () => picker.click());
1475
- picker.addEventListener('change', () => {
1476
- const files = [...(picker.files ?? [])];
1477
- picker.value = '';
1478
- if (files.length > 0) chooseFiles(face, files);
1479
- });
1480
- dropFiles(face, zone, choose);
1481
- zone.append(choose, hint, picker);
1482
- control.append(zone, list, track, error);
1483
- wrap.append(label, control);
1484
- m.label = label;
1485
- m.error = error;
1486
- m.button = choose;
1487
- m.box = list;
1488
- return wrap;
1489
- }
1490
-
1491
- /** The accept list of an upload: extensions ("pdf") and types ("image/*"); a photo takes images unless told. */
1492
- function acceptList(face: ObjectCell): string[] {
1493
- const a = get(face, 'accept');
1494
- if (a.t !== K.Block && word(face, 'style') === 'photo') return ['image/*'];
1495
- return a.t === K.Block ? a.s.data.slice(a.i).map(x => form(x).trim().toLowerCase()).filter(x => x !== '') : [];
1496
- }
1497
-
1498
- /** The picker's accept attribute for an accept list. */
1499
- function pickerAccept(list: string[]): string {
1500
- return list.map(x => (x.includes('/') || x.startsWith('.') ? x : `.${x}`)).join(',');
1501
- }
1502
-
1503
- /** Lets a zone take files dropped on it, unless its button is disabled. */
1504
- function dropFiles(face: ObjectCell, zone: HTMLElement, button: HTMLButtonElement): void {
1505
- const hasFiles = (ev: DragEvent): boolean => ev.dataTransfer?.types.includes('Files') === true;
1506
- zone.addEventListener('dragover', ev => {
1507
- if (!hasFiles(ev) || button.disabled) return;
1508
- ev.preventDefault();
1509
- ev.dataTransfer!.dropEffect = 'copy';
1510
- zone.classList.add('tb-drop-over');
1511
- });
1512
- zone.addEventListener('dragleave', ev => {
1513
- if (!zone.contains(ev.relatedTarget as Node | null)) zone.classList.remove('tb-drop-over');
1514
- });
1515
- zone.addEventListener('drop', ev => {
1516
- zone.classList.remove('tb-drop-over');
1517
- if (!hasFiles(ev) || button.disabled) return;
1518
- ev.preventDefault();
1519
- chooseFiles(face, [...ev.dataTransfer!.files]);
1520
- });
1521
- }
1522
-
1523
- /** The bar of how far the files went up, while a fetch with progress sends them. */
1524
- function sentBar(label: HTMLElement, id: string): HTMLElement {
1525
- label.id = `${id}-label`;
1526
- const track = el('div', 'tb-progress tb-upload-progress');
1527
- track.setAttribute('role', 'progressbar');
1528
- track.setAttribute('aria-valuemin', '0');
1529
- track.setAttribute('aria-valuemax', '100');
1530
- track.setAttribute('aria-labelledby', label.id);
1531
- track.hidden = true;
1532
- track.append(el('div', 'tb-progress-bar'));
1533
- return track;
1534
- }
1535
-
1536
- function syncSent(m: Mounted): void {
1537
- const track = m.el.querySelector<HTMLElement>('.tb-upload-progress')!;
1538
- const sent = get(m.face, 'sent');
1539
- const part = fraction(sent) ?? 0;
1540
- track.hidden = sent.t === K.None;
1541
- track.setAttribute('aria-valuenow', String(Math.round(part * 100)));
1542
- (track.firstChild as HTMLElement).style.width = `${part * 100}%`;
1543
- }
1544
-
1545
- // A photo: the image itself, a button to choose one and another to take it away. The
1546
- // image chosen shows from the browser's memory; one kept elsewhere, from its address.
1547
-
1548
- // A video or a sound: the browser's own player. Captions are one track per language;
1549
- // the active language's is the one shown, and it follows set-language.
1550
-
1551
- /** A video's captions as [language, address] pairs: a file alone is in the active language. */
1552
- function captionTracks(f: ObjectCell): [string, string][] {
1553
- const c = get(f, 'captions');
1554
- if (c.t === K.File || c.t === K.Url || c.t === K.String) return [[activeLanguage(host.rt), form(c)]];
1555
- if (c.t !== K.Block) return [];
1556
- const d = c.s.data.slice(c.i);
1557
- const out: [string, string][] = [];
1558
- for (let i = 0; i + 1 < d.length; i += 2) out.push([form(d[i]!), form(d[i + 1]!)]);
1559
- return out;
1560
- }
1561
-
1562
- function syncMedia(m: Mounted): void {
1563
- const f = m.face;
1564
- const media = m.el as HTMLMediaElement;
1565
- const src = str(f, 'value') ?? '';
1566
- if (media.getAttribute('src') !== src) media.src = src;
1567
- const t = str(f, 'text');
1568
- if (t !== null) media.setAttribute('aria-label', t);
1569
- else media.removeAttribute('aria-label');
1570
- media.loop = flag(f, 'looping');
1571
- // browsers only let what plays on its own do so without sound
1572
- const auto = flag(f, 'autoplay');
1573
- media.muted = flag(f, 'silent') || auto;
1574
- media.autoplay = auto;
1575
- if (!(media instanceof HTMLVideoElement)) return;
1576
- const poster = str(f, 'poster') ?? '';
1577
- if (media.getAttribute('poster') !== poster) media.poster = poster;
1578
- const lang = activeLanguage(host.rt);
1579
- const tracks = captionTracks(f);
1580
- const names = new Intl.DisplayNames([lang], { type: 'language' });
1581
- const now = Array.from(media.querySelectorAll('track'));
1582
- if (now.map(x => `${x.srclang} ${x.getAttribute('src')}`).join('|') !== tracks.map(([l, s]) => `${l} ${s}`).join('|')) {
1583
- media.replaceChildren(...tracks.map(([l, s]) => {
1584
- const track = el('track') as HTMLTrackElement;
1585
- track.kind = 'captions';
1586
- track.srclang = l;
1587
- track.src = s;
1588
- return track;
1589
- }));
1590
- }
1591
- // the captions shown, if any, follow the active language
1592
- const showing = Array.from(media.textTracks).some(x => x.mode === 'showing');
1593
- const pick = tracks.findIndex(([l]) => l === lang);
1594
- media.querySelectorAll('track').forEach((track, i) => {
1595
- track.label = names.of(track.srclang) ?? track.srclang;
1596
- track.default = i === Math.max(0, pick);
1597
- if (showing) track.track.mode = i === Math.max(0, pick) ? 'showing' : 'disabled';
1598
- });
1599
- }
1600
-
1601
- /** The address that shows each chosen file, made once and freed when the photo shows another. */
1602
- const shownUrls = new WeakMap<HTMLElement, { blob: Blob; url: string }>();
1603
-
1604
- function buildPhoto(face: ObjectCell, m: Mounted): HTMLElement {
1605
- const id = `tb-${nextId++}`;
1606
- const wrap = el('div', 'tb-field');
1607
- const label = el('label', 'tb-label');
1608
- label.htmlFor = id;
1609
- const control = el('div', 'tb-control');
1610
- const zone = el('div', 'tb-photo');
1611
- // the frame opens the picker for a pointer; the keyboard has the button
1612
- const frame = el('div', 'tb-photo-frame');
1613
- frame.addEventListener('click', () => { if (!choose.disabled) picker.click(); });
1614
- const picker = el('input');
1615
- picker.type = 'file';
1616
- picker.hidden = true;
1617
- picker.tabIndex = -1;
1618
- const actions = el('div', 'tb-photo-actions');
1619
- const choose = el('button', 'tb-button');
1620
- choose.type = 'button';
1621
- choose.id = id;
1622
- const svg = icon('upload');
1623
- if (svg !== null) choose.append(svg);
1624
- choose.append(el('span'));
1625
- const remove = el('button', 'tb-button tb-photo-remove');
1626
- remove.type = 'button';
1627
- remove.addEventListener('click', () => {
1628
- choose.focus();
1629
- void fire('ui-remove-file', face, int(1));
1630
- });
1631
- const error = el('div', 'tb-error');
1632
- error.id = `${id}-error`;
1633
- error.setAttribute('aria-live', 'polite');
1634
- choose.setAttribute('aria-describedby', error.id);
1635
- choose.addEventListener('click', () => picker.click());
1636
- picker.addEventListener('change', () => {
1637
- const files = [...(picker.files ?? [])];
1638
- picker.value = '';
1639
- if (files.length > 0) chooseFiles(face, files);
1640
- });
1641
- dropFiles(face, zone, choose);
1642
- actions.append(choose, remove);
1643
- zone.append(frame, actions, picker);
1644
- control.append(zone, sentBar(label, id), error);
1645
- wrap.append(label, control);
1646
- m.label = label;
1647
- m.error = error;
1648
- m.button = choose;
1649
- m.box = frame;
1650
- return wrap;
1651
- }
1652
-
1653
- /** What a photo shows: the image chosen, or the address of one kept elsewhere; null for none. */
1654
- function photoSrc(frame: HTMLElement, v: Cell): string | null {
1655
- const kept = shownUrls.get(frame);
1656
- const file = v.t === K.Object ? handleOf<Blob>(get(v as ObjectCell, 'file'), 'file') : null;
1657
- if (file !== null && kept !== undefined && kept.blob === file) return kept.url;
1658
- if (kept !== undefined) {
1659
- URL.revokeObjectURL(kept.url);
1660
- shownUrls.delete(frame);
1661
- }
1662
- if (file !== null) {
1663
- const url = URL.createObjectURL(file);
1664
- shownUrls.set(frame, { blob: file, url });
1665
- return url;
1666
- }
1667
- return v.t === K.String || v.t === K.Url || v.t === K.File ? form(v) : null;
1668
- }
1669
-
1670
- function syncPhoto(m: Mounted, err: string | null): void {
1671
- const f = m.face;
1672
- const t = str(f, 'text') ?? '';
1673
- m.label!.textContent = t;
1674
- m.label!.classList.toggle('tb-required', required(f));
1675
- const readonly = flag(f, 'readonly');
1676
- const choose = m.button!;
1677
- choose.disabled = flag(f, 'disabled') || readonly;
1678
- choose.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
1679
- const frame = m.box!;
1680
- frame.classList.toggle('tb-round', flag(f, 'round'));
1681
- frame.classList.toggle('tb-photo-pick', !choose.disabled);
1682
- const src = photoSrc(frame, get(f, 'value'));
1683
- let img = frame.querySelector('img');
1684
- if (src === null) {
1685
- if (img !== null || frame.firstChild === null) {
1686
- const svg = icon(flag(f, 'round') ? 'user' : 'image');
1687
- frame.replaceChildren(...(svg !== null ? [svg] : []));
1688
- }
1689
- } else {
1690
- if (img === null) {
1691
- img = el('img') as HTMLImageElement;
1692
- frame.replaceChildren(img);
1693
- }
1694
- if (img.getAttribute('src') !== src) img.src = src;
1695
- img.alt = t;
1696
- }
1697
- (choose.lastChild as HTMLElement).textContent = own(src === null ? 'choose-photo' : 'change-photo');
1698
- const remove = m.el.querySelector<HTMLButtonElement>('.tb-photo-remove')!;
1699
- remove.textContent = own('remove-photo');
1700
- remove.hidden = src === null || readonly;
1701
- remove.disabled = choose.disabled;
1702
- // read only, there is nothing to choose: only the photo is left
1703
- (m.el.querySelector('.tb-photo-actions') as HTMLElement).hidden = readonly;
1704
- (m.el.querySelector('input[type="file"]') as HTMLInputElement).accept = pickerAccept(acceptList(f));
1705
- m.error!.textContent = err ?? '';
1706
- syncSent(m);
1707
- }
1708
-
1709
- // --- widget: an element the page's JavaScript defines ----------------------------
1710
- //
1711
- // The element is made by its tag, once the page has defined it (import %geo-map.js).
1712
- // The face's value is the element's value property, both ways, as JSON; its props set
1713
- // properties. Its change event gives the value back, and any other on-xxx of the face
1714
- // listens to the element's event xxx, with the event's detail. The theme's custom
1715
- // properties (--tb-*) reach it, as they reach every element of the page.
1716
-
1717
- /** What was last given to or taken from each widget, as JSON, so a repaint sets only what changed. */
1718
- const widgetSet = new WeakMap<HTMLElement, { value: string; props: string }>();
1719
-
1720
- /** Events every face has, which the host listens to itself. */
1721
- const FACE_EVENTS = new Set(['on-change', 'on-focus', 'on-unfocus', 'on-over', 'on-dbl-click', 'on-key', 'on-end',
1722
- 'on-drop', 'on-reorder', 'on-menu', 'on-select']);
1723
-
1724
- /** A JavaScript value as Trebol's, as JSON carries it; none for what JSON cannot write. */
1725
- function fromJs(x: unknown): Cell {
1726
- let json: string | undefined;
1727
- try {
1728
- json = JSON.stringify(x);
1729
- } catch {
1730
- json = undefined;
1731
- }
1732
- if (json === undefined) return NONE;
1733
- const v = parseJson(json);
1734
- return typeof v === 'string' ? NONE : v;
1735
- }
1736
-
1737
- function buildWidget(face: ObjectCell, m: Mounted): HTMLElement {
1738
- const id = `tb-${nextId++}`;
1739
- const wrap = el('div', 'tb-field');
1740
- const label = el('label', 'tb-label');
1741
- label.htmlFor = id;
1742
- const control = el('div', 'tb-control');
1743
- let node: HTMLElement;
1744
- try {
1745
- node = document.createElement(str(face, 'tag') ?? 'div');
1746
- } catch {
1747
- // a tag that is no element's name
1748
- node = el('div');
1749
- }
1750
- node.classList.add('tb-widget');
1751
- node.id = id;
1752
- const error = el('div', 'tb-error');
1753
- error.id = `${id}-error`;
1754
- error.setAttribute('aria-live', 'polite');
1755
- node.setAttribute('aria-describedby', error.id);
1756
- widgetSet.set(node, { value: '', props: '' });
1757
- node.addEventListener('change', ev => {
1758
- if (ev.target !== node) return;
1759
- const v = fromJs((node as unknown as { value?: unknown }).value);
1760
- widgetSet.get(node)!.value = toJson(v);
1761
- void fire('ui-input', face, v);
1762
- });
1763
- const events = get(face, 'events');
1764
- if (events.t === K.Block) {
1765
- for (const w of events.s.data) {
1766
- const name = w.t === K.Word ? spell((w as WordCell).sym).toLowerCase() : '';
1767
- if (!name.startsWith('on-') || FACE_EVENTS.has(name)) continue;
1768
- node.addEventListener(name.slice(3), ev => fireEvent(face, name, [['detail', fromJs((ev as CustomEvent).detail)]]));
1769
- }
1770
- }
1771
- control.append(node, error);
1772
- wrap.append(label, control);
1773
- m.label = label;
1774
- m.error = error;
1775
- m.box = node;
1776
- return wrap;
1777
- }
1778
-
1779
- function syncWidget(m: Mounted, err: string | null): void {
1780
- const f = m.face;
1781
- const t = str(f, 'text') ?? '';
1782
- m.label!.textContent = t;
1783
- m.label!.hidden = t === '';
1784
- m.label!.classList.toggle('tb-required', required(f));
1785
- const node = m.box! as HTMLElement & { value?: unknown; disabled?: boolean; readOnly?: boolean };
1786
- const set = widgetSet.get(node)!;
1787
- const props = get(f, 'props');
1788
- const propsJson = props.t === K.Object || props.t === K.Map ? toJson(props) : '{}';
1789
- if (propsJson !== set.props) {
1790
- Object.assign(node, JSON.parse(propsJson) as object);
1791
- set.props = propsJson;
1792
- }
1793
- const valueJson = toJson(get(f, 'value'));
1794
- if (valueJson !== set.value) {
1795
- node.value = JSON.parse(valueJson) as unknown;
1796
- set.value = valueJson;
1797
- }
1798
- const disabled = flag(f, 'disabled');
1799
- node.toggleAttribute('disabled', disabled);
1800
- if ('disabled' in node) node.disabled = disabled;
1801
- if ('readOnly' in node) node.readOnly = flag(f, 'readonly');
1802
- node.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
1803
- if (t !== '') node.setAttribute('aria-label', t);
1804
- m.error!.textContent = err ?? '';
1805
- }
1806
-
1807
- function accepts(file: File, list: string[]): boolean {
1808
- if (list.length === 0) return true;
1809
- const name = file.name.toLowerCase();
1810
- const type = file.type.toLowerCase();
1811
- return list.some(x => x.includes('/')
1812
- ? (x.endsWith('/*') ? type.startsWith(x.slice(0, -1)) : type === x)
1813
- : name.endsWith(x.startsWith('.') ? x : `.${x}`));
1814
- }
1815
-
1816
- function chooseFiles(face: ObjectCell, files: File[]): void {
1817
- const list = acceptList(face);
1818
- const ok = files.filter(f => accepts(f, list));
1819
- const taken = flag(face, 'multiple') ? ok : ok.slice(0, 1);
1820
- const cells: Cell[] = [];
1821
- for (const f of taken) cells.push(string(f.name), int(f.size), string(f.type), fileHandle(f));
1822
- const refused = files.filter(f => !accepts(f, list)).map(f => string(f.name));
1823
- void fire('ui-files', face, blockOf(K.Block, cells), blockOf(K.Block, refused));
1824
- }
1825
-
1826
- /** A link as the page would follow it, relative ones too; null unless it is http or https. */
1827
- function webHref(url: string): string | null {
1828
- try {
1829
- const u = new URL(url, location.href);
1830
- return u.protocol === 'http:' || u.protocol === 'https:' ? u.href : null;
1831
- } catch {
1832
- return null;
1833
- }
1834
- }
1835
-
1836
- function syncUpload(m: Mounted, err: string | null): void {
1837
- const f = m.face;
1838
- const label = m.label!;
1839
- label.textContent = str(f, 'text') ?? '';
1840
- label.classList.toggle('tb-required', required(f));
1841
- const many = flag(f, 'multiple');
1842
- const choose = m.button!;
1843
- (choose.lastChild as HTMLElement).textContent = own(many ? 'choose-files' : 'choose-file');
1844
- const readonly = flag(f, 'readonly');
1845
- choose.disabled = flag(f, 'disabled') || readonly;
1846
- choose.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
1847
- const zone = choose.parentElement!;
1848
- // read only, there is nothing to choose: only the files are left
1849
- zone.hidden = readonly;
1850
- (zone.querySelector('.tb-upload-hint') as HTMLElement).textContent = own(many ? 'drop-files' : 'drop-file');
1851
- const picker = zone.querySelector('input') as HTMLInputElement;
1852
- picker.multiple = many;
1853
- picker.accept = pickerAccept(acceptList(f));
1854
- m.error!.textContent = err ?? '';
1855
- const v = get(f, 'value');
1856
- const files = v.t === K.Block ? v.s.data.slice(v.i).filter(x => x.t === K.Object) as ObjectCell[] : [];
1857
- const lang = activeLanguage(host.rt);
1858
- const items = files.map((file, i) => {
1859
- const li = el('li');
1860
- // a file kept elsewhere has a url: its name opens it, and an image shows itself small
1861
- const url = str(file, 'url');
1862
- const href = url !== null ? webHref(url) : null;
1863
- const name = el(href !== null ? 'a' : 'span', 'tb-upload-name');
1864
- name.textContent = str(file, 'name') ?? '';
1865
- if (name instanceof HTMLAnchorElement && href !== null) {
1866
- name.href = href;
1867
- name.target = '_blank';
1868
- name.rel = 'noopener';
1869
- }
1870
- if (href !== null && (str(file, 'type') ?? '').startsWith('image/')) {
1871
- const thumb = el('img', 'tb-upload-thumb');
1872
- thumb.src = href;
1873
- thumb.alt = '';
1874
- li.append(thumb);
1875
- }
1876
- const size = el('span', 'tb-upload-size');
1877
- const n = get(file, 'size');
1878
- size.textContent = n.t === K.Integer ? fileSize(Number(n.v), lang) : '';
1879
- if (readonly) {
1880
- li.append(name, size);
1881
- return li;
1882
- }
1883
- const remove = el('button', 'tb-upload-remove');
1884
- remove.type = 'button';
1885
- remove.disabled = choose.disabled;
1886
- remove.setAttribute('aria-label', own('remove-file', name.textContent ?? ''));
1887
- const x = icon('close');
1888
- if (x !== null) remove.append(x);
1889
- remove.addEventListener('click', () => {
1890
- choose.focus();
1891
- void fire('ui-remove-file', f, int(i + 1));
1892
- });
1893
- li.append(name, size, remove);
1894
- return li;
1895
- });
1896
- m.box!.replaceChildren(...items);
1897
- m.box!.hidden = items.length === 0;
1898
- syncSent(m);
1899
- }
1900
-
1901
- // A lookup: a field where the user types and chooses among what on-search finds, as in
1902
- // the WAI-ARIA combobox. Only one list is open at a time, in the top layer as a calendar.
1903
-
1904
- interface OpenLookup {
1905
- m: Mounted;
1906
- list: HTMLUListElement;
1907
- shown: Cell | null; // the options on show; null until the first answer
1908
- items: Cell[];
1909
- active: number;
1910
- }
1911
- let lookup: OpenLookup | null = null;
1912
- let lookupTimer: ReturnType<typeof setTimeout> | undefined;
1913
- const LOOKUP_WAIT_MS = 200;
1914
-
1915
- function lookupValues(f: ObjectCell): Cell[] {
1916
- const v = get(f, 'value');
1917
- return v.t === K.None ? [] : v.t === K.Block ? v.s.data.slice(v.i) : [v];
1918
- }
1919
-
1920
- function lookupText(f: ObjectCell, v: Cell): string {
1921
- const known = get(f, 'known');
1922
- const t = known.t === K.Map ? mapAt(known as MapCell, form(v)) : null;
1923
- return t !== null ? translate(t, host.rt) : form(v);
1924
- }
1925
-
1926
- /** Where a readonly lookup's value links to, from its `links` map, or null to show it as text. */
1927
- function lookupHref(f: ObjectCell, v: Cell): string | null {
1928
- const links = get(f, 'links');
1929
- if (!flag(f, 'readonly') || links.t !== K.Map) return null;
1930
- const to = mapAt(links as MapCell, form(v));
1931
- if (to === null) return null;
1932
- if (to.t === K.LitWord) return screenHref({ ...to, t: K.Word } as Cell);
1933
- if (to.t === K.LitPath) return screenHref({ ...to, t: K.Path } as Cell);
1934
- return screenHref(to) ?? (to.t === K.Url || to.t === K.File || to.t === K.String ? form(to) : null);
1935
- }
1936
-
1937
- function buildLookup(face: ObjectCell, m: Mounted): HTMLElement {
1938
- const id = `tb-${nextId++}`;
1939
- const wrap = el('div', 'tb-field');
1940
- const label = el('label', 'tb-label');
1941
- label.htmlFor = id;
1942
- const control = el('div', 'tb-control');
1943
- const box = el('div', 'tb-lookup');
1944
- const chosen = el('ul', 'tb-lookup-chosen');
1945
- const input = el('input', 'tb-input');
1946
- input.id = id;
1947
- input.type = 'text';
1948
- input.autocomplete = 'off';
1949
- input.setAttribute('role', 'combobox');
1950
- input.setAttribute('aria-autocomplete', 'list');
1951
- input.setAttribute('aria-expanded', 'false');
1952
- const name = word(face, 'name');
1953
- if (name !== null) input.name = name;
1954
- const error = el('div', 'tb-error');
1955
- error.id = `${id}-error`;
1956
- error.setAttribute('aria-live', 'polite');
1957
- input.setAttribute('aria-describedby', error.id);
1958
- input.addEventListener('click', () => {
1959
- if (lookup?.m !== m) openLookup(m, input, '');
1960
- });
1961
- input.addEventListener('input', () => {
1962
- if (lookup?.m !== m) openLookup(m, input, null);
1963
- clearTimeout(lookupTimer);
1964
- lookupTimer = setTimeout(() => void fire('ui-lookup-search', face, string(input.value)), LOOKUP_WAIT_MS);
1965
- });
1966
- input.addEventListener('keydown', ev => lookupKey(m, input, ev));
1967
- input.addEventListener('blur', () => {
1968
- closeLookup();
1969
- // what was typed is not a value: emptied, a lookup has none; else it goes back to what it had
1970
- if (input.readOnly) return;
1971
- const many = flag(face, 'multiple');
1972
- const emptied = !many && input.value === '' && get(face, 'value').t !== K.None;
1973
- if (emptied) void fire('ui-input', face, NONE);
1974
- else input.value = many ? '' : lookupValues(face).map(v => lookupText(face, v)).join('');
1975
- void fire('ui-blur', face);
1976
- });
1977
- box.append(chosen, input);
1978
- control.append(box, error);
1979
- wrap.append(label, control);
1980
- m.input = input;
1981
- m.label = label;
1982
- m.error = error;
1983
- m.box = chosen;
1984
- return wrap;
1985
- }
1986
-
1987
- function syncLookup(m: Mounted, err: string | null): void {
1988
- const f = m.face;
1989
- const input = m.input as HTMLInputElement;
1990
- const label = m.label!;
1991
- label.textContent = str(f, 'text') ?? '';
1992
- label.classList.toggle('tb-required', required(f));
1993
- const many = flag(f, 'multiple');
1994
- const readonly = flag(f, 'readonly');
1995
- const off = flag(f, 'disabled');
1996
- const values = lookupValues(f);
1997
- // readonly values with a link are shown as chips, so that each one is a real link
1998
- const chips = many || values.some(v => lookupHref(f, v) !== null);
1999
- input.readOnly = readonly;
2000
- input.disabled = off;
2001
- input.hidden = chips && readonly && values.length > 0;
2002
- input.setAttribute('aria-required', required(f) ? 'true' : 'false');
2003
- input.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
2004
- const hint = str(f, 'hint');
2005
- if (hint !== null) input.placeholder = hint;
2006
- m.error!.textContent = err ?? '';
2007
- if (chips) {
2008
- m.box!.replaceChildren(...values.map((v, i) => {
2009
- const li = el('li', 'tb-lookup-chip');
2010
- const href = lookupHref(f, v);
2011
- const shown = el(href !== null ? 'a' : 'span', href !== null ? 'tb-link' : '');
2012
- if (shown instanceof HTMLAnchorElement) shown.href = href!;
2013
- shown.textContent = lookupText(f, v);
2014
- li.append(shown);
2015
- if (!readonly && !off) {
2016
- const remove = el('button', 'tb-upload-remove');
2017
- remove.type = 'button';
2018
- remove.setAttribute('aria-label', own('remove-value', shown.textContent));
2019
- const x = icon('close');
2020
- if (x !== null) remove.append(x);
2021
- remove.addEventListener('click', () => {
2022
- input.focus();
2023
- void fire('ui-lookup-remove', f, int(i + 1));
2024
- });
2025
- li.append(remove);
2026
- }
2027
- return li;
2028
- }));
2029
- } else {
2030
- // a single value loses its chip when it stops being readonly or linked
2031
- m.box!.replaceChildren();
2032
- const want = values.map(v => lookupText(f, v)).join('');
2033
- if (document.activeElement !== input && input.value !== want) input.value = want;
2034
- }
2035
- if (lookup?.m === m) renderLookup();
2036
- }
2037
-
2038
- function openLookup(m: Mounted, input: HTMLInputElement, query: string | null): void {
2039
- if (input.readOnly || input.disabled) return;
2040
- closeLookup();
2041
- const list = el('ul', 'tb-lookup-list');
2042
- list.id = `tb-${nextId++}`;
2043
- list.setAttribute('role', 'listbox');
2044
- list.setAttribute('popover', 'manual');
2045
- // choosing with the pointer must not take the focus away from the field
2046
- list.addEventListener('pointerdown', ev => ev.preventDefault());
2047
- lookup = { m, list, shown: null, items: [], active: -1 };
2048
- input.setAttribute('aria-expanded', 'true');
2049
- input.setAttribute('aria-controls', list.id);
2050
- // a modal dialog makes all outside it inert: there, a list in the body would take no clicks
2051
- (input.closest('dialog') ?? document.body).append(list);
2052
- list.showPopover?.();
2053
- placeLookup();
2054
- if (query !== null) void fire('ui-lookup-search', m.face, string(query));
2055
- }
2056
-
2057
- function placeLookup(): void {
2058
- if (lookup === null) return;
2059
- const { list, m } = lookup;
2060
- const r = m.input!.getBoundingClientRect();
2061
- list.style.width = `${r.width}px`;
2062
- list.style.left = `${r.left}px`;
2063
- const height = list.getBoundingClientRect().height;
2064
- list.style.top = `${r.bottom + 4 + height > innerHeight - 8 ? Math.max(8, r.top - 4 - height) : r.bottom + 4}px`;
2065
- }
2066
-
2067
- function closeLookup(): void {
2068
- clearTimeout(lookupTimer);
2069
- if (lookup === null) return;
2070
- const { list, m } = lookup;
2071
- lookup = null;
2072
- list.hidePopover?.();
2073
- list.remove();
2074
- m.input!.setAttribute('aria-expanded', 'false');
2075
- m.input!.removeAttribute('aria-controls');
2076
- m.input!.removeAttribute('aria-activedescendant');
2077
- }
2078
-
2079
- function renderLookup(): void {
2080
- if (lookup === null) return;
2081
- const open = lookup;
2082
- const options = get(open.m.face, 'options');
2083
- // what is on show stays until the search answers; a query still on its way shows nothing new
2084
- if (options.t !== K.Block || options === open.shown) return;
2085
- if (open.shown === null && get(open.m.face, 'query').t === K.None) return;
2086
- open.shown = options;
2087
- const taken = new Set(flag(open.m.face, 'multiple') ? lookupValues(open.m.face).map(v => form(v)) : []);
2088
- open.items = optionsOf(open.m.face).filter(o => !taken.has(optionValue(o)));
2089
- open.active = -1;
2090
- open.list.replaceChildren(...open.items.map((o, i) => {
2091
- const li = el('li', 'tb-lookup-option');
2092
- li.id = `${open.list.id}-${i}`;
2093
- li.setAttribute('role', 'option');
2094
- li.setAttribute('aria-selected', 'false');
2095
- li.textContent = optionText(o);
2096
- li.addEventListener('click', () => pickLookup(o));
2097
- return li;
2098
- }));
2099
- if (open.items.length === 0) {
2100
- const none = el('li', 'tb-lookup-none');
2101
- none.textContent = own('no-matches');
2102
- open.list.append(none);
2103
- }
2104
- placeLookup();
2105
- }
2106
-
2107
- function pickLookup(option: Cell): void {
2108
- if (lookup === null) return;
2109
- const { m } = lookup;
2110
- const input = m.input as HTMLInputElement;
2111
- closeLookup();
2112
- input.value = flag(m.face, 'multiple') ? '' : optionText(option);
2113
- void fire('ui-lookup-pick', m.face, option);
2114
- }
2115
-
2116
- function moveLookup(by: number): void {
2117
- if (lookup === null || lookup.items.length === 0) return;
2118
- const { list, items, m } = lookup;
2119
- const at = lookup.active < 0 && by < 0 ? items.length - 1 : (lookup.active + by + items.length) % items.length;
2120
- list.children[lookup.active]?.setAttribute('aria-selected', 'false');
2121
- lookup.active = at;
2122
- const li = list.children[at]!;
2123
- li.setAttribute('aria-selected', 'true');
2124
- li.scrollIntoView({ block: 'nearest' });
2125
- m.input!.setAttribute('aria-activedescendant', li.id);
2126
- }
2127
-
2128
- function lookupKey(m: Mounted, input: HTMLInputElement, ev: KeyboardEvent): void {
2129
- const open = lookup?.m === m;
2130
- const stop = (): void => { ev.preventDefault(); ev.stopPropagation(); };
2131
- switch (ev.key) {
2132
- case 'ArrowDown': case 'ArrowUp':
2133
- stop();
2134
- if (open) moveLookup(ev.key === 'ArrowDown' ? 1 : -1);
2135
- else openLookup(m, input, '');
2136
- break;
2137
- case 'Enter':
2138
- if (!open) break;
2139
- // with its list open, Enter chooses: it never sends the form
2140
- stop();
2141
- if (lookup!.active >= 0) pickLookup(lookup!.items[lookup!.active]!);
2142
- break;
2143
- case 'Escape':
2144
- if (open) { stop(); closeLookup(); }
2145
- break;
2146
- case 'Backspace':
2147
- if (flag(m.face, 'multiple') && input.value === '' && !input.readOnly) {
2148
- const n = lookupValues(m.face).length;
2149
- if (n > 0) void fire('ui-lookup-remove', m.face, int(n));
2150
- }
2151
- break;
2152
- }
2153
- }
2154
-
2155
- function buildProgress(m: Mounted): HTMLElement {
2156
- const wrap = el('div', 'tb-progress-wrap');
2157
- const label = el('span', 'tb-progress-label');
2158
- label.id = `tb-${nextId++}`;
2159
- const track = el('div', 'tb-progress');
2160
- track.setAttribute('role', 'progressbar');
2161
- track.setAttribute('aria-valuemin', '0');
2162
- track.setAttribute('aria-valuemax', '100');
2163
- track.append(el('div', 'tb-progress-bar'));
2164
- wrap.append(label, track);
2165
- m.label = label;
2166
- m.box = track;
2167
- return wrap;
2168
- }
2169
-
2170
- /** A progress value as a fraction, or null while it is unknown. */
2171
- function fraction(v: Cell): number | null {
2172
- const n = v.t === K.Percent || v.t === K.Decimal ? v.v : v.t === K.Integer ? Number(v.v) : null;
2173
- return n === null || Number.isNaN(n) ? null : Math.min(1, Math.max(0, n));
2174
- }
2175
-
2176
- function syncProgress(m: Mounted): void {
2177
- const t = str(m.face, 'text');
2178
- const label = m.label!;
2179
- label.textContent = t ?? '';
2180
- label.hidden = t === null;
2181
- const track = m.box!;
2182
- if (t !== null) track.setAttribute('aria-labelledby', label.id);
2183
- else track.removeAttribute('aria-labelledby');
2184
- const n = fraction(get(m.face, 'value'));
2185
- track.classList.toggle('tb-indeterminate', n === null);
2186
- const bar = track.firstChild as HTMLElement;
2187
- if (n === null) {
2188
- track.removeAttribute('aria-valuenow');
2189
- bar.style.removeProperty('width');
2190
- } else {
2191
- track.setAttribute('aria-valuenow', String(Math.round(n * 100)));
2192
- bar.style.width = `${n * 100}%`;
2193
- }
2194
- }
2195
-
2196
- // --- drawings and charts ---------------------------------------------------------------
2197
-
2198
- const SVG_NS = 'http://www.w3.org/2000/svg';
2199
-
2200
- function svgNode(e: El): SVGElement {
2201
- const n = document.createElementNS(SVG_NS, e.tag);
2202
- for (const [k, v] of Object.entries(e.attrs)) n.setAttribute(k, v);
2203
- if (e.text !== undefined) n.textContent = e.text;
2204
- for (const k of e.kids) n.append(svgNode(k));
2205
- return n;
2206
- }
2207
-
2208
- /** A canvas: one SVG whose viewBox is the canvas's extent, as wide as it fits up to that. */
2209
- function buildCanvas(m: Mounted): HTMLElement {
2210
- const node = el('div', 'tb-canvas');
2211
- const svg = document.createElementNS(SVG_NS, 'svg');
2212
- node.append(svg);
2213
- m.kids = svg;
2214
- return node;
2215
- }
2216
-
2217
- function syncCanvas(m: Mounted): void {
2218
- const svg = m.kids as SVGSVGElement;
2219
- const ext = get(m.face, 'extent');
2220
- const [w, h] = ext.t === K.Pair ? [ext.x, ext.y] : [300, 150];
2221
- svg.setAttribute('viewBox', `0 0 ${w} ${h}`);
2222
- svg.setAttribute('width', String(w));
2223
- svg.setAttribute('height', String(h));
2224
- // with a text, the drawing is a picture with that name; without, it is decoration
2225
- const t = str(m.face, 'text');
2226
- if (t !== null) {
2227
- svg.setAttribute('role', 'img');
2228
- svg.setAttribute('aria-label', t);
2229
- svg.removeAttribute('aria-hidden');
2230
- } else {
2231
- svg.removeAttribute('role');
2232
- svg.removeAttribute('aria-label');
2233
- svg.setAttribute('aria-hidden', 'true');
2234
- }
2235
- const { kids, error } = drawSvg(get(m.face, 'draw'));
2236
- if (error !== null) console.warn(`Trebol: ${error}`);
2237
- svg.replaceChildren(...kids.map(svgNode));
2238
- }
2239
-
2240
- interface ChartParts { caption: HTMLElement; plot: HTMLElement; svg: SVGSVGElement; legend: HTMLElement; table: HTMLTableElement; empty: HTMLElement; width: number }
2241
-
2242
- const CHART_HEIGHT: Record<string, number> = { small: 160, medium: 240, large: 360 };
2243
-
2244
- /**
2245
- * A chart: its text as a caption, the plot, a legend, and the same numbers as a
2246
- * table that only a screen reader reads. It is drawn at the width it gets, and
2247
- * again when that changes, so its text stays the size of the page's.
2248
- */
2249
- function buildChart(m: Mounted): HTMLElement {
2250
- const node = el('figure', 'tb-chart');
2251
- const caption = el('figcaption', 'tb-chart-caption');
2252
- const plot = el('div', 'tb-chart-plot');
2253
- const svg = document.createElementNS(SVG_NS, 'svg');
2254
- svg.setAttribute('aria-hidden', 'true');
2255
- plot.append(svg);
2256
- const legend = el('ul', 'tb-chart-legend');
2257
- const table = el('table', 'tb-sr-only') as HTMLTableElement;
2258
- const empty = el('p', 'tb-chart-empty');
2259
- node.append(caption, plot, legend, empty, table);
2260
- const parts: ChartParts = { caption, plot, svg, legend, table, empty, width: 0 };
2261
- m.kids = parts;
2262
- if (typeof ResizeObserver !== 'undefined') {
2263
- new ResizeObserver(() => {
2264
- if (plot.clientWidth !== parts.width) drawChart(m);
2265
- }).observe(plot);
2266
- }
2267
- return node;
2268
- }
2269
-
2270
- /** A cell of a chart as a number, or null. */
2271
- function chartNumber(v: Cell): number | null {
2272
- if (v.t === K.Integer) return Number(v.v);
2273
- if (v.t === K.Decimal || v.t === K.Percent) return v.v;
2274
- if (v.t === K.Money) return decToNumber(v.v);
2275
- return null;
2276
- }
2277
-
2278
- /** How a number of the chart shows: as the values it stands for, money as money and percent as percent. */
2279
- function chartFormat(sample: Cell | null): (n: number) => string {
2280
- return n => {
2281
- if (sample !== null && sample.t === K.Money) {
2282
- const d = decFromNumber(Math.round(n * 100) / 100);
2283
- if (d !== null) return display(money(d, sample.cur));
2284
- }
2285
- if (sample !== null && sample.t === K.Percent) return display({ t: K.Percent, v: n });
2286
- return display(Number.isInteger(n) ? { t: K.Integer, v: n } : { t: K.Decimal, v: n });
2287
- };
2288
- }
2289
-
2290
- function syncChart(m: Mounted): void {
2291
- const p = m.kids as ChartParts;
2292
- const t = str(m.face, 'text');
2293
- p.caption.textContent = t ?? '';
2294
- p.caption.hidden = t === null;
2295
- drawChart(m);
2296
- }
2297
-
2298
- function drawChart(m: Mounted): void {
2299
- const f = m.face;
2300
- const p = m.kids as ChartParts;
2301
- const cols = columns(f);
2302
- const data = get(f, 'data');
2303
- const rows = data.t === K.Block ? data.s.data.slice(data.i) : [];
2304
- const kind = (word(f, 'kind') ?? 'bar') as ChartKind;
2305
- const labels = rows.map(r => cellText(rowField(r, cols[0]?.sym ?? intern('label'))));
2306
- let sample: Cell | null = null;
2307
- const series: Series[] = cols.slice(1).map((c, k) => ({
2308
- name: c.label,
2309
- color: SERIES_COLORS[k % SERIES_COLORS.length]!,
2310
- values: rows.map(r => {
2311
- const v = rowField(r, c.sym);
2312
- const n = chartNumber(v);
2313
- if (n !== null && sample === null) sample = v;
2314
- return n;
2315
- }),
2316
- }));
2317
- const format = chartFormat(sample);
2318
- const nothing = rows.length === 0 || series.length === 0;
2319
- p.empty.hidden = !nothing;
2320
- p.plot.hidden = nothing;
2321
- if (nothing) {
2322
- p.empty.textContent = own('empty');
2323
- p.legend.replaceChildren();
2324
- p.table.replaceChildren();
2325
- return;
2326
- }
2327
- const width = p.plot.clientWidth || 600;
2328
- const height = CHART_HEIGHT[word(f, 'size') ?? 'medium'] ?? 240;
2329
- p.width = p.plot.clientWidth;
2330
- // no width of its own: it takes the plot's, so it never widens what holds it
2331
- p.svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
2332
- p.svg.replaceChildren(...chartSvg({ kind, labels, series, stacked: flag(f, 'stacked'), width, height, format }).map(svgNode));
2333
- // the legend names the series, or a pie's slices
2334
- const keys = kind === 'pie' ? labels.map((l, i) => [l, pieColor(i)] as const) : series.length > 1 ? series.map(s => [s.name, s.color] as const) : [];
2335
- p.legend.replaceChildren(...keys.map(([name, color]) => {
2336
- const li = el('li', 'tb-chart-key');
2337
- const swatch = el('span', 'tb-chart-swatch');
2338
- swatch.style.setProperty('--tb-swatch', color);
2339
- li.append(swatch, name);
2340
- return li;
2341
- }));
2342
- p.legend.hidden = keys.length === 0;
2343
- // the same numbers for a screen reader
2344
- const cap = el('caption');
2345
- cap.textContent = str(f, 'text') ?? '';
2346
- const head = el('tr');
2347
- for (const c of cols) {
2348
- const th = el('th');
2349
- th.textContent = c.label;
2350
- head.append(th);
2351
- }
2352
- const body = rows.map(r => {
2353
- const tr = el('tr');
2354
- for (const c of cols) {
2355
- const td = el('td');
2356
- td.textContent = cellText(rowField(r, c.sym));
2357
- tr.append(td);
2358
- }
2359
- return tr;
2360
- });
2361
- p.table.replaceChildren(cap, el('thead'), el('tbody'));
2362
- p.table.tHead!.append(head);
2363
- p.table.tBodies[0]!.append(...body);
2364
- }
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
-
2777
-
2778
- function syncIcon(m: Mounted): void {
2779
- const name = iconName(m.face) ?? '';
2780
- const label = str(m.face, 'text');
2781
- const key = `${name} ${label ?? ''}`;
2782
- if (m.el.dataset['icon'] === key) return;
2783
- m.el.dataset['icon'] = key;
2784
- const svg = name !== '' ? icon(name, label) : null;
2785
- m.el.replaceChildren(...(svg !== null ? [svg] : []));
2786
- }
2787
-
2788
- /** No rule applies to a read-only face, so it never asks for a value. */
2789
- function required(f: ObjectCell): boolean {
2790
- return hasRule(f, 'required') && !flag(f, 'readonly');
2791
- }
2792
-
2793
- function syncRadio(m: Mounted, err: string | null): void {
2794
- const f = m.face;
2795
- m.label!.textContent = str(f, 'text') ?? '';
2796
- m.label!.classList.toggle('tb-required', required(f));
2797
- const v = get(f, 'value');
2798
- const want = v.t === K.None ? null : form(v);
2799
- for (const r of m.radios!) {
2800
- r.checked = r.value === want;
2801
- r.disabled = flag(f, 'disabled') || flag(f, 'readonly');
2802
- }
2803
- const group = m.radios![0]?.closest('[role="radiogroup"]');
2804
- group?.querySelectorAll('.tb-radio-title').forEach((t, i) => {
2805
- const g = entriesOf(f).filter(isGroup)[i];
2806
- if (g) t.textContent = translate(g.title, host.rt);
2807
- });
2808
- group?.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
2809
- group?.setAttribute('aria-required', required(f) ? 'true' : 'false');
2810
- m.error!.textContent = err ?? '';
2811
- }
2812
-
2813
- // --- rows ---------------------------------------------------------------------------
2814
- //
2815
- // The dialect makes the rows as faces; the host only draws them, as one line each
2816
- // with the labels of the first line as the headers, or as cards on narrow screens.
2817
-
2818
- function buildRowsField(m: Mounted): HTMLElement {
2819
- const id = `tb-${nextId++}`;
2820
- const wrap = el('div', 'tb-field');
2821
- const label = el('div', 'tb-label');
2822
- label.id = id;
2823
- const control = el('div', 'tb-control');
2824
- const box = el('div', 'tb-rows');
2825
- box.setAttribute('role', 'group');
2826
- box.setAttribute('aria-labelledby', id);
2827
- const error = el('div', 'tb-error');
2828
- error.setAttribute('aria-live', 'polite');
2829
- control.append(box, error);
2830
- wrap.append(label, control);
2831
- m.label = label;
2832
- m.error = error;
2833
- m.box = box;
2834
- return wrap;
2835
- }
2836
-
2837
- function syncRowsField(m: Mounted, err: string | null): void {
2838
- const f = m.face;
2839
- m.label!.textContent = str(f, 'text') ?? '';
2840
- m.label!.classList.toggle('tb-required', required(f));
2841
- m.error!.textContent = err ?? '';
2842
- // code gave it a new value or changed its flags: the dialect makes the rows again
2843
- const v = get(f, 'value');
2844
- const now = [v.t === K.Block ? v.s : null, flag(f, 'readonly'), flag(f, 'disabled')];
2845
- const was = m.shown as unknown[] | undefined;
2846
- if (was === undefined || now.some((x, i) => x !== was[i])) {
2847
- m.shown = now;
2848
- void fire('ui-rows', f);
2849
- }
2850
- }
2851
-
2852
- /** Puts the rows in their new order, keeping the nodes (and the focus) of the ones that stay. */
2853
- function placeEntries(m: Mounted): void {
2854
- const box = m.box!;
2855
- const faces = children(m.face);
2856
- const active = document.activeElement;
2857
- const fresh: HTMLElement[] = [];
2858
- const nodes = faces.map(c => {
2859
- const old = byCtx.get(c.ctx);
2860
- if (old !== undefined && old.el.parentElement === box) return old.el;
2861
- const n = build(c);
2862
- fresh.push(n);
2863
- return n;
2864
- });
2865
- let cursor = box.firstChild;
2866
- for (const n of nodes) {
2867
- if (n === cursor) cursor = cursor.nextSibling;
2868
- else box.insertBefore(n, cursor);
2869
- }
2870
- while (cursor !== null) {
2871
- const next = cursor.nextSibling;
2872
- box.removeChild(cursor);
2873
- cursor = next;
2874
- }
2875
- const add = nodes[nodes.length - 1];
2876
- // the button pressed went away with its row, or a row was just added
2877
- if (active !== null && active !== document.body && !active.isConnected) (add as HTMLElement | undefined)?.focus();
2878
- else if (fresh.length === 1 && (active === add || active === document.body)) {
2879
- fresh[0]!.querySelector<HTMLElement>('input, textarea, select, [contenteditable="true"]')?.focus();
2880
- }
2881
- }
2882
-
2883
- // --- rich text -----------------------------------------------------------------------
2884
- //
2885
- // An editable box whose value is Markdown (see markdown.ts). The box is drawn from
2886
- // the tree with text nodes and read back the same way; pasting takes only the text.
2887
-
2888
- const RICH_TOOLS: readonly [string, string][] = [
2889
- ['bold', 'bold'], ['italic', 'italic'], ['heading', 'heading'],
2890
- ['list', 'bullet-list'], ['list-ordered', 'number-list'], ['link', 'link'],
2891
- ];
2892
-
2893
- function inlineNodes(items: Inline[]): Node[] {
2894
- return items.flatMap((x): Node[] => {
2895
- switch (x.k) {
2896
- case 'text': return [document.createTextNode(x.text)];
2897
- case 'br': return [el('br')];
2898
- case 'b': case 'i': {
2899
- const e = el(x.k);
2900
- e.append(...inlineNodes(x.kids));
2901
- return [e];
2902
- }
2903
- case 'a': {
2904
- if (!safeHref(x.href)) return inlineNodes(x.kids);
2905
- const a = el('a');
2906
- a.href = x.href;
2907
- a.rel = 'noopener noreferrer';
2908
- a.target = '_blank';
2909
- a.append(...inlineNodes(x.kids));
2910
- return [a];
2911
- }
2912
- }
2913
- });
2914
- }
2915
-
2916
- function blockNodes(blocks: Block[]): Node[] {
2917
- return blocks.map(b => {
2918
- if (b.k === 'p' || b.k === 'h') {
2919
- const e = b.k === 'p' ? el('p') : el(`h${b.level}` as 'h1' | 'h2' | 'h3');
2920
- e.append(...inlineNodes(b.kids));
2921
- return e;
2922
- }
2923
- const list = el(b.k);
2924
- for (const item of b.items) {
2925
- const li = el('li');
2926
- li.append(...inlineNodes(item));
2927
- list.append(li);
2928
- }
2929
- return list;
2930
- });
2931
- }
2932
-
2933
- function readInline(nodes: Iterable<Node>): Inline[] {
2934
- const out: Inline[] = [];
2935
- for (const n of nodes) {
2936
- if (n.nodeType === Node.TEXT_NODE) {
2937
- const t = (n.textContent ?? '').replace(/\u00a0/g, ' ').replace(/[\n\r]+/g, ' ');
2938
- const last = out[out.length - 1];
2939
- if (t === '') continue;
2940
- if (last?.k === 'text') last.text += t;
2941
- else out.push({ k: 'text', text: t });
2942
- } else if (n instanceof HTMLElement) {
2943
- const kids = readInline(n.childNodes);
2944
- switch (n.tagName) {
2945
- case 'BR': out.push({ k: 'br' }); break;
2946
- case 'B': case 'STRONG': if (kids.length > 0) out.push({ k: 'b', kids }); break;
2947
- case 'I': case 'EM': if (kids.length > 0) out.push({ k: 'i', kids }); break;
2948
- case 'A': if (kids.length > 0) out.push({ k: 'a', href: n.getAttribute('href') ?? '', kids }); break;
2949
- default: out.push(...kids);
2950
- }
2951
- }
2952
- }
2953
- // the browser ends an empty or last line with a <br> that shows nothing
2954
- while (out[out.length - 1]?.k === 'br') out.pop();
2955
- return out;
2956
- }
2957
-
2958
- const RICH_BLOCK = /^(P|DIV|H[1-6]|UL|OL|BLOCKQUOTE|SECTION)$/;
2959
-
2960
- function readBlocks(box: HTMLElement): Block[] {
2961
- const out: Block[] = [];
2962
- let loose: Node[] = [];
2963
- const flush = (): void => {
2964
- const kids = readInline(loose);
2965
- if (kids.length > 0) out.push({ k: 'p', kids });
2966
- loose = [];
2967
- };
2968
- for (const n of box.childNodes) {
2969
- if (!(n instanceof HTMLElement) || !RICH_BLOCK.test(n.tagName)) {
2970
- loose.push(n);
2971
- continue;
2972
- }
2973
- flush();
2974
- if (n.tagName === 'UL' || n.tagName === 'OL') {
2975
- const items = [...n.children].map(li => readInline(li.childNodes)).filter(x => x.length > 0);
2976
- if (items.length > 0) out.push({ k: n.tagName === 'UL' ? 'ul' : 'ol', items });
2977
- } else if (n.tagName === 'DIV' || n.tagName === 'SECTION' || n.tagName === 'BLOCKQUOTE') {
2978
- out.push(...readBlocks(n));
2979
- } else {
2980
- const kids = readInline(n.childNodes);
2981
- if (kids.length === 0) continue;
2982
- if (n.tagName === 'P') out.push({ k: 'p', kids });
2983
- else out.push({ k: 'h', level: Math.min(3, Number(n.tagName[1])), kids });
2984
- }
2985
- }
2986
- flush();
2987
- return out;
2988
- }
2989
-
2990
- function buildRich(face: ObjectCell, m: Mounted): HTMLElement {
2991
- const id = `tb-${nextId++}`;
2992
- const wrap = el('div', 'tb-field');
2993
- const label = el('div', 'tb-label');
2994
- label.id = id;
2995
- const control = el('div', 'tb-control');
2996
- const shell = el('div', 'tb-rich');
2997
- const tools = el('div', 'tb-rich-tools');
2998
- tools.setAttribute('role', 'toolbar');
2999
- const box = el('div', 'tb-input tb-rich-box');
3000
- box.setAttribute('role', 'textbox');
3001
- box.setAttribute('aria-multiline', 'true');
3002
- box.setAttribute('aria-labelledby', id);
3003
- const linkRow = el('div', 'tb-rich-link');
3004
- linkRow.hidden = true;
3005
- const linkInput = el('input', 'tb-input');
3006
- linkInput.type = 'url';
3007
- const linkOk = el('button', 'tb-button tb-small');
3008
- linkOk.type = 'button';
3009
- linkRow.append(linkInput, linkOk);
3010
- const error = el('div', 'tb-error');
3011
- error.id = `${id}-error`;
3012
- error.setAttribute('aria-live', 'polite');
3013
- box.setAttribute('aria-describedby', error.id);
3014
- label.addEventListener('click', () => box.focus());
3015
- keepCarets();
3016
-
3017
- const changed = (): void => {
3018
- if (inserting) return;
3019
- const md = printMd(readBlocks(box));
3020
- if (md === m.shown) return;
3021
- m.shown = md;
3022
- void fire('ui-input', face, md === '' ? NONE : string(md));
3023
- };
3024
- box.addEventListener('input', changed);
3025
- box.addEventListener('paste', ev => {
3026
- ev.preventDefault();
3027
- document.execCommand('insertText', false, ev.clipboardData?.getData('text/plain') ?? '');
3028
- });
3029
- box.addEventListener('drop', ev => ev.preventDefault());
3030
- wrap.addEventListener('focusout', ev => {
3031
- if (!wrap.contains(ev.relatedTarget as Node | null) && !inDevtools(ev.relatedTarget)) void fire('ui-blur', face);
3032
- });
3033
-
3034
- let saved: Range | null = null;
3035
- const inHeading = (): boolean => {
3036
- const n = getSelection()?.anchorNode ?? null;
3037
- return (n instanceof Element ? n : n?.parentElement)?.closest('h1, h2, h3') != null;
3038
- };
3039
- const command = (what: string): void => {
3040
- box.focus();
3041
- switch (what) {
3042
- case 'bold': case 'italic': document.execCommand(what); break;
3043
- case 'heading': document.execCommand('formatBlock', false, inHeading() ? 'P' : 'H2'); break;
3044
- case 'bullet-list': document.execCommand('insertUnorderedList'); break;
3045
- case 'number-list': document.execCommand('insertOrderedList'); break;
3046
- case 'link': {
3047
- const s = getSelection();
3048
- saved = s !== null && s.rangeCount > 0 && box.contains(s.anchorNode) ? s.getRangeAt(0).cloneRange() : null;
3049
- linkRow.hidden = false;
3050
- linkInput.value = '';
3051
- linkInput.removeAttribute('aria-invalid');
3052
- linkInput.focus();
3053
- return;
3054
- }
3055
- }
3056
- changed();
3057
- };
3058
- for (const [name, what] of RICH_TOOLS) {
3059
- const b = el('button', 'tb-rich-tool');
3060
- b.type = 'button';
3061
- b.dataset['tool'] = what;
3062
- const svg = icon(name);
3063
- if (svg !== null) b.append(svg);
3064
- // pressing a tool keeps the selection in the text
3065
- b.addEventListener('mousedown', ev => ev.preventDefault());
3066
- b.addEventListener('click', () => command(what));
3067
- tools.append(b);
3068
- }
3069
- const addLink = (): void => {
3070
- const typed = linkInput.value.trim();
3071
- const url = /^[a-z][a-z0-9+.-]*:/i.test(typed) ? typed : `https://${typed}`;
3072
- if (typed === '' || !safeHref(url)) {
3073
- linkInput.setAttribute('aria-invalid', 'true');
3074
- return;
3075
- }
3076
- linkRow.hidden = true;
3077
- box.focus();
3078
- const s = getSelection();
3079
- if (saved !== null && s !== null) {
3080
- s.removeAllRanges();
3081
- s.addRange(saved);
3082
- }
3083
- if (saved === null || saved.collapsed) document.execCommand('insertText', false, typed);
3084
- if (saved !== null && !saved.collapsed) document.execCommand('createLink', false, url);
3085
- else {
3086
- // what was just typed becomes the link
3087
- const r = getSelection()?.getRangeAt(0);
3088
- if (r !== undefined) {
3089
- const node = r.startContainer;
3090
- const start = Math.max(0, r.startOffset - typed.length);
3091
- const whole = document.createRange();
3092
- whole.setStart(node, start);
3093
- whole.setEnd(node, r.startOffset);
3094
- s?.removeAllRanges();
3095
- s?.addRange(whole);
3096
- document.execCommand('createLink', false, url);
3097
- }
3098
- }
3099
- changed();
3100
- };
3101
- linkOk.addEventListener('click', addLink);
3102
- linkInput.addEventListener('keydown', ev => {
3103
- if (ev.key === 'Enter') {
3104
- ev.preventDefault();
3105
- addLink();
3106
- } else if (ev.key === 'Escape') {
3107
- ev.stopPropagation();
3108
- linkRow.hidden = true;
3109
- box.focus();
3110
- }
3111
- });
3112
- shell.append(tools, linkRow, box);
3113
- control.append(shell, error);
3114
- wrap.append(label, control);
3115
- m.label = label;
3116
- m.error = error;
3117
- m.box = box;
3118
- return wrap;
3119
- }
3120
-
3121
- function syncRich(m: Mounted, err: string | null): void {
3122
- const f = m.face;
3123
- const box = m.box!;
3124
- m.label!.textContent = str(f, 'text') ?? '';
3125
- m.label!.classList.toggle('tb-required', required(f));
3126
- const shell = box.parentElement!;
3127
- const readonly = flag(f, 'readonly');
3128
- const disabled = flag(f, 'disabled');
3129
- const locked = readonly || disabled;
3130
- box.contentEditable = locked ? 'false' : 'true';
3131
- box.tabIndex = disabled ? -1 : 0;
3132
- box.setAttribute('aria-readonly', locked ? 'true' : 'false');
3133
- box.setAttribute('aria-disabled', disabled ? 'true' : 'false');
3134
- box.setAttribute('aria-required', required(f) ? 'true' : 'false');
3135
- box.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
3136
- const tools = shell.querySelector<HTMLElement>('.tb-rich-tools')!;
3137
- tools.hidden = locked;
3138
- tools.setAttribute('aria-label', str(f, 'text') ?? '');
3139
- for (const b of tools.querySelectorAll<HTMLButtonElement>('button')) {
3140
- const name = own(b.dataset['tool']!);
3141
- b.setAttribute('aria-label', name);
3142
- b.title = name;
3143
- }
3144
- const linkRow = shell.querySelector<HTMLElement>('.tb-rich-link')!;
3145
- if (locked) linkRow.hidden = true;
3146
- linkRow.querySelector('input')!.placeholder = own('link-url');
3147
- linkRow.querySelector('button')!.textContent = own('link-add');
3148
- m.error!.textContent = err ?? '';
3149
- // never fight the user's typing: only what code set is drawn again
3150
- const md = str(f, 'value') ?? '';
3151
- if (md !== m.shown && document.activeElement !== box) {
3152
- m.shown = md;
3153
- box.replaceChildren(...blockNodes(parseMd(md)));
3154
- richCaret.delete(box);
3155
- }
3156
- }
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
-
3222
- // --- tables and lists ---------------------------------------------------------------
3223
-
3224
- /** A column; `image` when it shows each row's picture, `round` when cut to a circle. */
3225
- interface Column { sym: Sym; word: Cell; label: string; image: boolean; round: boolean }
3226
-
3227
- function columns(face: ObjectCell): Column[] {
3228
- const c = get(face, 'columns');
3229
- if (c.t !== K.Block) return [];
3230
- const out: Column[] = [];
3231
- const d = c.s.data;
3232
- for (let i = c.i; i + 1 < d.length; i += 2) {
3233
- const w = d[i]!;
3234
- if (w.t !== K.Word) continue;
3235
- // a column of images keeps its label in a block with what it is: ["Photo" image round]
3236
- const spec = d[i + 1]!;
3237
- const parts = spec.t === K.Block ? (spec as BlockCell).s.data.slice((spec as BlockCell).i) : [spec];
3238
- const has = (name: string): boolean => parts.some(p => p.t === K.Word && canon((p as WordCell).sym) === canon(intern(name)));
3239
- out.push({ sym: (w as WordCell).sym, word: w, label: translate(parts[0] ?? NONE, host.rt), image: has('image'), round: has('round') });
3240
- }
3241
- return out;
3242
- }
3243
-
3244
- /** The picture of a row in a column of images, from an address or a file; without one, an empty place for it. */
3245
- function thumb(box: Element, v: Cell, round: boolean): void {
3246
- const src = v.t === K.String || v.t === K.Url || v.t === K.File ? form(v) : '';
3247
- const old = box.querySelector<HTMLElement>(':scope > .tb-thumb');
3248
- let pic = old;
3249
- if (src === '' ? pic?.tagName !== 'SPAN' : pic?.tagName !== 'IMG') {
3250
- // decoration: the row's text says who or what it is
3251
- pic = el(src === '' ? 'span' : 'img', 'tb-thumb');
3252
- if (src !== '') (pic as HTMLImageElement).alt = '';
3253
- if (old !== null) old.replaceWith(pic);
3254
- else box.prepend(pic);
3255
- }
3256
- if (src !== '' && pic!.getAttribute('src') !== src) (pic as HTMLImageElement).src = src;
3257
- pic!.classList.toggle('tb-round', round);
3258
- }
3259
-
3260
- function sameRow(a: Cell, b: Cell): boolean {
3261
- if (a.t === K.Map && b.t === K.Map) return a.s === b.s;
3262
- if (a.t === K.Object && b.t === K.Object) return a.ctx === b.ctx;
3263
- return false;
3264
- }
3265
-
3266
- function cellText(v: Cell): string {
3267
- if (v.t === K.None) return '';
3268
- if (v.t === K.Logic) return own(v.v ? 'yes' : 'no');
3269
- return display(v);
3270
- }
3271
-
3272
- const NUMERIC: ReadonlySet<number> = new Set([K.Integer, K.Decimal, K.Money, K.Percent]);
3273
-
3274
- function buildRows(face: ObjectCell, style: string, m: Mounted): HTMLElement {
3275
- const wrap = el('div', style === 'table' ? 'tb-table-wrap' : 'tb-list-wrap');
3276
- let box: HTMLElement;
3277
- if (style === 'table') {
3278
- // explicit roles keep the table semantics when narrow screens restyle it as cards
3279
- const table = el('table', 'tb-table');
3280
- table.setAttribute('role', 'table');
3281
- const head = el('thead');
3282
- const tr = el('tr');
3283
- tr.setAttribute('role', 'row');
3284
- const cols = columns(face);
3285
- for (const c of cols) {
3286
- const th = el('th');
3287
- th.scope = 'col';
3288
- th.setAttribute('role', 'columnheader');
3289
- tr.append(th);
3290
- }
3291
- head.append(tr);
3292
- head.addEventListener('click', ev => {
3293
- const th = (ev.target as Element).closest('th');
3294
- const c = th !== null && th.querySelector('.tb-sort') !== null ? cols[th.cellIndex] : undefined;
3295
- if (c !== undefined) void fire('ui-sort', face, c.word);
3296
- });
3297
- box = el('tbody');
3298
- // the totals row sits outside tbody, so it is never chosen, sorted or moved
3299
- const foot = el('tfoot');
3300
- const totals = newTableRow(cols);
3301
- totals.className = 'tb-totals';
3302
- foot.append(totals);
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);
3313
- wrap.append(table);
3314
- } else {
3315
- box = el('ul', 'tb-list');
3316
- wrap.append(box);
3317
- }
3318
- const empty = el('p', 'tb-empty');
3319
- wrap.append(empty);
3320
- const choose = (target: EventTarget | null): void => {
3321
- const item = (target as Element | null)?.closest(style === 'table' ? 'tr' : 'li');
3322
- const row = item ? rowOf.get(item) : undefined;
3323
- if (row !== undefined) void fire('ui-select', face, row);
3324
- };
3325
- box.addEventListener('click', ev => choose(ev.target));
3326
- box.addEventListener('keydown', ev => {
3327
- if (ev.key === 'Enter' || ev.key === ' ') {
3328
- ev.preventDefault();
3329
- choose(ev.target);
3330
- }
3331
- });
3332
- m.box = box;
3333
- m.rows = new Map();
3334
- m.empty = empty;
3335
- return wrap;
3336
- }
3337
-
3338
- /** The rows of a table or list in the order shown, with their keys; then draws them. */
3339
- function syncRows(m: Mounted): void {
3340
- const f = m.face;
3341
- const data = get(f, 'data');
3342
- let rows = data.t === K.Block ? data.s.data.slice(data.i) : [];
3343
- if (m.box!.tagName === 'TBODY') {
3344
- syncHead(f, m.box!.parentElement as HTMLTableElement, columns(f));
3345
- const order = hostSorted(f);
3346
- if (order !== null) rows = sortGroups(rows, order.sym, order.desc, activeLanguage(host.rt), cellText);
3347
- }
3348
- const keyWord = get(f, 'key');
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);
3389
- const selected = get(f, 'selected');
3390
- const selectable = handlerFor(f, 'on-select');
3391
- box.parentElement!.classList.toggle('tb-selectable', selectable);
3392
- const { first, end } = rowsToDraw(m);
3393
- const count = m.items.length;
3394
- const old = m.rows!;
3395
- const next = new Map<string, HTMLElement>();
3396
- let cursor = box.firstChild;
3397
- for (let i = first; i < end; i++) {
3398
- const { row, k } = m.items[i]!;
3399
- const group = groupRow(row);
3400
- let item = old.get(k);
3401
- if (group !== null) {
3402
- // a group's head or foot: kept by its place, never chosen, dragged or sorted
3403
- if (item === undefined) item = group.kind === 'head' ? newGroupHead(cols, table) : table ? newTableRow(cols) : newListItem();
3404
- item.className = `tb-group-${group.kind} tb-level-${group.level}`;
3405
- if (group.kind === 'head') {
3406
- const t = translate(group.value, host.rt);
3407
- const cell = item.firstElementChild!;
3408
- if (cell.textContent !== t) cell.textContent = t;
3409
- if (table) (cell as HTMLTableCellElement).colSpan = Math.max(1, cols.length);
3410
- } else fillRow(item, group.value, cols, table);
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');
3421
- }
3422
- next.set(k, item);
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
- }
3431
- if (item !== cursor) box.insertBefore(item, cursor);
3432
- else cursor = cursor.nextSibling;
3433
- }
3434
- for (const [k, item] of old) if (next.get(k) !== item) item.remove();
3435
- m.rows = next;
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
- }
3521
- }
3522
-
3523
- /** Headers in the active language; in a sortable table each is a button, with an arrow on the sorted one. */
3524
- function syncHead(f: ObjectCell, table: HTMLTableElement, cols: Column[]): void {
3525
- const sortable = flag(f, 'sortable') || handlerFor(f, 'on-sort');
3526
- const order = sortedBy(f);
3527
- const ths = table.tHead!.rows[0]!.cells;
3528
- cols.forEach((c, i) => {
3529
- const th = ths[i];
3530
- if (th === undefined) return;
3531
- const on = order !== null && canon(order.sym) === canon(c.sym);
3532
- let button = th.querySelector<HTMLButtonElement>('.tb-sort');
3533
- if (sortable && button === null) {
3534
- button = el('button', 'tb-sort');
3535
- button.type = 'button';
3536
- button.append(el('span'));
3537
- th.replaceChildren(button);
3538
- } else if (!sortable && button !== null) {
3539
- th.replaceChildren();
3540
- button = null;
3541
- }
3542
- const label = button !== null ? button.firstChild! : th;
3543
- if (label.textContent !== c.label) label.textContent = c.label;
3544
- if (button !== null) {
3545
- // the button stays, so a header chosen from the keyboard keeps the focus
3546
- const arrow = on && order.desc ? 'arrow-down' : 'arrow-up';
3547
- const svg = button.querySelector('svg');
3548
- if (svg?.dataset['icon'] !== arrow) {
3549
- const next = icon(arrow);
3550
- if (next !== null) {
3551
- next.dataset['icon'] = arrow;
3552
- if (svg) svg.replaceWith(next);
3553
- else button.append(next);
3554
- }
3555
- }
3556
- button.querySelector('svg')?.classList.toggle('tb-sort-idle', !on);
3557
- }
3558
- if (on) th.setAttribute('aria-sort', order.desc ? 'descending' : 'ascending');
3559
- else th.removeAttribute('aria-sort');
3560
- });
3561
- const totals = get(f, 'totals');
3562
- const foot = table.tFoot!;
3563
- foot.hidden = totals.t === K.None;
3564
- if (totals.t !== K.None) fillRow(foot.rows[0]!, totals, cols, true);
3565
- }
3566
-
3567
- /** A table's sorted facet: [column asc] or [column desc]. */
3568
- function sortedBy(f: ObjectCell): { sym: Sym; desc: boolean } | null {
3569
- const v = get(f, 'sorted');
3570
- if (v.t !== K.Block || v.s.data.length - v.i < 2) return null;
3571
- const c = v.s.data[v.i]!;
3572
- const o = v.s.data[v.i + 1]!;
3573
- if ((c.t !== K.Word && c.t !== K.LitWord) || (o.t !== K.Word && o.t !== K.LitWord)) return null;
3574
- return { sym: (c as WordCell).sym, desc: canon((o as WordCell).sym) === canon(intern('desc')) };
3575
- }
3576
-
3577
- /** The order the host applies itself: a sortable table without on-sort, which sorts for itself. */
3578
- function hostSorted(f: ObjectCell): { sym: Sym; desc: boolean } | null {
3579
- return flag(f, 'sortable') && !handlerFor(f, 'on-sort') ? sortedBy(f) : null;
3580
- }
3581
-
3582
- /** A group's title, the width of the whole row. */
3583
- function newGroupHead(cols: Column[], table: boolean): HTMLElement {
3584
- if (!table) {
3585
- const li = el('li');
3586
- li.append(el('span'));
3587
- return li;
3588
- }
3589
- const tr = el('tr');
3590
- tr.setAttribute('role', 'row');
3591
- const th = el('th');
3592
- th.scope = 'rowgroup';
3593
- th.setAttribute('role', 'rowheader');
3594
- th.colSpan = Math.max(1, cols.length);
3595
- tr.append(th);
3596
- return tr;
3597
- }
3598
-
3599
- function newTableRow(cols: Column[]): HTMLElement {
3600
- const tr = el('tr');
3601
- tr.setAttribute('role', 'row');
3602
- for (const c of cols) {
3603
- const td = el('td');
3604
- td.setAttribute('role', 'cell');
3605
- td.dataset['label'] = c.label;
3606
- tr.append(td);
3607
- }
3608
- return tr;
3609
- }
3610
-
3611
- function newListItem(): HTMLElement {
3612
- const li = el('li');
3613
- const texts = el('span', 'tb-list-texts');
3614
- texts.append(el('span', 'tb-list-primary'), el('span', 'tb-list-secondary'));
3615
- li.append(texts);
3616
- return li;
3617
- }
3618
-
3619
- function fillRow(item: HTMLElement, row: Cell, cols: Column[], table: boolean): void {
3620
- const set = (e: Element, t: string): void => {
3621
- if (e.textContent !== t) e.textContent = t;
3622
- };
3623
- if (table) {
3624
- cols.forEach((c, i) => {
3625
- const v = rowField(row, c.sym);
3626
- const td = item.children[i]!;
3627
- if (c.image) {
3628
- td.classList.add('tb-thumb-cell');
3629
- return thumb(td, v, c.round);
3630
- }
3631
- set(td, cellText(v));
3632
- td.classList.toggle('tb-num', NUMERIC.has(v.t));
3633
- });
3634
- return;
3635
- }
3636
- // a list shows its picture first, then its first column, and the others on a quieter line
3637
- const pic = cols.find(c => c.image);
3638
- if (pic !== undefined) thumb(item, rowField(row, pic.sym), pic.round);
3639
- else item.querySelector(':scope > .tb-thumb')?.remove();
3640
- const [first, ...rest] = cols.filter(c => !c.image).map(c => cellText(rowField(row, c.sym)));
3641
- const texts = item.querySelector(':scope > .tb-list-texts')!;
3642
- set(texts.children[0]!, first ?? '');
3643
- set(texts.children[1]!, rest.filter(Boolean).join(' · '));
3644
- }
3645
-
3646
- function handlerFor(face: ObjectCell, name: string): boolean {
3647
- const ev = get(face, 'events');
3648
- if (ev.t !== K.Block) return false;
3649
- const c = canon(intern(name));
3650
- return ev.s.data.some(x => x.t === K.Word && canon((x as WordCell).sym) === c);
3651
- }
3652
-
3653
- // --- trees ---------------------------------------------------------------------------
3654
-
3655
- const CHILDREN = intern('children');
3656
- const EXPANDED = intern('expanded');
3657
-
3658
- function treeItems(m: Mounted): HTMLElement[] {
3659
- return Array.from(m.box!.querySelectorAll<HTMLElement>('[role="treeitem"]'));
3660
- }
3661
-
3662
- /** The node whose children a group holds; none for the root. */
3663
- function groupParent(m: Mounted, group: HTMLElement): Cell {
3664
- if (group === m.box) return NONE;
3665
- const item = group.closest('[role="treeitem"]');
3666
- return item !== null ? rowOf.get(item) ?? NONE : NONE;
3667
- }
3668
-
3669
- function buildTree(face: ObjectCell, m: Mounted): HTMLElement {
3670
- const wrap = el('div', 'tb-tree-wrap');
3671
- const box = el('ul', 'tb-tree');
3672
- box.setAttribute('role', 'tree');
3673
- const empty = el('p', 'tb-empty');
3674
- wrap.append(box, empty);
3675
- box.addEventListener('click', ev => {
3676
- const target = ev.target as Element;
3677
- const item = target.closest<HTMLElement>('[role="treeitem"]');
3678
- if (item === null) return;
3679
- if (target.closest('.tb-tree-toggle') !== null) return toggleNode(m, item);
3680
- focusItem(m, item);
3681
- selectNode(m, item);
3682
- });
3683
- box.addEventListener('keydown', ev => treeKey(m, ev));
3684
- m.box = box;
3685
- m.rows = new Map();
3686
- m.empty = empty;
3687
- m.open = new Set();
3688
- return wrap;
3689
- }
3690
-
3691
- function newTreeItem(): HTMLElement {
3692
- const li = el('li');
3693
- li.setAttribute('role', 'treeitem');
3694
- const row = el('div', 'tb-tree-row');
3695
- const toggle = el('span', 'tb-tree-toggle');
3696
- toggle.setAttribute('aria-hidden', 'true');
3697
- const chevron = icon('chevron-right');
3698
- if (chevron !== null) toggle.append(chevron);
3699
- row.append(toggle, el('span', 'tb-tree-label'));
3700
- const group = el('ul');
3701
- group.setAttribute('role', 'group');
3702
- li.append(row, group);
3703
- return li;
3704
- }
3705
-
3706
- /** Creates, updates, moves or removes the items of a tree, level by level, by key. */
3707
- function syncTree(m: Mounted): void {
3708
- const f = m.face;
3709
- const label = columns(f)[0]?.sym ?? intern('name');
3710
- const keyWord = get(f, 'key');
3711
- const key = keyWord.t === K.Word || keyWord.t === K.LitWord ? (keyWord as WordCell).sym : intern('id');
3712
- const selected = get(f, 'selected');
3713
- const old = m.rows!;
3714
- const open = m.open!;
3715
- const next = new Map<string, HTMLElement>();
3716
- const level = (group: HTMLElement, nodes: Cell[], depth: number, parentKey: string): void => {
3717
- let cursor = group.firstChild;
3718
- nodes.forEach((node, i) => {
3719
- const id = rowField(node, key);
3720
- let k = id.t === K.None ? `${parentKey}/${i}` : `${id.t}:${form(id)}`;
3721
- if (next.has(k)) k = `${parentKey}/${i}#${k}`;
3722
- const known = old.get(k);
3723
- const item = known ?? newTreeItem();
3724
- next.set(k, item);
3725
- rowOf.set(item, node);
3726
- item.dataset['key'] = k;
3727
- item.setAttribute('aria-level', String(depth));
3728
- item.style.setProperty('--tb-level', String(depth - 1));
3729
- const text = cellText(rowField(node, label));
3730
- const name = item.firstElementChild!.lastElementChild!;
3731
- if (name.textContent !== text) name.textContent = text;
3732
- const kids = rowField(node, CHILDREN);
3733
- const folder = kids.t === K.Block;
3734
- // `expanded: true` opens a node the first time it shows
3735
- if (folder && known === undefined && rowField(node, EXPANDED).t === K.Logic && (rowField(node, EXPANDED) as { v: boolean }).v) open.add(k);
3736
- const isOpen = folder && open.has(k);
3737
- if (folder) item.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
3738
- else item.removeAttribute('aria-expanded');
3739
- const sub = item.lastElementChild as HTMLElement;
3740
- if (isOpen) level(sub, (kids as BlockCell).s.data.slice((kids as BlockCell).i), depth + 1, k);
3741
- else sub.replaceChildren();
3742
- sub.hidden = sub.childElementCount === 0;
3743
- const on = selected.t !== K.None && sameRow(selected, node);
3744
- item.classList.toggle('tb-selected', on);
3745
- item.setAttribute('aria-selected', on ? 'true' : 'false');
3746
- if (item !== cursor) group.insertBefore(item, cursor);
3747
- else cursor = cursor.nextSibling;
3748
- });
3749
- // whatever is left after the last placed item is gone from the data
3750
- while (cursor !== null) {
3751
- const gone = cursor;
3752
- cursor = cursor.nextSibling;
3753
- gone.remove();
3754
- }
3755
- };
3756
- const data = get(f, 'data');
3757
- level(m.box!, data.t === K.Block ? data.s.data.slice(data.i) : [], 1, '');
3758
- m.rows = next;
3759
- // one Tab stop: the item that had it, else the selected one, else the first
3760
- const items = treeItems(m);
3761
- const current = items.find(e => e.tabIndex === 0 && e.hasAttribute('tabindex'))
3762
- ?? items.find(e => e.classList.contains('tb-selected')) ?? items[0];
3763
- for (const e of items) e.tabIndex = e === current ? 0 : -1;
3764
- m.empty!.textContent = str(f, 'text') ?? own('empty');
3765
- m.empty!.hidden = items.length > 0;
3766
- }
3767
-
3768
- function focusItem(m: Mounted, item: HTMLElement): void {
3769
- for (const e of treeItems(m)) e.tabIndex = e === item ? 0 : -1;
3770
- item.focus();
3771
- }
3772
-
3773
- function selectNode(m: Mounted, item: HTMLElement): void {
3774
- const node = rowOf.get(item);
3775
- if (node !== undefined) void fire('ui-select', m.face, node);
3776
- }
3777
-
3778
- /** Opens or closes a folder; opening runs on-expand, which may load its children. */
3779
- function toggleNode(m: Mounted, item: HTMLElement, want?: boolean): void {
3780
- if (!item.hasAttribute('aria-expanded')) return;
3781
- const k = item.dataset['key']!;
3782
- const open = want ?? !m.open!.has(k);
3783
- if (open === m.open!.has(k)) return;
3784
- const inside = document.activeElement !== item && item.contains(document.activeElement);
3785
- if (open) m.open!.add(k);
3786
- else m.open!.delete(k);
3787
- syncTree(m);
3788
- if (inside) focusItem(m, item);
3789
- const node = rowOf.get(item);
3790
- if (open && node !== undefined) void fire('ui-expand', m.face, node);
3791
- }
3792
-
3793
- /** The keys of the treeview pattern: arrows, Home, End, Enter, Space and a letter to jump. */
3794
- function treeKey(m: Mounted, ev: KeyboardEvent): void {
3795
- const item = (ev.target as Element).closest<HTMLElement>('[role="treeitem"]');
3796
- if (item === null || ev.altKey || ev.ctrlKey || ev.metaKey) return;
3797
- const items = treeItems(m);
3798
- const i = items.indexOf(item);
3799
- const expanded = item.getAttribute('aria-expanded');
3800
- let to: HTMLElement | null | undefined = null;
3801
- switch (ev.key) {
3802
- case 'ArrowDown': to = items[i + 1]; break;
3803
- case 'ArrowUp': to = items[i - 1]; break;
3804
- case 'Home': to = items[0]; break;
3805
- case 'End': to = items[items.length - 1]; break;
3806
- case 'ArrowRight':
3807
- if (expanded === 'false') toggleNode(m, item, true);
3808
- else if (expanded === 'true') to = item.querySelector<HTMLElement>('[role="treeitem"]');
3809
- break;
3810
- case 'ArrowLeft':
3811
- if (expanded === 'true') toggleNode(m, item, false);
3812
- else to = item.parentElement!.closest<HTMLElement>('[role="treeitem"]');
3813
- break;
3814
- case 'Enter': case ' ': selectNode(m, item); break;
3815
- default: {
3816
- if (ev.key.length !== 1 || ev.key.trim() === '') return;
3817
- const c = ev.key.toLowerCase();
3818
- const label = (e: HTMLElement): string => (e.querySelector('.tb-tree-label')?.textContent ?? '').toLowerCase();
3819
- to = [...items.slice(i + 1), ...items.slice(0, i)].find(e => label(e).startsWith(c));
3820
- }
3821
- }
3822
- ev.preventDefault();
3823
- if (to) focusItem(m, to);
3824
- }
3825
-
3826
- /** Where a drag over a tree lands: between siblings, or into a folder when over the middle of its row. */
3827
- function treeTarget(m: Mounted, src: Source, x: number, y: number): Target | null {
3828
- const at = document.elementFromPoint(x, y)?.closest<HTMLElement>('[role="treeitem"]');
3829
- const drop = flag(m.face, 'drop');
3830
- let t: Target;
3831
- if (at === null || at === undefined || !m.box!.contains(at)) {
3832
- t = { m, index: insertionAt(m, x, y), reorder: false, group: m.box!, parent: NONE };
3833
- } else {
3834
- const r = at.querySelector(':scope > .tb-tree-row')!.getBoundingClientRect();
3835
- if (at.hasAttribute('aria-expanded') && y > r.top + r.height / 4 && y < r.bottom - r.height / 4) {
3836
- const node = rowOf.get(at)!;
3837
- const kids = rowField(node, CHILDREN) as BlockCell;
3838
- t = { m, index: kids.s.data.length - kids.i, reorder: false, group: at.lastElementChild as HTMLElement, parent: node, into: at };
3839
- } else {
3840
- const group = at.parentElement!;
3841
- const index = Array.prototype.indexOf.call(group.children, at) + (y > r.top + r.height / 2 ? 1 : 0);
3842
- t = { m, index, reorder: false, group, parent: groupParent(m, group) };
3843
- }
3844
- }
3845
- // never into itself or below itself
3846
- if (src.el === t.into || src.el.contains(t.group!)) return null;
3847
- t.reorder = src.within === m && t.group === src.group && t.into === undefined;
3848
- return t.reorder || drop ? t : null;
3849
- }
3850
-
3851
- // --- toolbars and breadcrumbs -------------------------------------------------------
3852
-
3853
- const BAR_ITEMS = 'button, a[href], input, select, textarea, [tabindex]';
3854
-
3855
- /** The controls of a toolbar, in order; `shown` skips hidden and disabled ones. */
3856
- function barItems(bar: HTMLElement, shown = true): HTMLElement[] {
3857
- return Array.from(bar.querySelectorAll<HTMLElement>(BAR_ITEMS)).filter(e => e.closest('.tb-toolbar') === bar
3858
- && (!shown || e.getClientRects().length > 0 && !(e as HTMLButtonElement).disabled));
3859
- }
3860
-
3861
- function buildToolbar(): HTMLElement {
3862
- const bar = el('div', 'tb-toolbar');
3863
- bar.setAttribute('role', 'toolbar');
3864
- // one Tab stop: the arrows move between the controls (roving tabindex)
3865
- bar.addEventListener('keydown', ev => {
3866
- const at = ev.target as HTMLElement;
3867
- if (ev.altKey || ev.ctrlKey || ev.metaKey || at.matches('input, select, textarea')) return;
3868
- const items = barItems(bar);
3869
- const i = items.indexOf(at);
3870
- if (i < 0) return;
3871
- const to = ev.key === 'ArrowRight' ? (i + 1) % items.length : ev.key === 'ArrowLeft' ? (i - 1 + items.length) % items.length
3872
- : ev.key === 'Home' ? 0 : ev.key === 'End' ? items.length - 1 : -1;
3873
- if (to < 0) return;
3874
- ev.preventDefault();
3875
- items[to]!.focus();
3876
- });
3877
- bar.addEventListener('focusin', ev => {
3878
- const at = ev.target as HTMLElement;
3879
- if (!barItems(bar, false).includes(at)) return;
3880
- for (const e of barItems(bar, false)) e.tabIndex = e === at ? 0 : -1;
3881
- });
3882
- return bar;
3883
- }
3884
-
3885
- /** Keeps exactly one control of a toolbar in the Tab order, and the text of its buttons as their tooltip. */
3886
- function syncToolbar(bar: HTMLElement): void {
3887
- for (const e of Array.from(bar.children)) {
3888
- const m = byNode.get(e);
3889
- if (m !== undefined && m.el === e && word(m.face, 'style') === 'button') sync(m);
3890
- }
3891
- // the bar may not be on the page yet, so visibility is checked only when moving
3892
- const items = barItems(bar, false);
3893
- const current = items.find(e => e.tabIndex === 0 && e.hasAttribute('tabindex')) ?? items[0];
3894
- for (const e of items) e.tabIndex = e === current ? 0 : -1;
3895
- }
3896
-
3897
- interface Crumb { text: string; id: Cell }
3898
-
3899
- /** The items of a breadcrumb: a label and a word or path each, the last one maybe without. */
3900
- function crumbs(face: ObjectCell): Crumb[] {
3901
- const d = get(face, 'data');
3902
- if (d.t !== K.Block) return [];
3903
- const out: Crumb[] = [];
3904
- const cells = d.s.data.slice(d.i);
3905
- for (let i = 0; i < cells.length; i++) {
3906
- const c = cells[i]!;
3907
- if (c.t !== K.String && c.t !== K.Map) continue;
3908
- const next = cells[i + 1];
3909
- const id = next !== undefined && (next.t === K.Word || next.t === K.Path) ? next : NONE;
3910
- if (id !== NONE) i++;
3911
- out.push({ text: translate(c, host.rt), id });
3912
- }
3913
- return out;
3914
- }
3915
-
3916
- function buildBreadcrumb(m: Mounted): HTMLElement {
3917
- const nav = el('nav', 'tb-breadcrumb');
3918
- keepOwn(nav, 'breadcrumb', 'aria-label');
3919
- m.box = el('ol');
3920
- nav.append(m.box);
3921
- return nav;
3922
- }
3923
-
3924
- /** Rebuilds the items; on narrow screens the middle ones hide behind a "…" that lists them in a menu. */
3925
- function syncBreadcrumb(m: Mounted): void {
3926
- const f = m.face;
3927
- const items = crumbs(f);
3928
- // choosing an item sets value, which repaints the face: keep the nodes (and the focus) if nothing changed
3929
- const signature = items.map(c => `${c.text}\u0000${form(c.id)}`).join('\u0001');
3930
- if (m.kids === signature) return;
3931
- m.kids = signature;
3932
- // a lit-word or lit-path, so that passing it on does not evaluate it
3933
- const pick = (c: Crumb): void => void fire('ui-crumb', f, c.id.t === K.Path ? ({ ...c.id, t: K.LitPath } as Cell) : wordOf(K.LitWord, form(c.id)));
3934
- const middle = items.length > 3 ? items.slice(1, -2) : [];
3935
- const nodes: HTMLElement[] = items.map((c, i) => {
3936
- const li = el('li');
3937
- if (middle.includes(c)) li.className = 'tb-crumb-middle';
3938
- if (c.id === NONE) {
3939
- const span = el('span', 'tb-crumb');
3940
- span.textContent = c.text;
3941
- if (i === items.length - 1) span.setAttribute('aria-current', 'page');
3942
- li.append(span);
3943
- } else {
3944
- const b = el('button', 'tb-crumb');
3945
- b.type = 'button';
3946
- b.textContent = c.text;
3947
- b.addEventListener('click', () => pick(c));
3948
- li.append(b);
3949
- }
3950
- return li;
3951
- });
3952
- if (middle.length > 0) {
3953
- const li = el('li', 'tb-crumb-more');
3954
- const b = el('button', 'tb-crumb');
3955
- b.type = 'button';
3956
- b.textContent = '…';
3957
- keepOwn(b, 'more-levels', 'aria-label');
3958
- b.setAttribute('aria-haspopup', 'menu');
3959
- b.setAttribute('aria-expanded', 'false');
3960
- b.addEventListener('click', () => {
3961
- const r = b.getBoundingClientRect();
3962
- openMenu(middle.map(c => ({ text: c.text, run: () => pick(c) })), r.left, r.bottom + 4, b);
3963
- });
3964
- li.append(b);
3965
- nodes.splice(1, 0, li);
3966
- }
3967
- m.box!.replaceChildren(...nodes);
3968
- }
3969
-
3970
- // --- dialogs, tabs and toasts --------------------------------------------------------
3971
-
3972
- function buildDialog(face: ObjectCell, m: Mounted): HTMLElement {
3973
- const d = el('dialog', 'tb-dialog');
3974
- const head = el('header', 'tb-dialog-head');
3975
- const title = el('h2', 'tb-dialog-title');
3976
- title.id = `tb-${nextId++}`;
3977
- d.setAttribute('aria-labelledby', title.id);
3978
- const x = el('button', 'tb-dialog-close');
3979
- x.type = 'button';
3980
- keepOwn(x, 'close', 'aria-label');
3981
- x.textContent = '×';
3982
- x.addEventListener('click', () => void fire('ui-close', face));
3983
- head.append(title, x);
3984
- const body = el('div', 'tb-dialog-body');
3985
- d.append(head, body);
3986
- // Esc: let the face decide, so code that keeps it open still wins
3987
- d.addEventListener('cancel', ev => {
3988
- ev.preventDefault();
3989
- void fire('ui-close', face);
3990
- });
3991
- m.label = title;
3992
- m.box = body;
3993
- return d;
3994
- }
3995
-
3996
- function syncDialog(m: Mounted): void {
3997
- const d = m.el as HTMLDialogElement;
3998
- m.label!.textContent = str(m.face, 'text') ?? '';
3999
- const open = !flag(m.face, 'hidden');
4000
- if (open === d.open) return;
4001
- if (!d.isConnected) {
4002
- queueMicrotask(() => { if (d.isConnected) syncDialog(m); });
4003
- return;
4004
- }
4005
- if (!open) return d.close();
4006
- d.showModal();
4007
- // after this repaint, which never writes into a focused input
4008
- queueMicrotask(() => d.querySelector<HTMLElement>('input, textarea, select')?.focus());
4009
- }
4010
-
4011
- function buildTabs(face: ObjectCell, m: Mounted): HTMLElement {
4012
- const node = el('div', 'tb-tabs');
4013
- const list = el('div', 'tb-tablist');
4014
- list.setAttribute('role', 'tablist');
4015
- node.append(list);
4016
- const tabs = children(face);
4017
- const pick = (i: number): void => {
4018
- void fire('ui-input', face, { t: K.Integer, v: i + 1 });
4019
- (list.children[i] as HTMLElement | undefined)?.focus();
4020
- };
4021
- tabs.forEach((t, i) => {
4022
- const panel = build(t);
4023
- const b = el('button', 'tb-tab');
4024
- b.type = 'button';
4025
- b.id = `tb-${nextId++}`;
4026
- panel.id = `${b.id}-panel`;
4027
- b.setAttribute('role', 'tab');
4028
- b.setAttribute('aria-controls', panel.id);
4029
- panel.setAttribute('aria-labelledby', b.id);
4030
- b.textContent = str(t, 'text') ?? '';
4031
- b.addEventListener('click', () => pick(i));
4032
- const tm = byCtx.get(t.ctx)!;
4033
- tm.button = b;
4034
- list.append(b);
4035
- node.append(panel);
4036
- });
4037
- list.addEventListener('keydown', ev => {
4038
- const at = Array.prototype.indexOf.call(list.children, document.activeElement);
4039
- const n = tabs.length;
4040
- const to = ev.key === 'ArrowRight' ? (at + 1) % n : ev.key === 'ArrowLeft' ? (at - 1 + n) % n
4041
- : ev.key === 'Home' ? 0 : ev.key === 'End' ? n - 1 : -1;
4042
- if (to < 0 || at < 0) return;
4043
- ev.preventDefault();
4044
- pick(to);
4045
- });
4046
- m.box = list;
4047
- return node;
4048
- }
4049
-
4050
- function syncTabs(m: Mounted): void {
4051
- const v = get(m.face, 'value');
4052
- const tabs = children(m.face);
4053
- const at = v.t === K.Integer ? Math.min(Math.max(Number(v.v), 1), tabs.length) - 1 : 0;
4054
- tabs.forEach((t, i) => {
4055
- const tm = byCtx.get(t.ctx);
4056
- if (tm === undefined || tm.button === null) return;
4057
- const on = i === at;
4058
- tm.button.setAttribute('aria-selected', on ? 'true' : 'false');
4059
- tm.button.tabIndex = on ? 0 : -1;
4060
- tm.el.hidden = !on;
4061
- });
4062
- }
4063
-
4064
- // A split shows two panes side by side with a handle between them; on narrow
4065
- // screens it shows one pane, the one its value names, and the second pane
4066
- // gets a back button.
4067
- function buildSplit(face: ObjectCell, m: Mounted): HTMLElement {
4068
- const node = el('div', 'tb-split');
4069
- const [a, b] = children(face);
4070
- const first = el('div', 'tb-split-pane');
4071
- const second = el('div', 'tb-split-pane');
4072
- first.tabIndex = second.tabIndex = -1;
4073
- const handle = el('div', 'tb-split-handle');
4074
- handle.tabIndex = 0;
4075
- handle.setAttribute('role', 'separator');
4076
- handle.setAttribute('aria-orientation', 'vertical');
4077
- keepOwn(handle, 'resize-panes', 'aria-label');
4078
- handle.setAttribute('aria-valuemin', '20');
4079
- handle.setAttribute('aria-valuemax', '80');
4080
- const resize = (pct: number): void => {
4081
- const p = Math.round(Math.min(80, Math.max(20, pct)));
4082
- node.style.setProperty('--tb-split', `${p}%`);
4083
- handle.setAttribute('aria-valuenow', String(p));
4084
- };
4085
- resize(40);
4086
- handle.addEventListener('pointerdown', ev => {
4087
- handle.setPointerCapture(ev.pointerId);
4088
- ev.preventDefault();
4089
- });
4090
- handle.addEventListener('pointermove', ev => {
4091
- if (!handle.hasPointerCapture(ev.pointerId)) return;
4092
- const r = node.getBoundingClientRect();
4093
- resize(((ev.clientX - r.left) / r.width) * 100);
4094
- });
4095
- handle.addEventListener('keydown', ev => {
4096
- const now = Number(handle.getAttribute('aria-valuenow'));
4097
- const to = ev.key === 'ArrowLeft' ? now - 5 : ev.key === 'ArrowRight' ? now + 5
4098
- : ev.key === 'Home' ? 20 : ev.key === 'End' ? 80 : null;
4099
- if (to === null) return;
4100
- ev.preventDefault();
4101
- resize(to);
4102
- });
4103
- const back = el('button', 'tb-button tb-split-back');
4104
- back.type = 'button';
4105
- const arrow = iconNode('arrow-left');
4106
- const caption = el('span');
4107
- keepOwn(caption, 'back');
4108
- back.append(...(arrow !== null ? [arrow] : []), caption);
4109
- back.addEventListener('click', () => void fire('ui-input', face, { t: K.Integer, v: 1 }));
4110
- if (a !== undefined) first.append(build(a));
4111
- second.append(back);
4112
- if (b !== undefined) second.append(build(b));
4113
- node.append(first, handle, second);
4114
- return node;
4115
- }
4116
-
4117
- function syncSplit(m: Mounted): void {
4118
- const v = get(m.face, 'value');
4119
- const pane = v.t === K.Integer && Number(v.v) === 2 ? '2' : '1';
4120
- const was = m.el.dataset['pane'];
4121
- if (was === pane) return;
4122
- m.el.dataset['pane'] = pane;
4123
- // on narrow screens the other pane just appeared: take the focus there
4124
- if (was !== undefined && matchMedia('(max-width: 640px)').matches) {
4125
- const shown = m.el.children[pane === '2' ? 2 : 0] as HTMLElement;
4126
- (shown.querySelector<HTMLElement>('.tb-selected') ?? shown).focus();
4127
- }
4128
- }
4129
-
4130
- let toasts: HTMLElement | null = null;
4131
-
4132
- native('show-toast', '["Shows a short message at the edge of the screen." message [string!] kind [word! none!]]', (_t, f) => {
4133
- if (toasts === null) {
4134
- // a manual popover sits in the top layer, so toasts show above open dialogs
4135
- toasts = el('div', 'tb-toasts');
4136
- toasts.popover = 'manual';
4137
- toasts.setAttribute('aria-live', 'polite');
4138
- document.body.append(toasts);
4139
- }
4140
- const kind = f.args[1]!.t === K.Word ? spell((f.args[1] as WordCell).sym).toLowerCase() : null;
4141
- const t = el('div', kind !== null ? `tb-toast tb-${kind}` : 'tb-toast');
4142
- if (kind === 'danger') t.setAttribute('role', 'alert');
4143
- const message = text(f.args[0] as StringCell);
4144
- devLog.note('toast', kind !== null ? `${kind}: ${message}` : message);
4145
- const box = toasts;
4146
- const dismiss = (): void => {
4147
- t.remove();
4148
- if (box.childElementCount === 0 && box.matches(':popover-open')) box.hidePopover();
4149
- };
4150
- t.addEventListener('click', dismiss);
4151
- setTimeout(dismiss, kind === 'danger' ? 6000 : 4000);
4152
- if (box.matches(':popover-open')) box.hidePopover();
4153
- box.append(t);
4154
- box.showPopover();
4155
- // screen readers announce text that changes inside a live region already shown
4156
- setTimeout(() => { t.textContent = message; }, 50);
4157
- return value(f.args[0]!);
4158
- });
4159
-
4160
- native('show-confirm', '["Asks a question in a small dialog; true when the user says yes." question [string!] yes [string! none!] no [string! none!] kind [word! none!]]', (_t, f, v) => {
4161
- if (f.phase === 1) return value(v!);
4162
- f.phase = 1;
4163
- const answer = (at: number, key: string): string => f.args[at]!.t === K.String ? text(f.args[at] as StringCell) : own(key);
4164
- const danger = f.args[3]!.t === K.Word && spell((f.args[3] as WordCell).sym).toLowerCase() === 'danger';
4165
- const d = el('dialog', 'tb-dialog tb-confirm');
4166
- d.setAttribute('role', 'alertdialog');
4167
- const body = el('div', 'tb-dialog-body');
4168
- const q = el('p', 'tb-confirm-question');
4169
- q.id = `tb-${nextId++}`;
4170
- q.textContent = text(f.args[0] as StringCell);
4171
- d.setAttribute('aria-labelledby', q.id);
4172
- const row = el('div', 'tb-row tb-right');
4173
- const no = el('button', 'tb-button');
4174
- const yes = el('button', danger ? 'tb-button tb-danger' : 'tb-button tb-primary');
4175
- no.type = yes.type = 'button';
4176
- no.textContent = answer(2, 'no');
4177
- yes.textContent = answer(1, 'yes');
4178
- row.append(no, yes);
4179
- body.append(q, row);
4180
- d.append(body);
4181
- const p = new Promise<Cell>(resolve => {
4182
- const done = (ok: boolean): void => {
4183
- d.close();
4184
- d.remove();
4185
- resolve(ok ? TRUE : FALSE);
4186
- };
4187
- yes.addEventListener('click', () => done(true));
4188
- no.addEventListener('click', () => done(false));
4189
- // Esc is no
4190
- d.addEventListener('cancel', ev => { ev.preventDefault(); done(false); });
4191
- });
4192
- document.body.append(d);
4193
- // over an open dialog too: the top layer stacks dialogs in the order they open
4194
- d.showModal();
4195
- // what cannot be undone starts on no, so Enter does not do it by mistake
4196
- (danger ? no : yes).focus();
4197
- return { k: 'await', p };
4198
- });
4199
-
4200
- native('print-faces', '["Opens the print dialog for the page, or for one face only." face [object! none!]]', (_t, f) => {
4201
- const target = f.args[0]!.t === K.Object ? byCtx.get((f.args[0] as ObjectCell).ctx)?.el : undefined;
4202
- if (f.args[0]!.t === K.Object && (target === undefined || !target.isConnected)) {
4203
- return throwError('script', 'not-shown', 'print-page/only needs a face on the screen');
4204
- }
4205
- if (target !== undefined) {
4206
- target.classList.add('tb-print-target');
4207
- document.documentElement.classList.add('tb-print-only');
4208
- addEventListener('afterprint', () => {
4209
- target.classList.remove('tb-print-target');
4210
- document.documentElement.classList.remove('tb-print-only');
4211
- }, { once: true });
4212
- }
4213
- print();
4214
- return value(UNSET);
4215
- });
4216
-
4217
- // --- syncing -----------------------------------------------------------------------
4218
-
4219
- function sync(m: Mounted): void {
4220
- const f = m.face;
4221
- const style = word(f, 'style') ?? '';
4222
- const role = word(f, 'role');
4223
- const t = str(f, 'text');
4224
- const hidden = flag(f, 'hidden');
4225
- const err = str(f, 'error');
4226
- const cls: string[] = [];
4227
- if (hidden && style !== 'dialog') cls.push('tb-hidden');
4228
- if (flag(f, 'fill')) cls.push('tb-fill');
4229
- if (flag(f, 'narrow-only')) cls.push('tb-narrow-only');
4230
- if (flag(f, 'wide-only')) cls.push('tb-wide-only');
4231
- if (flag(f, 'fit')) cls.push('tb-fit');
4232
- if (flag(f, 'drop')) cls.push('tb-drop-zone');
4233
- if (role !== null && !INPUTS.has(style)) cls.push(`tb-${role}`);
4234
- const size = word(f, 'size');
4235
- if (size !== null) cls.push(`tb-${size}`);
4236
- const align = word(f, 'align');
4237
- if (align !== null && style === 'row') cls.push(`tb-${align}`);
4238
- const valign = word(f, 'valign');
4239
- if (valign !== null && style === 'row') cls.push(`tb-${valign}`);
4240
- if (err !== null) cls.push('tb-invalid');
4241
- if (flag(f, 'pending')) cls.push('tb-pending');
4242
- setExtra(m.el, cls);
4243
- // shown as it is, but it and its children cannot be used
4244
- m.el.inert = flag(f, 'inert');
4245
- // a face you can drag takes the focus, so the keyboard reaches its menu and moves it
4246
- if (flag(f, 'drag') && !isData(m) && m.el.tabIndex < 0) m.el.tabIndex = 0;
4247
- space(m.el, 'padding', get(f, 'pad'));
4248
- space(m.el, 'gap', get(f, 'gap'));
4249
-
4250
- if (style === 'radio') return syncRadio(m, err);
4251
- if (style === 'upload') return syncUpload(m, err);
4252
- if (style === 'photo') return syncPhoto(m, err);
4253
- if (style === 'widget') return syncWidget(m, err);
4254
- if (style === 'lookup') return syncLookup(m, err);
4255
- if (style === 'rich') return syncRich(m, err);
4256
- if (m.input !== null) {
4257
- if (m.label !== null) {
4258
- m.label.textContent = t ?? '';
4259
- m.label.classList.toggle('tb-required', required(f) && style !== 'check');
4260
- }
4261
- const v = get(f, 'value');
4262
- if (m.input instanceof HTMLInputElement && m.input.type === 'checkbox') {
4263
- m.input.checked = v.t === K.Logic && v.v;
4264
- } else {
4265
- // options given by code after the face was made
4266
- if (m.input instanceof HTMLSelectElement) {
4267
- if (m.input.dataset.options !== optionsKey(f)) fillSelect(m.input, f);
4268
- }
4269
- const want = v.t === K.None ? str(f, 'typed') ?? '' : style === 'money' || style === 'date' ? display(v) : form(v);
4270
- // never fight the user's typing: with the focus, only a value code set is drawn (set-values
4271
- // after Enter sent the form); a read-only field has no typing to fight
4272
- const theirs = document.activeElement === m.input && !flag(f, 'readonly') && (m.typing > 0 || v === m.typed);
4273
- if (!theirs && m.input.value !== want) m.input.value = want;
4274
- const hint = str(f, 'hint');
4275
- if (m.input instanceof HTMLSelectElement) {
4276
- const select = m.input;
4277
- select.options[0]!.textContent = hint ?? own('choose');
4278
- optionsOf(f).forEach((o, i) => {
4279
- const opt = select.options[i + 1];
4280
- if (opt) opt.textContent = optionText(o);
4281
- });
4282
- const groups = select.querySelectorAll('optgroup');
4283
- entriesOf(f).filter(isGroup).forEach((g, i) => {
4284
- if (groups[i]) groups[i]!.label = translate(g.title, host.rt);
4285
- });
4286
- }
4287
- else if (hint !== null) m.input.placeholder = hint;
4288
- }
4289
- const readonly = flag(f, 'readonly');
4290
- // text can be read-only; a choice or a checkbox can only be disabled
4291
- const typing = m.input instanceof HTMLTextAreaElement || (m.input instanceof HTMLInputElement && m.input.type !== 'checkbox');
4292
- if (typing) (m.input as HTMLInputElement | HTMLTextAreaElement).readOnly = readonly;
4293
- m.input.disabled = flag(f, 'disabled') || (readonly && !typing);
4294
- if (style === 'date') {
4295
- const pick = m.input.nextElementSibling as HTMLButtonElement;
4296
- pick.disabled = m.input.disabled || readonly;
4297
- pick.setAttribute('aria-label', t !== null ? own('choose-date-of', t) : own('choose-date'));
4298
- }
4299
- m.input.setAttribute('aria-required', required(f) ? 'true' : 'false');
4300
- m.input.setAttribute('aria-invalid', err !== null ? 'true' : 'false');
4301
- if (m.error !== null) m.error.textContent = err ?? '';
4302
- return;
4303
- }
4304
- switch (style) {
4305
- case 'title': case 'heading': case 'text': {
4306
- const tv = get(f, 'text');
4307
- m.el.textContent = tv.t === K.None ? '' : tv.t === K.Map || tv.t === K.Word ? translate(tv, host.rt) : display(tv);
4308
- break;
4309
- }
4310
- case 'tile': (m.label ?? m.el).textContent = t ?? ''; break;
4311
- case 'button': case 'link': {
4312
- (m.label ?? m.el).textContent = t ?? '';
4313
- const named = iconLabel(f);
4314
- if (named !== null) m.el.setAttribute('aria-label', named);
4315
- else m.el.removeAttribute('aria-label');
4316
- const keys = str(f, 'shortcut');
4317
- if (keys !== null) m.el.setAttribute('aria-keyshortcuts', shortcutAria(keys));
4318
- else m.el.removeAttribute('aria-keyshortcuts');
4319
- // in a toolbar, narrow screens show only the icon, so the text goes in the tooltip too
4320
- const bar = m.label !== null && m.el.parentElement?.classList.contains('tb-toolbar') === true;
4321
- const tip = named ?? (keys !== null || bar ? t : null);
4322
- m.el.title = tip === null ? '' : keys === null ? tip : `${tip} (${shortcutLabel(keys)})`;
4323
- break;
4324
- }
4325
- case 'progress': syncProgress(m); return;
4326
- case 'canvas': syncCanvas(m); return;
4327
- case 'chart': syncChart(m); return;
4328
- case 'orbit': syncOrbit(m); return;
4329
- case 'icon': syncIcon(m); return;
4330
- case 'video': case 'audio': syncMedia(m); return;
4331
- case 'image': {
4332
- const img = m.el as HTMLImageElement;
4333
- const src = str(f, 'value') ?? '';
4334
- if (img.getAttribute('src') !== src) img.src = src;
4335
- img.alt = t ?? '';
4336
- img.classList.toggle('tb-round', flag(f, 'round'));
4337
- // a size, as in Red: the image fills it, cut to fit
4338
- const ext = get(f, 'extent');
4339
- img.style.width = ext.t === K.Pair ? `${ext.x}px` : '';
4340
- img.style.height = ext.t === K.Pair ? `${ext.y}px` : '';
4341
- return;
4342
- }
4343
- case 'table': case 'list': syncRows(m); return;
4344
- case 'rows': syncRowsField(m, err); break;
4345
- case 'tree': syncTree(m); return;
4346
- case 'breadcrumb': syncBreadcrumb(m); return;
4347
- case 'toolbar': {
4348
- if (t !== null) m.el.setAttribute('aria-label', t);
4349
- else m.el.removeAttribute('aria-label');
4350
- break;
4351
- }
4352
- case 'desktop': case 'backdrop': {
4353
- const src = str(f, 'value');
4354
- m.el.style.backgroundImage = src !== null ? `url(${JSON.stringify(src)})` : '';
4355
- break;
4356
- }
4357
- case 'dialog': syncDialog(m); break;
4358
- case 'tabs': syncTabs(m); return;
4359
- case 'split': syncSplit(m); return;
4360
- case 'tab': if (m.button !== null) m.button.textContent = t ?? ''; break;
4361
- case 'panel': {
4362
- let h = m.el.querySelector<HTMLElement>(':scope > .tb-panel-title');
4363
- if (t === null) h?.remove();
4364
- else {
4365
- if (h === null) {
4366
- h = el('h2', 'tb-panel-title');
4367
- m.el.prepend(h);
4368
- }
4369
- h.textContent = t;
4370
- }
4371
- break;
4372
- }
4373
- case 'scroll': {
4374
- if (t !== null) m.el.setAttribute('aria-label', t);
4375
- else m.el.removeAttribute('aria-label');
4376
- break;
4377
- }
4378
- case 'grid': {
4379
- const cols = get(f, 'cols');
4380
- m.el.style.setProperty('--tb-cols', cols.t === K.Integer ? String(cols.v) : '2');
4381
- // [1 4 1]: a column per weight, never narrower than what it holds
4382
- const weights = cols.t === K.Block ? cols.s.data.slice(cols.i).filter(c => c.t === K.Integer) : [];
4383
- if (weights.length > 0) m.el.style.setProperty('--tb-tracks', weights.map(w => `minmax(min-content, ${form(w)}fr)`).join(' '));
4384
- else m.el.style.removeProperty('--tb-tracks');
4385
- break;
4386
- }
4387
- }
4388
- if (style === 'toolbar') syncToolbar(m.el);
4389
- if (m.el instanceof HTMLButtonElement) {
4390
- // a submit stays focusable while the form has errors; clicking it shows them
4391
- if (flag(f, 'submit')) m.el.setAttribute('aria-disabled', flag(f, 'disabled') ? 'true' : 'false');
4392
- else m.el.disabled = flag(f, 'disabled');
4393
- }
4394
- // children replaced by code: rebuild this container
4395
- const kids = get(f, 'pane');
4396
- if (kids.t === K.Block && (m.kids as BlockCell | undefined)?.s !== kids.s) {
4397
- m.kids = kids;
4398
- if (style === 'rows') {
4399
- placeEntries(m);
4400
- void fire('ui-pane', f);
4401
- return;
4402
- }
4403
- const box = m.box ?? m.el;
4404
- if (style === 'screens') placeScreen(m, box);
4405
- else {
4406
- const keep = box.querySelector(':scope > .tb-panel-title');
4407
- box.replaceChildren(...(keep ? [keep] : []));
4408
- appendChildren(box, f, style);
4409
- }
4410
- // let the dialect link the new faces to their view and form
4411
- void fire('ui-pane', f);
4412
- }
4413
- if (style === 'screens') settleScreen(m.box ?? m.el, f);
4414
- }
4415
-
4416
- /** A screen is made away from the page; the page keeps the one it has until `entering` ends. */
4417
- function placeScreen(m: Mounted, box: HTMLElement): void {
4418
- comingScreen = el('div');
4419
- appendChildren(comingScreen, m.face, 'screens');
4420
- settleScreen(box, m.face);
4421
- }
4422
-
4423
- function settleScreen(box: HTMLElement, f: ObjectCell): void {
4424
- const entering = flag(f, 'entering');
4425
- box.toggleAttribute('aria-busy', entering);
4426
- if (entering || comingScreen === null) return;
4427
- box.replaceChildren(...comingScreen.childNodes);
4428
- comingScreen = null;
4429
- enteredScreen(box);
4430
- }
4431
-
4432
- /** Sets a spacing property to a step of the theme's scale, or back to the stylesheet's. */
4433
- function space(e: HTMLElement, prop: string, v: Cell): void {
4434
- if (v.t === K.Integer) e.style.setProperty(prop, `var(--tb-space-${v.v})`);
4435
- else e.style.removeProperty(prop);
4436
- }
4437
-
4438
- /** Sets the face-driven classes, keeping the base classes from build. */
4439
- function setExtra(e: HTMLElement, cls: string[]): void {
4440
- const prev = (e.dataset['tb'] ?? '').split(' ').filter(Boolean);
4441
- for (const c of prev) if (!cls.includes(c)) e.classList.remove(c);
4442
- for (const c of cls) e.classList.add(c);
4443
- e.dataset['tb'] = cls.join(' ');
4444
- }
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
-
4475
- function syncDirty(): void {
4476
- for (const ctx of dirty) {
4477
- ctx.dirty = false;
4478
- const m = byCtx.get(ctx);
4479
- if (m !== undefined && (m.el.isConnected || comingScreen?.contains(m.el))) sync(m);
4480
- }
4481
- dirty.length = 0;
4482
- }
4483
-
4484
- // --- screens ---------------------------------------------------------------------
4485
17
  //
4486
- // The page's link is `#/name/arg...`, each part URI-encoded. `go` pushes a
4487
- // history entry; back, forward and links to a screen change the hash, and the
4488
- // host passes the new route to `ui-route`.
4489
-
4490
- /** The screens face of the page. */
4491
- let screensFace: ObjectCell | null = null;
4492
- let comingScreen: HTMLElement | null = null; // the screen being made, not on the page yet
4493
- /** Where a change of screen is announced. */
4494
- let screenNews: HTMLElement | null = null;
4495
-
4496
- function routeParts(): string[] {
4497
- const h = location.hash.replace(/^#\/?/, '');
4498
- if (h === '') return [];
4499
- return h.split('/').map(p => {
4500
- try { return decodeURIComponent(p); } catch { return p; }
4501
- });
4502
- }
4503
-
4504
- function routeBlock(): BlockCell {
4505
- return blockOf(K.Block, routeParts().map(p => string(p)));
4506
- }
4507
-
4508
- /** `#/client/42` for the word `client` or the path `client/42`; null for anything else. */
4509
- function screenHref(v: Cell): string | null {
4510
- const part = (c: Cell): string => encodeURIComponent(c.t === K.String ? text(c as StringCell) : c.t === K.Word ? spell((c as WordCell).sym) : form(c));
4511
- if (v.t === K.Word) return '#/' + part(v);
4512
- if (v.t === K.Path) return '#/' + v.s.data.slice(v.i).map(part).join('/');
4513
- return null;
4514
- }
18
+ // This file boots the page and holds the natives the UI dialect calls (show,
19
+ // repaint, apply-theme); the rest lives in browser/, one file per part:
20
+ // mount.ts builds a face's node, sync.ts copies fields to it, and each kind of
21
+ // face or behaviour (tables.ts, menus.ts, drag.ts, calendar.ts...) has its own.
4515
22
 
4516
- native('route', '["The screen and arguments in the address bar." ]', () => value(routeBlock()));
4517
23
 
4518
- // Where the page stands in the browser's history: how many of its screens lie behind the
4519
- // current one (depth) and how far forward it has been (top). Each entry keeps both in
4520
- // history.state, so back, forward and a reload find them again.
4521
- let here = { depth: 0, top: 0 };
4522
-
4523
- /** At start: an entry with no state is the first of the page. */
4524
- function startHistory(): void {
4525
- const state = history.state as { depth?: number; top?: number } | null;
4526
- if (typeof state?.depth === 'number') here = { depth: state.depth, top: state.top ?? state.depth };
4527
- history.replaceState({ ...here }, '');
4528
- }
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
-
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. */
4535
- function landHistory(): void {
4536
- const state = history.state as { depth?: number } | null;
4537
- before = { ...here };
4538
- if (typeof state?.depth === 'number') here = { depth: state.depth, top: here.top };
4539
- else here = { depth: here.depth + 1, top: here.depth + 1 };
4540
- history.replaceState({ ...here }, '');
4541
- }
4542
-
4543
- native('set-route', '["Puts a screen and arguments in the address bar." route [block!] replace [logic!]]', (_t, f) => {
4544
- const href = screenHref({ ...(f.args[0] as BlockCell), t: K.Path } as Cell) ?? '#/';
4545
- const replace = f.args[1]!.t === K.Logic && f.args[1]!.v;
4546
- if (replace) {
4547
- history.replaceState({ ...here }, '', href);
4548
- return value(f.args[0]!);
4549
- }
4550
- // a new screen after going back drops the ones ahead, as the browser does
4551
- here = { depth: here.depth + 1, top: here.depth + 1 };
4552
- history.pushState({ ...here }, '', href);
4553
- return value(f.args[0]!);
4554
- });
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
-
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)])));
24
+ import { K, NONE, native, value, getWord, intern, spell, text, type ObjectCell, type StringCell } from '../core/index.ts';
25
+ import { startHost, startUi, runSource, report, activeLanguage } from './index.ts';
26
+ import { spawn } from './scheduler.ts';
27
+ import { DEFAULT_THEME, LOOKS, THEME_WORDS, type ThemeParams } from './theme.ts';
28
+ import { interCss } from './fonts.ts';
29
+ import { addBuiltIn, builtInText } from './modules.ts';
30
+ import { devLog } from './devlog.ts';
31
+ import { startDevtools } from './devtools.ts';
32
+ import { get, str, showOwn, word, children } from './browser/faces.ts';
33
+ import { host, byNode, byCtx, dirty, fire, showError, build, setHost } from './browser/mount.ts';
34
+ import { seenKeys, setViewKeys } from './browser/events.ts';
35
+ import { swipe, onSwipeMove, onSwipeEnd, outsideSwipe } from './browser/swipe.ts';
36
+ import { mountedAbove, dragging, endDrag, onPointerDown, onPointerMove, onReorderKey } from './browser/drag.ts';
37
+ import { onKeyDown, onViewKey } from './browser/keys.ts';
38
+ import { onRowsMoved, onPrint } from './browser/tables.ts';
39
+ import { stepsLanded, undoToasts } from './browser/dialogs.ts';
40
+ import { sync, react, syncDirty } from './browser/sync.ts';
41
+ import { screensFace, routeBlock, here, startHistory, undoing, landHistory, unsaved, setScreensFace, setHere, setUndoing } from './browser/screens.ts';
42
+ import { root, titleFace, setSheet, setTheme, setRoot, setRootFace, setTitleFace } from './browser/page.ts';
43
+ // every part, for what it does as it loads (natives, listeners)
44
+ import './browser/faces.ts';
45
+ import './browser/mount.ts';
46
+ import './browser/events.ts';
47
+ import './browser/swipe.ts';
48
+ import './browser/drag.ts';
49
+ import './browser/menus.ts';
50
+ import './browser/calendar.ts';
51
+ import './browser/times.ts';
52
+ import './browser/keys.ts';
53
+ import './browser/count.ts';
54
+ import './browser/fields.ts';
55
+ import './browser/uploads.ts';
56
+ import './browser/widget.ts';
57
+ import './browser/lookup.ts';
58
+ import './browser/drawings.ts';
59
+ import './browser/orbits.ts';
60
+ import './browser/row-faces.ts';
61
+ import './browser/richtext.ts';
62
+ import './browser/tables.ts';
63
+ import './browser/trees.ts';
64
+ import './browser/toolbars.ts';
65
+ import './browser/dialogs.ts';
66
+ import './browser/sync.ts';
67
+ import './browser/screens.ts';
68
+ import './browser/page.ts';
4575
69
 
4576
- native('route-back', '["Goes one step back in the history." ]', () => {
4577
- if (here.depth === 0) return value(logic(false));
4578
- history.back();
4579
- return value(logic(true));
4580
- });
70
+ // --- natives -----------------------------------------------------------------------
4581
71
 
4582
- native('route-forward', '["Goes one step forward in the history." ]', () => {
4583
- if (here.depth >= here.top) return value(logic(false));
4584
- history.forward();
4585
- return value(logic(true));
72
+ native('ui-watch', '["Marks an object a reaction reads, so that a change to it runs the reactions at the end of the round." object [object!]]', (_t, f) => {
73
+ const o = f.args[0] as ObjectCell;
74
+ o.ctx.watch = dirty;
75
+ return value(o);
4586
76
  });
4587
77
 
4588
- /** After code showed another screen: focus it and announce its title. */
4589
- function enteredScreen(box: HTMLElement): void {
4590
- const screen = box.firstElementChild as HTMLElement | null;
4591
- if (screen === null) return;
4592
- const heading = screen.querySelector<HTMLElement>('h1, h2');
4593
- const target = heading ?? screen;
4594
- if (target.tabIndex < 0) target.tabIndex = -1;
4595
- target.focus({ preventScroll: true });
4596
- window.scrollTo(0, 0);
4597
- if (screenNews === null) {
4598
- screenNews = el('div', 'tb-sr-only');
4599
- screenNews.setAttribute('aria-live', 'polite');
4600
- document.body.append(screenNews);
4601
- }
4602
- const news = screenNews;
4603
- news.textContent = '';
4604
- setTimeout(() => { news.textContent = screen.getAttribute('aria-label') ?? ''; }, 50);
4605
- }
4606
-
4607
- // --- natives -----------------------------------------------------------------------
4608
-
4609
78
  native('repaint', '["Redraws the faces that changed." ]', () => {
4610
79
  // after a change of language: every mounted face shows its values again
4611
80
  document.documentElement.lang = activeLanguage(host.rt);
@@ -4618,24 +87,21 @@ native('repaint', '["Redraws the faces that changed." ]', () => {
4618
87
  return value(NONE);
4619
88
  });
4620
89
 
4621
- let root: HTMLElement | null = null;
4622
- /** The face whose text is the page title: the view's title, or the screen shown. */
4623
- let titleFace: ObjectCell | null = null;
4624
-
4625
90
  native('show', '["Draws a face and everything in it." face [object!]]', (_t, f) => {
4626
91
  const face = f.args[0] as ObjectCell;
4627
- viewKeys = null;
4628
- screensFace = null;
92
+ setRootFace(face);
93
+ setViewKeys(null);
94
+ setScreensFace(null);
4629
95
  document.documentElement.lang = activeLanguage(host.rt);
4630
96
  const node = build(face);
4631
97
  if (root !== null) root.replaceWith(node);
4632
98
  else document.body.append(node);
4633
- root = node;
99
+ setRoot(node);
4634
100
  const title = children(face).find(c => word(c, 'style') === 'title');
4635
101
  // a screen names the page itself
4636
102
  if (title !== undefined && screensFace === null) {
4637
103
  document.title = str(title, 'text') ?? document.title;
4638
- titleFace = title;
104
+ setTitleFace(title);
4639
105
  }
4640
106
  return value(face);
4641
107
  });
@@ -4666,16 +132,6 @@ export function themeParams(obj: ObjectCell): ThemeParams {
4666
132
  return p;
4667
133
  }
4668
134
 
4669
- function setTheme(p: ThemeParams): void {
4670
- let tag = document.getElementById('tb-theme');
4671
- if (tag === null) {
4672
- tag = el('style');
4673
- tag.id = 'tb-theme';
4674
- document.head.append(tag);
4675
- }
4676
- tag.textContent = themeCss(p);
4677
- }
4678
-
4679
135
  native('apply-theme', '["Changes the look of the whole screen." spec [object!]]', (_t, f) => {
4680
136
  setTheme(themeParams(f.args[0] as ObjectCell));
4681
137
  return value(f.args[0]!);
@@ -4691,19 +147,25 @@ async function boot(): Promise<void> {
4691
147
  addBuiltIn(new URL(path, location.href).href, src);
4692
148
  }
4693
149
  }
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);
150
+ if (document.querySelector('style[data-tb-fonts], link[data-tb-fonts]') === null) {
151
+ setSheet('fonts', interCss(file => new URL(`fonts/${file}`, import.meta.url).href));
4699
152
  }
4700
153
  setTheme(DEFAULT_THEME);
4701
- host = startHost({ onError: e => showError(report(e)) });
154
+ setHost(startHost({ onError: e => showError(report(e)) }));
4702
155
  host.sch.afterPump = () => {
4703
156
  react();
4704
157
  syncDirty();
4705
158
  devLog.repainted();
4706
159
  };
160
+ // an answer kept by cached that comes: the reactions that read it run
161
+ const news = getWord({ t: K.Word, sym: intern('ui-cache-news'), bind: host.rt.lib });
162
+ if (news?.t === K.Object) news.ctx.watch = dirty;
163
+ // the page back into view: what cached kept is asked again
164
+ document.addEventListener('visibilitychange', () => {
165
+ if (document.visibilityState === 'visible') spawn(host.sch, { data: [{ t: K.Word, sym: intern('ui-caches-again'), bind: host.rt.lib }] }, 0);
166
+ // hidden, maybe closed: what waits for a notice to go is done now (its requests are sent with keepalive)
167
+ else if (undoToasts.size > 0) spawn(host.sch, { data: [{ t: K.Word, sym: intern('ui-toasts-done'), bind: host.rt.lib }] }, 0);
168
+ });
4707
169
  document.addEventListener('keydown', onKeyDown, true);
4708
170
  document.addEventListener('keydown', onReorderKey);
4709
171
  // a scroll anywhere: the page, a scroll face, a dialog
@@ -4716,9 +178,15 @@ async function boot(): Promise<void> {
4716
178
  document.addEventListener('pointermove', onPointerMove, { passive: false });
4717
179
  document.addEventListener('pointerup', () => endDrag(true));
4718
180
  document.addEventListener('pointercancel', () => endDrag(false));
181
+ document.addEventListener('pointermove', onSwipeMove, { passive: false });
182
+ document.addEventListener('pointerup', onSwipeEnd);
183
+ document.addEventListener('pointercancel', onSwipeEnd);
184
+ document.addEventListener('pointerdown', outsideSwipe, true);
185
+ document.addEventListener('scroll', outsideSwipe, { capture: true, passive: true });
186
+ addEventListener('resize', outsideSwipe);
4719
187
  document.addEventListener('keydown', ev => { if (ev.key === 'Escape' && dragging?.on) { ev.preventDefault(); seenKeys.add(ev); endDrag(false); } }, true);
4720
188
  // a touch drag must not scroll the page
4721
- document.addEventListener('touchmove', ev => { if (dragging?.on) ev.preventDefault(); }, { passive: false });
189
+ document.addEventListener('touchmove', ev => { if (dragging?.on || swipe?.on) ev.preventDefault(); }, { passive: false });
4722
190
  document.addEventListener('keydown', onViewKey);
4723
191
  const devMark = document.querySelector('meta[name="trebol-dev"]');
4724
192
  if (devMark !== null) {
@@ -4740,10 +208,11 @@ async function boot(): Promise<void> {
4740
208
  });
4741
209
  }
4742
210
  startHistory();
211
+ window.addEventListener('popstate', stepsLanded);
4743
212
  window.addEventListener('hashchange', () => {
4744
213
  if (undoing !== null) {
4745
- here = undoing;
4746
- undoing = null;
214
+ setHere(undoing);
215
+ setUndoing(null);
4747
216
  history.replaceState({ ...here }, '');
4748
217
  return;
4749
218
  }
@@ -4764,3 +233,4 @@ async function boot(): Promise<void> {
4764
233
  }
4765
234
 
4766
235
  void boot();
236
+