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
package/src/host/index.ts CHANGED
@@ -5,18 +5,20 @@ import './natives.ts';
5
5
  import './net.ts';
6
6
  import './page.ts';
7
7
  import './compress.ts';
8
+ import './share.ts';
8
9
  import './locale.ts';
9
10
  import { setLoader, defaultLoader, type Loader } from './modules.ts';
10
11
  import {
11
- K, makeRuntime, load, bindSeries, doSource, scriptStart, errorMessage, form, mold,
12
+ makeRuntime, load, bindSeries, runSync, scriptStart, errorMessage, form,
12
13
  LIBRARY_FILES, type Cell, type ObjectCell, type Runtime,
13
14
  } from '../core/index.ts';
14
15
  import { makeScheduler, spawn, taskResult, type Scheduler } from './scheduler.ts';
15
16
 
16
17
  export { output } from './natives.ts';
17
18
  export { fileHandle } from './net.ts';
19
+ export { setShareEnv, type ShareEnv, type ChannelLike, type LocksLike, type Envelope } from './share.ts';
18
20
  export { page } from './page.ts';
19
- export { mapAt, formatLocal, activeLanguage, shown, translate, uiText, editLocal, readLocal, readDate, weekStart, fileSize, LOCAL_KINDS } from './locale.ts';
21
+ export { mapAt, formatLocal, activeLanguage, shown, translate, uiText, editLocal, readLocal, readDate, readRange, readTime, weekStart, fileSize, LOCAL_KINDS, amountOf, countStep } from './locale.ts';
20
22
  export type { Loader } from './modules.ts';
21
23
  export * from './scheduler.ts';
22
24
 
@@ -31,8 +33,106 @@ fetch: func [
31
33
  url [url! string!]
32
34
  /with "method, headers, body, form, multipart, timeout, full"
33
35
  options [block! object!]
36
+ /local answer
34
37
  ][
35
- http-request url either with [either block? options [make object! options] [options]] [none]
38
+ if all [with block? options] [options: make object! options]
39
+ answer: http-request url either with [options] [none]
40
+ ; what was kept of the same path is old now
41
+ if all [with find [post put patch delete] attempt [to word! select options 'method]] [ui-cache-touched url]
42
+ answer
43
+ ]
44
+
45
+ ; --- answers kept: cached and refresh ---------------------------------------------
46
+ ;
47
+ ; Each url read with cached has an entry; a reaction that reads cached %/x has
48
+ ; the entry's version among its sources, so it runs again when an answer comes.
49
+ ; ui-cache-news counts every answer, for reactions whose url is not written out.
50
+
51
+ ui-cache-entries: copy []
52
+ ui-cache-news: make object! [version: 0]
53
+
54
+ ui-cache-entry: func ["The entry of what cached keeps for a url, made the first time." url /local key e] [
55
+ key: form url
56
+ unless e: select/case ui-cache-entries key [
57
+ e: make object! [url: none answer: none version: 0 stale: true asking: false again: false task: none]
58
+ e/url: url
59
+ append ui-cache-entries reduce [key e]
60
+ ]
61
+ e
62
+ ]
63
+
64
+ ; The path of a url, without the server, the query or the fragment.
65
+ ui-cache-path: func ["The path of a url, without the server, the query or the fragment." url /local s i] [
66
+ s: form url
67
+ if i: find s "#" [s: copy/part s i]
68
+ if i: find s "?" [s: copy/part s i]
69
+ if i: find s "://" [s: any [find skip i 3 "/" copy "/"]]
70
+ s
71
+ ]
72
+
73
+ ; Asks again behind; one request at a time per url, and one more if asked meanwhile.
74
+ ui-cache-ask: func ["Asks again behind for the answer of an entry of cached." e] [
75
+ e/stale: false
76
+ either e/asking [e/again: true] [
77
+ e/asking: true
78
+ e/task: spawn compose [ui-cache-answer (e)]
79
+ ]
80
+ ]
81
+
82
+ ui-cache-answer: func ["Asks for the answer of an entry of cached, and keeps it." e /local r] [
83
+ forever [
84
+ e/again: false
85
+ r: try [fetch e/url]
86
+ either error? :r [
87
+ ; the last answer stays; the next read asks again
88
+ e/stale: true
89
+ print ["cached:" form e/url "--" r/message]
90
+ ] [
91
+ e/answer: :r
92
+ e/version: e/version + 1
93
+ ui-cache-news/version: ui-cache-news/version + 1
94
+ ]
95
+ unless e/again [break]
96
+ ]
97
+ e/asking: false
98
+ ]
99
+
100
+ ; Every url kept is asked again: the page came back into view.
101
+ ui-caches-again: func ["Asks again for every answer cached keeps." /local key e] [
102
+ foreach [key e] ui-cache-entries [ui-cache-ask e]
103
+ ]
104
+
105
+ ; Every url kept is old: it is asked again the next time it is read (a screen is entered).
106
+ ui-caches-old: func ["Marks every answer cached keeps as old: the next read asks again." /local key e] [
107
+ foreach [key e] ui-cache-entries [e/stale: true]
108
+ ]
109
+
110
+ ; A post, put, patch or delete to url: what was kept of its path, or of a path
111
+ ; above or under it (/api/clients for /api/clients/7), is asked again.
112
+ ui-cache-touched: func ["Asks again for what cached keeps of the path of url, or above or under it." url /local key e a b] [
113
+ a: ui-cache-path url
114
+ foreach [key e] ui-cache-entries [
115
+ b: ui-cache-path e/url
116
+ if any [a = b find/match a join b "/" find/match b join a "/"] [ui-cache-ask e]
117
+ ]
118
+ ]
119
+
120
+ cached: func [
121
+ "The last answer to a GET of url, at once (none the first time), and asks again behind: a reaction (is, react) that reads it runs again when the answer comes."
122
+ url [url! string!]
123
+ /local e
124
+ ][
125
+ e: ui-cache-entry url
126
+ if e/stale [ui-cache-ask e]
127
+ e/answer
128
+ ]
129
+
130
+ refresh: func [
131
+ "Asks again for an answer kept by cached, now; reactions that read it run again when it comes."
132
+ url [url! string!]
133
+ ][
134
+ ui-cache-ask ui-cache-entry url
135
+ exit
36
136
  ]
37
137
 
38
138
  show-progress: func [
@@ -183,7 +283,10 @@ export function startHost(opts: HostOptions = {}): Host {
183
283
  const onError = opts.onError ?? (e => console.error(report(e)));
184
284
  const rt = makeRuntime();
185
285
  setLoader(rt, opts.loader ?? defaultLoader());
186
- const r = doSource(rt, HOST_MEZZANINES, 'host');
286
+ // in lib, as the core's mezzanines: a word a program sets never takes the place of one of them
287
+ const code = load(HOST_MEZZANINES, { file: 'host' });
288
+ bindSeries(code.s, rt.lib, true);
289
+ const r = runSync(rt, code);
187
290
  // Host mezzanines failing to load is a bug in Trebol itself.
188
291
  if (r.k === 'error') throw new Error(`host mezzanines failed: ${errorMessage(r.e)}`);
189
292
  const sch = makeScheduler(rt, e => onError(e));
@@ -3,10 +3,44 @@
3
3
  // core keeps its own language-neutral form/mold.
4
4
 
5
5
  import {
6
- K, native, value, string, form, text, formatDec, spell, ctxFind, intern,
6
+ K, native, value, string, form, text, formatDec, spell, ctxFind, intern, integer, decimal, percent, money, dec,
7
+ decToNumber, I64,
7
8
  type Cell, type ObjectCell, type StringCell, type WordCell, type MapCell, type Runtime,
8
9
  } from '../core/index.ts';
9
10
 
11
+ /** How much a number, a percent or an amount is, as a JavaScript number; null for anything else. */
12
+ export function amountOf(c: Cell): number | null {
13
+ switch (c.t) {
14
+ case K.Integer: return I64.toNumber(c.v);
15
+ case K.Decimal: case K.Percent: return c.v;
16
+ case K.Money: return decToNumber(c.v);
17
+ default: return null;
18
+ }
19
+ }
20
+
21
+ /** The digits after the point a decimal number is written with. */
22
+ function fractionDigits(n: number): number {
23
+ const m = /\.(\d+)|e-(\d+)/.exec(String(n));
24
+ return m === null ? 0 : m[1] !== undefined ? m[1].length : Number(m[2]);
25
+ }
26
+
27
+ /**
28
+ * What a number that counts shows at x on its way to `to` (a text with `count`): a value of the kind of `to`,
29
+ * with no more digits than it has, so the run reads as the number it ends on.
30
+ */
31
+ export function countStep(to: Cell, x: number): Cell {
32
+ switch (to.t) {
33
+ case K.Integer: return integer(Math.round(x));
34
+ case K.Money: return money(dec(BigInt(Math.round(x * 10 ** to.v.e)), to.v.e), to.cur);
35
+ case K.Decimal: case K.Percent: {
36
+ const k = 10 ** fractionDigits(to.v);
37
+ const v = Math.round(x * k) / k;
38
+ return to.t === K.Decimal ? decimal(v) : percent(v);
39
+ }
40
+ default: return to;
41
+ }
42
+ }
43
+
10
44
  /** The kinds `localize` formats; anything else shows as `form` gives it. */
11
45
  export const LOCAL_KINDS: ReadonlySet<number> = new Set([K.Date, K.Time, K.Integer, K.Decimal, K.Percent, K.Money]);
12
46
 
@@ -121,6 +155,38 @@ export function readDate(s: string, lang: string): string | null {
121
155
  return `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
122
156
  }
123
157
 
158
+ /**
159
+ * Two dates typed for a range, as `2026-11-03 2026-11-10` with the start first, or null. They are
160
+ * written apart by a dash with spaces around it, as `3/11/2026 – 10/11/2026` or `3/11/2026 - 10/11/2026`,
161
+ * or by a space alone; a range typed end first is turned round.
162
+ */
163
+ export function readRange(s: string, lang: string): string | null {
164
+ let parts = s.trim().split(/\s*[\u2013\u2014]\s*|\s+-\s+/);
165
+ if (parts.length === 1) parts = s.trim().split(/\s+/);
166
+ if (parts.length !== 2) return null;
167
+ const [a, b] = parts.map(p => readDate(p, lang));
168
+ if (a == null || b == null) return null;
169
+ return a <= b ? `${a} ${b}` : `${b} ${a}`;
170
+ }
171
+
172
+ /**
173
+ * A time typed in any language, as `09:30`, or null: `9:30`, `9.30`, `9h30`, `930`, `21`, and with am or pm,
174
+ * `9:30 pm` or `9pm`. Minutes go from 00 to 59 and hours from 0 to 23, or 1 to 12 with am or pm.
175
+ */
176
+ export function readTime(s: string): string | null {
177
+ const t = /^(\d{1,2})(?:\s*[:.h]\s*(\d{2})|(\d{2}))?\s*h?\s*(?:([ap])\.?\s*m\.?)?$/i.exec(s.trim());
178
+ if (t === null) return null;
179
+ let h = Number(t[1]);
180
+ const m = Number(t[2] ?? t[3] ?? 0);
181
+ const half = t[4]?.toLowerCase();
182
+ if (m > 59) return null;
183
+ if (half !== undefined) {
184
+ if (h < 1 || h > 12) return null;
185
+ h = (h % 12) + (half === 'p' ? 12 : 0);
186
+ } else if (h > 23) return null;
187
+ return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
188
+ }
189
+
124
190
  /** The first day of the week in a language, 1 for Monday to 7 for Sunday. */
125
191
  export function weekStart(lang: string): number {
126
192
  try {
@@ -136,8 +202,8 @@ export function weekStart(lang: string): number {
136
202
 
137
203
  /** The active language: `i18n/language` of the user context, `en` if there is none. */
138
204
  export function activeLanguage(rt: Runtime): string {
139
- const i = ctxFind(rt.user, intern('i18n'));
140
- const obj = i < 0 ? null : rt.user.vals[i]!;
205
+ const i = ctxFind(rt.lib, intern('i18n'));
206
+ const obj = i < 0 ? null : rt.lib.vals[i]!;
141
207
  if (obj === null || obj.t !== K.Object) return 'en';
142
208
  const o = obj as ObjectCell;
143
209
  const j = ctxFind(o.ctx, intern('language'));
@@ -149,8 +215,8 @@ export function activeLanguage(rt: Runtime): string {
149
215
 
150
216
  /** A field of the user's `i18n` object, or null. */
151
217
  function i18nField(rt: Runtime, name: string): Cell | null {
152
- const i = ctxFind(rt.user, intern('i18n'));
153
- const obj = i < 0 ? null : rt.user.vals[i]!;
218
+ const i = ctxFind(rt.lib, intern('i18n'));
219
+ const obj = i < 0 ? null : rt.lib.vals[i]!;
154
220
  if (obj === null || obj.t !== K.Object) return null;
155
221
  const j = ctxFind((obj as ObjectCell).ctx, intern(name));
156
222
  return j < 0 ? null : (obj as ObjectCell).ctx.vals[j]!;
@@ -157,3 +157,12 @@ export function appendText(src: string, text: string): string {
157
157
  export function safeHref(href: string): boolean {
158
158
  return /^(https?:|mailto:)/i.test(href.trim());
159
159
  }
160
+
161
+ /** What a link face may open: web, mail and phone addresses and addresses with no scheme (a path,
162
+ * a #screen); anything else (javascript:, data:...) is null. Spaces before it and tabs or line
163
+ * breaks inside it are dropped first, as the browser does, so "java\tscript:" is caught too. */
164
+ export function linkHref(href: string): string | null {
165
+ const plain = href.replace(/[\t\n\r]/g, '').replace(/^[\x00-\x20]+/, '');
166
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(plain);
167
+ return scheme === null || /^(https?|mailto|tel)$/i.test(scheme[1]!) ? href : null;
168
+ }
@@ -11,6 +11,13 @@
11
11
  //
12
12
  // A `.js` file is a JavaScript module instead (js.ts).
13
13
  //
14
+ // `import 'trebol-es` imports a package by its name: the first node_modules/trebol-es/
15
+ // found going up from the importing file (from the page or the working directory when
16
+ // no file imports it), as Node finds packages. Its package.json says which file is the
17
+ // module, `"trebol": "es.trb"`. The same loader reads it, so this works on a disk and
18
+ // over http alike; `trebol build` puts the package's files inside the page where the
19
+ // page finds them, under node_modules/.
20
+ //
14
21
  // `do %file` runs a script in the user context each time; `read` gives a
15
22
  // file's text and `load %file` its values.
16
23
  //
@@ -18,8 +25,8 @@
18
25
 
19
26
  import {
20
27
  K, NONE, UNSET, native, value, text, load, mold, string, context, collectSetWords, bindSeries, bindSelf,
21
- copyDeep, setWord, getWord, splice, currentFile, throwError, makeError, scriptStart, LoadError, T, canon, intern,
22
- type Cell, type BlockCell, type StringCell, type ObjectCell, type Runtime, type WordCell, type Series, type Task,
28
+ copyDeep, setWord, getWord, splice, currentFile, throwError, makeError, scriptStart, LoadError, T, canon, intern, spell, LIBRARY_FILES, blockOf,
29
+ type Cell, type BlockCell, type StringCell, type ObjectCell, type Runtime, type WordCell, type Series, type Task, type Step, type NativeFrame,
23
30
  } from '../core/index.ts';
24
31
  import { jsModule } from './js.ts';
25
32
 
@@ -74,6 +81,7 @@ const EXPORTS = canon(intern('exports'));
74
81
  const EXPORT = canon(intern('export'));
75
82
  const TYPE = canon(intern('type'));
76
83
  const MODULE = canon(intern('module'));
84
+ const PARTS = canon(intern('parts'));
77
85
 
78
86
  /** The value after `name:` in a script header, or null. */
79
87
  function headerField(header: BlockCell | null, name: number): Cell | null {
@@ -170,15 +178,74 @@ native('do-file', '["Runs the script in a file, as do does; a module is imported
170
178
  return { k: 'do', s: code.s, i: start };
171
179
  });
172
180
 
173
- interface ImportState { href: string; entry: ModuleEntry; ctx: ReturnType<typeof context> | null; exports: WordCell[] }
181
+ interface ImportState {
182
+ href: string; entry: ModuleEntry; ctx: ReturnType<typeof context> | null; exports: WordCell[]; lib?: boolean;
183
+ /** The module's code, kept while its parts are read. */
184
+ code?: BlockCell; start?: number; parts?: string[];
185
+ /** What runs, each part and then the module's own body, and which of them runs now. */
186
+ bodies?: Series<Cell>[]; at?: number;
187
+ }
188
+
189
+ /** Package names as npm takes them, without a scope (a scope does not fit in a word). */
190
+ const PACKAGE_NAME = /^[a-z0-9][a-z0-9._-]*$/;
191
+
192
+ /** The href of a package's module: the "trebol" file of the first node_modules/<name>/ going up from `from`. */
193
+ async function packageModule(loader: Loader, from: string, name: string): Promise<Cell> {
194
+ let dir = new URL('./', from);
195
+ for (;;) {
196
+ const at = new URL(`node_modules/${name}/`, dir).href;
197
+ const json = builtIn.get(`${at}package.json`) ?? await loader.read(`${at}package.json`).catch(() => null);
198
+ if (json !== null) {
199
+ let main: unknown;
200
+ try {
201
+ main = (JSON.parse(json) as { trebol?: unknown }).trebol;
202
+ } catch {
203
+ throw makeError('access', 'cannot-open', `the package.json of ${name} is not JSON`);
204
+ }
205
+ if (typeof main !== 'string') throw makeError('access', 'cannot-open', `${name} is not a Trebol package: its package.json has no "trebol" file`);
206
+ return string(new URL(main, at).href);
207
+ }
208
+ if (dir.pathname === '/' || dir.protocol !== 'file:' && dir.protocol !== 'http:' && dir.protocol !== 'https:') break;
209
+ dir = new URL('../', dir);
210
+ }
211
+ throw makeError('access', 'cannot-open', `cannot find the package ${name}: no node_modules/${name}/package.json`);
212
+ }
213
+
214
+ /** Binds the bodies of a module (its parts, then its own code) to one context and runs the first. */
215
+ function startModule(rt: Runtime, f: NativeFrame, st: ImportState, bodies: Series<Cell>[]): Step {
216
+ for (const b of bodies) st.exports.push(...takeExports(b));
217
+ const ctx = context();
218
+ ctx.self = true;
219
+ for (const b of bodies) collectSetWords(b, 0, ctx);
220
+ // Trebol's own modules (the UI dialect) see lib, as R3's modules do, so a word a program sets,
221
+ // form: or can?, never takes the place of one they use; their exports go to lib too
222
+ for (const b of bodies) {
223
+ bindSeries(b, st.lib ? rt.lib : rt.user, true);
224
+ bindSeries(b, ctx);
225
+ bindSelf(b, ctx);
226
+ }
227
+ st.ctx = ctx;
228
+ st.bodies = bodies;
229
+ st.at = 0;
230
+ f.phase = 2;
231
+ f.trap = 1 << T.Error;
232
+ return { k: 'do', s: bodies[0]!, i: 0 };
233
+ }
174
234
 
175
- native('import', '["Runs a module and gives its exports." source [file! url! string!]]', (t, f, v) => {
235
+ native('import', '["Runs a module and gives its exports; a word is a package by its name, from node_modules." source [file! url! string! word!]]', (t, f, v) => {
176
236
  const rt = t.rt;
177
237
  const loader = loaders.get(rt);
178
238
  const mods = modules.get(rt);
179
239
  if (loader === undefined || mods === undefined) return throwError('access', 'no-loader', 'this host cannot load modules');
180
- if (f.phase === 0) {
181
- const href = hrefOf(t, loader, f.args[0]!);
240
+ // a package: where its module is comes first, then it is imported as a file is
241
+ if (f.phase === 0 && f.args[0]!.t === K.Word) {
242
+ const name = spell((f.args[0] as WordCell).sym);
243
+ if (!PACKAGE_NAME.test(name)) return throwError('script', 'bad-module', `${name} is not the name of a package`);
244
+ f.phase = 5;
245
+ return { k: 'await', p: packageModule(loader, resolve(loader.base, currentFile(t), './'), name) };
246
+ }
247
+ if (f.phase === 0 || f.phase === 5) {
248
+ const href = f.phase === 5 ? text(v as StringCell) : hrefOf(t, loader, f.args[0]!);
182
249
  const known = mods.get(href);
183
250
  if (known !== undefined) {
184
251
  if (known.obj !== null) return value(known.obj);
@@ -231,10 +298,9 @@ native('import', '["Runs a module and gives its exports." source [file! url! str
231
298
  mods.delete(st.href);
232
299
  st.entry.settle(false, e);
233
300
  };
234
- if (f.phase === 1) {
235
- let code: BlockCell;
301
+ const loadIt = (src: Cell, file: string): BlockCell | Step => {
236
302
  try {
237
- code = load(text(v as StringCell), { file: st.href });
303
+ return load(text(src as StringCell), { file });
238
304
  } catch (e) {
239
305
  // LoadError is the one exception on the normal path; it becomes a value here.
240
306
  if (!(e instanceof LoadError)) throw e;
@@ -242,21 +308,50 @@ native('import', '["Runs a module and gives its exports." source [file! url! str
242
308
  if (step.k === 'throw') failed(step.e.v);
243
309
  return step;
244
310
  }
311
+ };
312
+ if (f.phase === 1) {
313
+ const code = loadIt(v!, st.href);
314
+ if ('k' in code) return code;
245
315
  const { header, start } = scriptStart(code);
246
316
  const listed = headerField(header, EXPORTS);
247
317
  if (listed !== null && listed.t === K.Block) st.exports = listed.s.data.filter(w => w.t === K.Word) as WordCell[];
248
- const body = copyDeep(code.s, start);
249
- st.exports.push(...takeExports(body));
250
- const ctx = context();
251
- ctx.self = true;
252
- collectSetWords(body, 0, ctx);
253
- bindSeries(body, rt.user, true);
254
- bindSeries(body, ctx);
255
- bindSelf(body, ctx);
256
- st.ctx = ctx;
257
- f.phase = 2;
258
- f.trap = 1 << T.Error;
259
- return { k: 'do', s: body, i: 0 };
318
+ st.lib = LIBRARY_FILES.has(st.href);
319
+ // parts: [%a.trb %b.trb] are files of the same module, read before it runs
320
+ const parts = headerField(header, PARTS);
321
+ if (parts !== null) {
322
+ const files = parts.t === K.Block ? parts.s.data.slice(parts.i) : [];
323
+ if (files.length === 0 || files.some(x => x.t !== K.File)) {
324
+ const step = throwError('script', 'bad-module', 'parts: takes a block of files');
325
+ if (step.k === 'throw') failed(step.e.v);
326
+ return step;
327
+ }
328
+ st.code = code;
329
+ st.start = start;
330
+ st.parts = files.map(x => new URL(text(x as StringCell), st.href).href);
331
+ // the parts of Trebol's own modules are Trebol's own code too
332
+ if (st.lib) for (const h of st.parts) LIBRARY_FILES.add(h);
333
+ f.phase = 6;
334
+ const loader = loaders.get(rt)!;
335
+ return { k: 'await', p: Promise.all(st.parts.map((h, i) => readText(loader, h, files[i]!))).then(texts => blockOf(K.Block, texts)) };
336
+ }
337
+ return startModule(rt, f, st, [copyDeep(code.s, start)]);
338
+ }
339
+ if (f.phase === 6) {
340
+ const bodies: Series<Cell>[] = [];
341
+ const texts = (v as BlockCell).s.data;
342
+ for (let i = 0; i < texts.length; i++) {
343
+ const part = loadIt(texts[i]!, st.parts![i]!);
344
+ if ('k' in part) return part;
345
+ bodies.push(copyDeep(part.s, scriptStart(part).start));
346
+ }
347
+ bodies.push(copyDeep(st.code!.s, st.start!));
348
+ st.code = undefined;
349
+ return startModule(rt, f, st, bodies);
350
+ }
351
+ // a part ran: the next one, or the module's own body
352
+ if (f.phase === 2 && f.thrown === null && st.at! + 1 < st.bodies!.length) {
353
+ st.at!++;
354
+ return { k: 'do', s: st.bodies![st.at!]!, i: 0 };
260
355
  }
261
356
  // phase 2: the module body ran
262
357
  if (f.thrown !== null) {
@@ -273,6 +368,7 @@ native('import', '["Runs a module and gives its exports." source [file! url! str
273
368
  if (step.k === 'throw') failed(step.e.v);
274
369
  return step;
275
370
  }
371
+ if (st.lib) setWord({ t: K.Word, sym: w.sym, bind: rt.lib }, st.ctx!.vals[i]!);
276
372
  setWord({ t: K.Word, sym: w.sym, bind: rt.user }, st.ctx!.vals[i]!);
277
373
  }
278
374
  st.entry.obj = obj;
@@ -0,0 +1,204 @@
1
+ // How the page moves when it changes: a screen that gives way to another, rows
2
+ // that come, go or change places, a face shown or hidden. Nothing here is asked
3
+ // for by the app; the theme's --tb-move and --tb-ease say how long and how, and a
4
+ // user who asks the system for less motion gets none.
5
+
6
+ /** The theme's time for a change of place, in ms, read from the page once. */
7
+ let moveMs = -1;
8
+
9
+ function duration(): number {
10
+ if (moveMs < 0) {
11
+ const v = getComputedStyle(document.documentElement).getPropertyValue('--tb-move').trim();
12
+ moveMs = v.endsWith('ms') ? parseFloat(v) : v.endsWith('s') ? parseFloat(v) * 1000 : 220;
13
+ if (!Number.isFinite(moveMs)) moveMs = 220;
14
+ }
15
+ return moveMs;
16
+ }
17
+
18
+ /** The theme changed: read its time again. */
19
+ export function themeMoved(): void {
20
+ moveMs = -1;
21
+ }
22
+
23
+ const EASE = 'cubic-bezier(0.2, 0, 0, 1)';
24
+
25
+ /** Whether the page may move now: the browser can, the user has not asked for less, the page is on show. */
26
+ export function mayMove(): boolean {
27
+ if (typeof matchMedia !== 'function' || typeof Element.prototype.animate !== 'function') return false;
28
+ if (matchMedia('(prefers-reduced-motion: reduce)').matches) return false;
29
+ return document.visibilityState !== 'hidden' && duration() > 0;
30
+ }
31
+
32
+ // --- screens ---------------------------------------------------------------------
33
+
34
+ /** Which way the user went to the screen coming: on, or back to one seen before. */
35
+ let travel: 'on' | 'back' = 'on';
36
+
37
+ export function travelled(way: 'on' | 'back'): void {
38
+ travel = way;
39
+ }
40
+
41
+ let swapping = false;
42
+
43
+ /**
44
+ * Puts the screen coming in place of the one on show: the browser takes a picture of
45
+ * the page, swap changes it, and the old screen slides out as the new one slides in,
46
+ * the way the user went. Faces given the same `morph` in both become one another.
47
+ * swap is called once, now or at the browser's next frame; it may decide not to.
48
+ */
49
+ export function changeScreen(box: HTMLElement, coming: HTMLElement, swap: () => void): void {
50
+ const doc = document as Document & { startViewTransition?: (update: () => void) => { finished: Promise<void> } };
51
+ // the first screen, or a page that cannot or may not move
52
+ const way = travel;
53
+ travel = 'on';
54
+ if (swapping) return;
55
+ if (box.childElementCount === 0 || typeof doc.startViewTransition !== 'function' || !mayMove()) return swap();
56
+ swapping = true;
57
+ const root = document.documentElement;
58
+ root.dataset['tbTravel'] = way;
59
+ box.style.setProperty('view-transition-name', 'tb-screen');
60
+ // only the names in both screens: a face with no partner goes with its screen
61
+ const both = morphsIn(coming);
62
+ const was = nameMorphs(both);
63
+ const t = doc.startViewTransition(() => {
64
+ swapping = false;
65
+ clearMorphs();
66
+ swap();
67
+ nameMorphs(was);
68
+ });
69
+ void t.finished.catch(() => {}).then(() => {
70
+ box.style.removeProperty('view-transition-name');
71
+ delete root.dataset['tbTravel'];
72
+ clearMorphs();
73
+ });
74
+ }
75
+
76
+ /** The faces given a morph name for the change of screen going on. */
77
+ let named: HTMLElement[] = [];
78
+
79
+ /**
80
+ * Gives the browser the morph name of each face on show that has one among those
81
+ * given, so a face of the old screen and one of the new with the same name become
82
+ * one another; when two on show share a name, the first keeps it. Gives the names given.
83
+ */
84
+ function nameMorphs(among: Set<string>): Set<string> {
85
+ const seen = new Set<string>();
86
+ for (const e of Array.from(document.querySelectorAll<HTMLElement>('[data-tb-morph]'))) {
87
+ const name = morphIdent(e.dataset['tbMorph']!);
88
+ if (!among.has(name) || seen.has(name) || e.getClientRects().length === 0) continue;
89
+ seen.add(name);
90
+ e.style.setProperty('view-transition-name', name);
91
+ named.push(e);
92
+ }
93
+ return seen;
94
+ }
95
+
96
+ /** The morph names of a screen not yet on the page. */
97
+ function morphsIn(screen: HTMLElement): Set<string> {
98
+ return new Set(Array.from(screen.querySelectorAll<HTMLElement>('[data-tb-morph]'), e => morphIdent(e.dataset['tbMorph']!)));
99
+ }
100
+
101
+ function clearMorphs(): void {
102
+ for (const e of named) e.style.removeProperty('view-transition-name');
103
+ named = [];
104
+ }
105
+
106
+ /** A name as the browser takes it: letters, digits, - and _, anything else spelled by its code. */
107
+ export function morphIdent(name: string): string {
108
+ let out = 'tb-m-';
109
+ for (const ch of name) out += /[A-Za-z0-9_-]/.test(ch) ? ch : `_${ch.codePointAt(0)!.toString(16)}_`;
110
+ return out;
111
+ }
112
+
113
+ // --- rows --------------------------------------------------------------------------
114
+
115
+ /** Where each row stood before the rows changed. */
116
+ export function rowPlaces(rows: Iterable<HTMLElement>): Map<HTMLElement, DOMRect> {
117
+ const at = new Map<HTMLElement, DOMRect>();
118
+ for (const r of rows) at.set(r, r.getBoundingClientRect());
119
+ return at;
120
+ }
121
+
122
+ /**
123
+ * After the rows changed: those that stayed glide from where they were to where
124
+ * they are, the new ones fade in.
125
+ */
126
+ export function moveRows(rows: Iterable<HTMLElement>, was: Map<HTMLElement, DOMRect>): void {
127
+ const ms = duration();
128
+ for (const r of rows) {
129
+ const from = was.get(r);
130
+ if (from === undefined) {
131
+ r.animate([{ opacity: 0 }, { opacity: 1 }], { duration: ms, easing: EASE });
132
+ continue;
133
+ }
134
+ const to = r.getBoundingClientRect();
135
+ const dx = from.left - to.left;
136
+ const dy = from.top - to.top;
137
+ if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) continue;
138
+ r.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], { duration: ms, easing: EASE });
139
+ }
140
+ }
141
+
142
+ /**
143
+ * A row that went fades where it stood, out of the flow so the others close the gap:
144
+ * its cells keep their widths, as it no longer lies in its table.
145
+ */
146
+ export function leaveRow(r: HTMLElement, at: DOMRect): void {
147
+ const widths = Array.from(r.children, c => c.getBoundingClientRect().width);
148
+ Array.from(r.children as HTMLCollectionOf<HTMLElement>).forEach((c, i) => {
149
+ c.style.width = `${widths[i]}px`;
150
+ c.style.boxSizing = 'border-box';
151
+ });
152
+ r.classList.add('tb-leaving');
153
+ r.setAttribute('aria-hidden', 'true');
154
+ r.removeAttribute('tabindex');
155
+ Object.assign(r.style, { position: 'fixed', top: `${at.top}px`, left: `${at.left}px`, width: `${at.width}px`, height: `${at.height}px`, margin: '0' });
156
+ const a = r.animate([{ opacity: 1 }, { opacity: 0 }], { duration: duration() * 0.7, easing: EASE });
157
+ a.onfinish = () => r.remove();
158
+ a.oncancel = () => r.remove();
159
+ }
160
+
161
+ // --- shown and hidden --------------------------------------------------------------
162
+
163
+ /** The faces folding away now, so a face shown again stops folding. */
164
+ const folding = new WeakMap<HTMLElement, Animation>();
165
+
166
+ /** Whether a face is folding away now. */
167
+ export function isFolding(e: HTMLElement): boolean {
168
+ return folding.has(e);
169
+ }
170
+
171
+ /** A face shown again unfolds: from no height, if it lies among others one above another, and from clear. */
172
+ export function unfold(e: HTMLElement): void {
173
+ folding.get(e)?.cancel();
174
+ const h = e.getBoundingClientRect().height;
175
+ const stacked = stackedIn(e);
176
+ const frames: Keyframe[] = stacked && h > 0
177
+ ? [{ height: '0px', opacity: 0, overflow: 'hidden' }, { height: `${h}px`, opacity: 1, overflow: 'hidden' }]
178
+ : [{ opacity: 0 }, { opacity: 1 }];
179
+ e.animate(frames, { duration: duration(), easing: EASE });
180
+ }
181
+
182
+ /** A face hidden folds away, and then done hides it. */
183
+ export function fold(e: HTMLElement, done: () => void): void {
184
+ const h = e.getBoundingClientRect().height;
185
+ const stacked = stackedIn(e);
186
+ const frames: Keyframe[] = stacked && h > 0
187
+ ? [{ height: `${h}px`, opacity: 1, overflow: 'hidden' }, { height: '0px', opacity: 0, overflow: 'hidden', marginTop: '0px', marginBottom: '0px', paddingTop: '0px', paddingBottom: '0px' }]
188
+ : [{ opacity: 1 }, { opacity: 0 }];
189
+ const a = e.animate(frames, { duration: duration() * 0.8, easing: EASE });
190
+ folding.set(e, a);
191
+ a.onfinish = () => {
192
+ folding.delete(e);
193
+ done();
194
+ };
195
+ a.oncancel = () => folding.delete(e);
196
+ }
197
+
198
+ /** Whether a face lies among others one above another, so its height can open. */
199
+ function stackedIn(e: HTMLElement): boolean {
200
+ const p = e.parentElement;
201
+ if (p === null) return false;
202
+ const s = getComputedStyle(p);
203
+ return !s.display.includes('flex') || s.flexDirection.startsWith('column');
204
+ }