@wardic/dom 0.0.0-stage → 1.0.0-rc.10

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 (315) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/THIRD_PARTY_NOTICES.md +145 -0
  4. package/dist/Appear.d.ts +30 -0
  5. package/dist/Appear.d.ts.map +1 -0
  6. package/dist/Appear.js +31 -0
  7. package/dist/Appear.js.map +1 -0
  8. package/dist/Color.d.ts +14 -0
  9. package/dist/Color.d.ts.map +1 -0
  10. package/dist/Color.js +16 -0
  11. package/dist/Color.js.map +1 -0
  12. package/dist/DomAnnouncer.d.ts +13 -0
  13. package/dist/DomAnnouncer.d.ts.map +1 -0
  14. package/dist/DomAnnouncer.js +14 -0
  15. package/dist/DomAnnouncer.js.map +1 -0
  16. package/dist/DomBatch.d.ts +20 -0
  17. package/dist/DomBatch.d.ts.map +1 -0
  18. package/dist/DomBatch.js +23 -0
  19. package/dist/DomBatch.js.map +1 -0
  20. package/dist/DomClock.d.ts +11 -0
  21. package/dist/DomClock.d.ts.map +1 -0
  22. package/dist/DomClock.js +12 -0
  23. package/dist/DomClock.js.map +1 -0
  24. package/dist/DomDefaultTransition.d.ts +12 -0
  25. package/dist/DomDefaultTransition.d.ts.map +1 -0
  26. package/dist/DomDefaultTransition.js +13 -0
  27. package/dist/DomDefaultTransition.js.map +1 -0
  28. package/dist/DomInput.d.ts +14 -0
  29. package/dist/DomInput.d.ts.map +1 -0
  30. package/dist/DomInput.js +17 -0
  31. package/dist/DomInput.js.map +1 -0
  32. package/dist/DomInterpolators.d.ts +13 -0
  33. package/dist/DomInterpolators.d.ts.map +1 -0
  34. package/dist/DomInterpolators.js +14 -0
  35. package/dist/DomInterpolators.js.map +1 -0
  36. package/dist/DomKeyRules.d.ts +13 -0
  37. package/dist/DomKeyRules.d.ts.map +1 -0
  38. package/dist/DomKeyRules.js +14 -0
  39. package/dist/DomKeyRules.js.map +1 -0
  40. package/dist/DomPositionalKeys.d.ts +13 -0
  41. package/dist/DomPositionalKeys.d.ts.map +1 -0
  42. package/dist/DomPositionalKeys.js +14 -0
  43. package/dist/DomPositionalKeys.js.map +1 -0
  44. package/dist/DomProbe.d.ts +13 -0
  45. package/dist/DomProbe.d.ts.map +1 -0
  46. package/dist/DomProbe.js +14 -0
  47. package/dist/DomProbe.js.map +1 -0
  48. package/dist/DomProjectionSystem.d.ts +28 -0
  49. package/dist/DomProjectionSystem.d.ts.map +1 -0
  50. package/dist/DomProjectionSystem.js +41 -0
  51. package/dist/DomProjectionSystem.js.map +1 -0
  52. package/dist/DomRenderer.d.ts +13 -0
  53. package/dist/DomRenderer.d.ts.map +1 -0
  54. package/dist/DomRenderer.js +15 -0
  55. package/dist/DomRenderer.js.map +1 -0
  56. package/dist/DomScrollSource.d.ts +14 -0
  57. package/dist/DomScrollSource.d.ts.map +1 -0
  58. package/dist/DomScrollSource.js +15 -0
  59. package/dist/DomScrollSource.js.map +1 -0
  60. package/dist/FlushGate.d.ts +48 -0
  61. package/dist/FlushGate.d.ts.map +1 -0
  62. package/dist/FlushGate.js +62 -0
  63. package/dist/FlushGate.js.map +1 -0
  64. package/dist/KeyboardPress.d.ts +16 -0
  65. package/dist/KeyboardPress.d.ts.map +1 -0
  66. package/dist/KeyboardPress.js +17 -0
  67. package/dist/KeyboardPress.js.map +1 -0
  68. package/dist/MeasuredPair.d.ts +14 -0
  69. package/dist/MeasuredPair.d.ts.map +1 -0
  70. package/dist/MeasuredPair.js +16 -0
  71. package/dist/MeasuredPair.js.map +1 -0
  72. package/dist/OwnValues.d.ts +14 -0
  73. package/dist/OwnValues.d.ts.map +1 -0
  74. package/dist/OwnValues.js +15 -0
  75. package/dist/OwnValues.js.map +1 -0
  76. package/dist/ProjectionSystem.d.ts +34 -0
  77. package/dist/ProjectionSystem.d.ts.map +1 -0
  78. package/dist/ProjectionSystem.js +29 -0
  79. package/dist/ProjectionSystem.js.map +1 -0
  80. package/dist/ReorderController.d.ts +61 -0
  81. package/dist/ReorderController.d.ts.map +1 -0
  82. package/dist/ReorderController.js +78 -0
  83. package/dist/ReorderController.js.map +1 -0
  84. package/dist/Report.d.ts +12 -0
  85. package/dist/Report.d.ts.map +1 -0
  86. package/dist/Report.js +13 -0
  87. package/dist/Report.js.map +1 -0
  88. package/dist/ScrollOffset.d.ts +34 -0
  89. package/dist/ScrollOffset.d.ts.map +1 -0
  90. package/dist/ScrollOffset.js +42 -0
  91. package/dist/ScrollOffset.js.map +1 -0
  92. package/dist/Style.d.ts +15 -0
  93. package/dist/Style.d.ts.map +1 -0
  94. package/dist/Style.js +17 -0
  95. package/dist/Style.js.map +1 -0
  96. package/dist/Svg.d.ts +13 -0
  97. package/dist/Svg.d.ts.map +1 -0
  98. package/dist/Svg.js +14 -0
  99. package/dist/Svg.js.map +1 -0
  100. package/dist/Variables.d.ts +13 -0
  101. package/dist/Variables.d.ts.map +1 -0
  102. package/dist/Variables.js +14 -0
  103. package/dist/Variables.js.map +1 -0
  104. package/dist/index.d.ts +83 -0
  105. package/dist/index.d.ts.map +1 -0
  106. package/dist/index.js +71 -0
  107. package/dist/index.js.map +1 -0
  108. package/dist/internal/announcer.d.ts +50 -0
  109. package/dist/internal/announcer.d.ts.map +1 -0
  110. package/dist/internal/announcer.js +115 -0
  111. package/dist/internal/announcer.js.map +1 -0
  112. package/dist/internal/appear-slot.d.ts +23 -0
  113. package/dist/internal/appear-slot.d.ts.map +1 -0
  114. package/dist/internal/appear-slot.js +29 -0
  115. package/dist/internal/appear-slot.js.map +1 -0
  116. package/dist/internal/appear.d.ts +237 -0
  117. package/dist/internal/appear.d.ts.map +1 -0
  118. package/dist/internal/appear.js +740 -0
  119. package/dist/internal/appear.js.map +1 -0
  120. package/dist/internal/auto-scroll.d.ts +24 -0
  121. package/dist/internal/auto-scroll.d.ts.map +1 -0
  122. package/dist/internal/auto-scroll.js +124 -0
  123. package/dist/internal/auto-scroll.js.map +1 -0
  124. package/dist/internal/batch-writer.d.ts +16 -0
  125. package/dist/internal/batch-writer.d.ts.map +1 -0
  126. package/dist/internal/batch-writer.js +77 -0
  127. package/dist/internal/batch-writer.js.map +1 -0
  128. package/dist/internal/clock.d.ts +19 -0
  129. package/dist/internal/clock.d.ts.map +1 -0
  130. package/dist/internal/clock.js +39 -0
  131. package/dist/internal/clock.js.map +1 -0
  132. package/dist/internal/colors.d.ts +45 -0
  133. package/dist/internal/colors.d.ts.map +1 -0
  134. package/dist/internal/colors.js +193 -0
  135. package/dist/internal/colors.js.map +1 -0
  136. package/dist/internal/complex.d.ts +24 -0
  137. package/dist/internal/complex.d.ts.map +1 -0
  138. package/dist/internal/complex.js +28 -0
  139. package/dist/internal/complex.js.map +1 -0
  140. package/dist/internal/content-watch.d.ts +20 -0
  141. package/dist/internal/content-watch.d.ts.map +1 -0
  142. package/dist/internal/content-watch.js +76 -0
  143. package/dist/internal/content-watch.js.map +1 -0
  144. package/dist/internal/default-transition.d.ts +25 -0
  145. package/dist/internal/default-transition.d.ts.map +1 -0
  146. package/dist/internal/default-transition.js +41 -0
  147. package/dist/internal/default-transition.js.map +1 -0
  148. package/dist/internal/drag-defaults.d.ts +18 -0
  149. package/dist/internal/drag-defaults.d.ts.map +1 -0
  150. package/dist/internal/drag-defaults.js +38 -0
  151. package/dist/internal/drag-defaults.js.map +1 -0
  152. package/dist/internal/gate.d.ts +188 -0
  153. package/dist/internal/gate.d.ts.map +1 -0
  154. package/dist/internal/gate.js +458 -0
  155. package/dist/internal/gate.js.map +1 -0
  156. package/dist/internal/input.d.ts +35 -0
  157. package/dist/internal/input.d.ts.map +1 -0
  158. package/dist/internal/input.js +658 -0
  159. package/dist/internal/input.js.map +1 -0
  160. package/dist/internal/interpolators.d.ts +19 -0
  161. package/dist/internal/interpolators.d.ts.map +1 -0
  162. package/dist/internal/interpolators.js +30 -0
  163. package/dist/internal/interpolators.js.map +1 -0
  164. package/dist/internal/key-rules.d.ts +11 -0
  165. package/dist/internal/key-rules.d.ts.map +1 -0
  166. package/dist/internal/key-rules.js +244 -0
  167. package/dist/internal/key-rules.js.map +1 -0
  168. package/dist/internal/keyboard-press.d.ts +7 -0
  169. package/dist/internal/keyboard-press.d.ts.map +1 -0
  170. package/dist/internal/keyboard-press.js +45 -0
  171. package/dist/internal/keyboard-press.js.map +1 -0
  172. package/dist/internal/measure.d.ts +157 -0
  173. package/dist/internal/measure.d.ts.map +1 -0
  174. package/dist/internal/measure.js +296 -0
  175. package/dist/internal/measure.js.map +1 -0
  176. package/dist/internal/measured-pairs.d.ts +38 -0
  177. package/dist/internal/measured-pairs.d.ts.map +1 -0
  178. package/dist/internal/measured-pairs.js +251 -0
  179. package/dist/internal/measured-pairs.js.map +1 -0
  180. package/dist/internal/own-values.d.ts +35 -0
  181. package/dist/internal/own-values.d.ts.map +1 -0
  182. package/dist/internal/own-values.js +117 -0
  183. package/dist/internal/own-values.js.map +1 -0
  184. package/dist/internal/pass-ends.d.ts +21 -0
  185. package/dist/internal/pass-ends.d.ts.map +1 -0
  186. package/dist/internal/pass-ends.js +14 -0
  187. package/dist/internal/pass-ends.js.map +1 -0
  188. package/dist/internal/positional-keys.d.ts +16 -0
  189. package/dist/internal/positional-keys.d.ts.map +1 -0
  190. package/dist/internal/positional-keys.js +21 -0
  191. package/dist/internal/positional-keys.js.map +1 -0
  192. package/dist/internal/probe.d.ts +10 -0
  193. package/dist/internal/probe.d.ts.map +1 -0
  194. package/dist/internal/probe.js +116 -0
  195. package/dist/internal/probe.js.map +1 -0
  196. package/dist/internal/projection-defaults.d.ts +34 -0
  197. package/dist/internal/projection-defaults.d.ts.map +1 -0
  198. package/dist/internal/projection-defaults.js +21 -0
  199. package/dist/internal/projection-defaults.js.map +1 -0
  200. package/dist/internal/projection.d.ts +537 -0
  201. package/dist/internal/projection.d.ts.map +1 -0
  202. package/dist/internal/projection.js +5228 -0
  203. package/dist/internal/projection.js.map +1 -0
  204. package/dist/internal/renderer.d.ts +104 -0
  205. package/dist/internal/renderer.d.ts.map +1 -0
  206. package/dist/internal/renderer.js +618 -0
  207. package/dist/internal/renderer.js.map +1 -0
  208. package/dist/internal/reorder.d.ts +174 -0
  209. package/dist/internal/reorder.d.ts.map +1 -0
  210. package/dist/internal/reorder.js +466 -0
  211. package/dist/internal/reorder.js.map +1 -0
  212. package/dist/internal/report.d.ts +30 -0
  213. package/dist/internal/report.d.ts.map +1 -0
  214. package/dist/internal/report.js +60 -0
  215. package/dist/internal/report.js.map +1 -0
  216. package/dist/internal/require-global.d.ts +11 -0
  217. package/dist/internal/require-global.d.ts.map +1 -0
  218. package/dist/internal/require-global.js +31 -0
  219. package/dist/internal/require-global.js.map +1 -0
  220. package/dist/internal/reveal.d.ts +20 -0
  221. package/dist/internal/reveal.d.ts.map +1 -0
  222. package/dist/internal/reveal.js +71 -0
  223. package/dist/internal/reveal.js.map +1 -0
  224. package/dist/internal/runner.d.ts +21 -0
  225. package/dist/internal/runner.d.ts.map +1 -0
  226. package/dist/internal/runner.js +48 -0
  227. package/dist/internal/runner.js.map +1 -0
  228. package/dist/internal/scale-correction.d.ts +80 -0
  229. package/dist/internal/scale-correction.d.ts.map +1 -0
  230. package/dist/internal/scale-correction.js +227 -0
  231. package/dist/internal/scale-correction.js.map +1 -0
  232. package/dist/internal/scroll.d.ts +37 -0
  233. package/dist/internal/scroll.d.ts.map +1 -0
  234. package/dist/internal/scroll.js +279 -0
  235. package/dist/internal/scroll.js.map +1 -0
  236. package/dist/internal/scrollers.d.ts +35 -0
  237. package/dist/internal/scrollers.d.ts.map +1 -0
  238. package/dist/internal/scrollers.js +38 -0
  239. package/dist/internal/scrollers.js.map +1 -0
  240. package/dist/internal/starting-style.d.ts +141 -0
  241. package/dist/internal/starting-style.d.ts.map +1 -0
  242. package/dist/internal/starting-style.js +300 -0
  243. package/dist/internal/starting-style.js.map +1 -0
  244. package/dist/internal/svg.d.ts +60 -0
  245. package/dist/internal/svg.d.ts.map +1 -0
  246. package/dist/internal/svg.js +257 -0
  247. package/dist/internal/svg.js.map +1 -0
  248. package/dist/internal/variables.d.ts +45 -0
  249. package/dist/internal/variables.d.ts.map +1 -0
  250. package/dist/internal/variables.js +92 -0
  251. package/dist/internal/variables.js.map +1 -0
  252. package/package.json +65 -4
  253. package/src/Appear.ts +54 -0
  254. package/src/Color.ts +24 -0
  255. package/src/DomAnnouncer.ts +22 -0
  256. package/src/DomBatch.ts +22 -0
  257. package/src/DomClock.ts +13 -0
  258. package/src/DomDefaultTransition.ts +16 -0
  259. package/src/DomInput.ts +23 -0
  260. package/src/DomInterpolators.ts +16 -0
  261. package/src/DomKeyRules.ts +17 -0
  262. package/src/DomPositionalKeys.ts +16 -0
  263. package/src/DomProbe.ts +15 -0
  264. package/src/DomProjectionSystem.ts +44 -0
  265. package/src/DomRenderer.ts +26 -0
  266. package/src/DomScrollSource.ts +14 -0
  267. package/src/FlushGate.ts +81 -0
  268. package/src/KeyboardPress.ts +16 -0
  269. package/src/MeasuredPair.ts +15 -0
  270. package/src/OwnValues.ts +19 -0
  271. package/src/ProjectionSystem.ts +51 -0
  272. package/src/ReorderController.ts +122 -0
  273. package/src/Report.ts +17 -0
  274. package/src/ScrollOffset.ts +54 -0
  275. package/src/Style.ts +37 -0
  276. package/src/Svg.ts +21 -0
  277. package/src/Variables.ts +17 -0
  278. package/src/index.ts +120 -0
  279. package/src/internal/announcer.ts +132 -0
  280. package/src/internal/appear-slot.ts +32 -0
  281. package/src/internal/appear.ts +1134 -0
  282. package/src/internal/auto-scroll.ts +176 -0
  283. package/src/internal/batch-writer.ts +95 -0
  284. package/src/internal/clock.ts +45 -0
  285. package/src/internal/colors.ts +258 -0
  286. package/src/internal/complex.ts +29 -0
  287. package/src/internal/content-watch.ts +84 -0
  288. package/src/internal/culori.d.ts +58 -0
  289. package/src/internal/default-transition.ts +50 -0
  290. package/src/internal/drag-defaults.ts +54 -0
  291. package/src/internal/gate.ts +598 -0
  292. package/src/internal/input.ts +763 -0
  293. package/src/internal/interpolators.ts +33 -0
  294. package/src/internal/key-rules.ts +357 -0
  295. package/src/internal/keyboard-press.ts +45 -0
  296. package/src/internal/measure.ts +373 -0
  297. package/src/internal/measured-pairs.ts +297 -0
  298. package/src/internal/own-values.ts +166 -0
  299. package/src/internal/pass-ends.ts +23 -0
  300. package/src/internal/positional-keys.ts +24 -0
  301. package/src/internal/probe.ts +175 -0
  302. package/src/internal/projection-defaults.ts +45 -0
  303. package/src/internal/projection.ts +6233 -0
  304. package/src/internal/renderer.ts +648 -0
  305. package/src/internal/reorder.ts +650 -0
  306. package/src/internal/report.ts +69 -0
  307. package/src/internal/require-global.ts +46 -0
  308. package/src/internal/reveal.ts +75 -0
  309. package/src/internal/runner.ts +64 -0
  310. package/src/internal/scale-correction.ts +310 -0
  311. package/src/internal/scroll.ts +358 -0
  312. package/src/internal/scrollers.ts +51 -0
  313. package/src/internal/starting-style.ts +396 -0
  314. package/src/internal/svg.ts +300 -0
  315. package/src/internal/variables.ts +145 -0
@@ -0,0 +1,1134 @@
1
+ /**
2
+ * Appear animations (#48, ADR-0044): a server-rendered mount animation played in CSS from first
3
+ * paint, which the client takes over at mount (the **Handoff**). The DOM's half, framework-free:
4
+ *
5
+ * - **The sampler** steps a binding's mount animation through core's machines, as a 60 Hz client
6
+ * would (`Machine.CATCH_UP_DT`), projects each Frame with the DOM's `project`, and writes it as one
7
+ * `@keyframes` rule, thinned to the stops a straight line can't stand in for, within a tolerance
8
+ * per key below what a screen shows (decision 9). One rule a spec, cached across requests by it.
9
+ * - **A sheet** collects one render's rules. An element's inline style names only a custom
10
+ * property, `animation: var(--wardic-aN)`, which the sheet defines in `:root` once the render
11
+ * knows its timing (decision 5); undefined, it leaves the element at its Starting style.
12
+ * - **The Handoff's reads:** the element's `wardic-…` animation and how far it has got. Its removal,
13
+ * written in the same task as the engine's first frame (decision 6), is `appear-slot.ts`'s, with
14
+ * `pending`: what a page's code asks before any Handoff, kept out of this module.
15
+ *
16
+ * @module
17
+ */
18
+ import * as Batch from "@wardic/core/Batch"
19
+ import * as BaseValue from "@wardic/core/BaseValue"
20
+ import type * as Frame from "@wardic/core/Frame"
21
+ import * as Machine from "@wardic/core/Machine"
22
+ import * as Projection from "@wardic/core/Projection"
23
+ import type * as Values from "@wardic/core/Values"
24
+ import * as Arr from "effect/Array"
25
+ import * as Bool from "effect/Boolean"
26
+ import { identity, type LazyArg } from "effect/Function"
27
+ import * as Match from "effect/Match"
28
+ import * as Option from "effect/Option"
29
+ import * as Order from "effect/Order"
30
+ import * as Predicate from "effect/Predicate"
31
+ import * as Rec from "effect/Record"
32
+ import * as Result from "effect/Result"
33
+ import * as UndefinedOr from "effect/UndefinedOr"
34
+ import { spacesRegistered } from "./colors.ts"
35
+ import { drawnUnitOf, project, TEMPLATE_KEY, TRANSFORM_FUNCS, type TransformTemplate, unitOf } from "./renderer.ts"
36
+ import { PREFIX } from "./appear-slot.ts"
37
+ import { dashCase, isPathKey, isSvgInnerTag, splitPatchForTag, svgAttrNameOf } from "./svg.ts"
38
+
39
+ /** An element's mount animation, as its binding describes it. */
40
+ export interface Spec {
41
+ /**
42
+ * What built the animation, as one string the binding writes the same on the server and the
43
+ * client: its starting values, its targets, its transition, whether motion is reduced. The rule's
44
+ * name is its hash, so a client tells a Handoff it can continue from one it can't (decision 6).
45
+ */
46
+ readonly key: string
47
+ /** The element's tag, so an SVG element's keys go to its attributes; `undefined` for an HTML element. */
48
+ // ADR-0014.
49
+ readonly tag: string | undefined
50
+ /**
51
+ * The animation's values from its start (for an `infinite` one, one cycle of it), built only when
52
+ * the rule isn't cached: a server render calls it once per spec per process.
53
+ */
54
+ readonly machine: LazyArg<Machine.Machine<Frame.Frame<Values.Values>>>
55
+ /** Played over and over: an infinite repeat, `machine` one cycle of it. */
56
+ readonly infinite?: boolean | undefined
57
+ /** A layout node: drawn through its projection at rest, as the client draws it, its own move on top. */
58
+ // ADR-0009, #245; its own translate (#363).
59
+ readonly projected?: boolean | undefined
60
+ /**
61
+ * The element's transform template: each stop's transform drawn through it, as the client draws it. A
62
+ * function's text can't name a rule, so a templated spec's rule is named by its stops, and sampled for
63
+ * each element that has one, never cached.
64
+ */
65
+ // A **Transform template** (#443).
66
+ readonly template?: TransformTemplate | undefined
67
+ }
68
+
69
+ /** A spec's `@keyframes` rule. */
70
+ export interface Keyframes {
71
+ /** The rule's name: `wardic-` and the spec's hash. */
72
+ readonly name: string
73
+ /**
74
+ * Seconds the rule plays, a multiple of 1/60 s: to the first Frame from which every one is within
75
+ * tolerance of the settled one.
76
+ */
77
+ readonly duration: number
78
+ /** Seconds to the Frame the spec settles at, which a client waits for: at or past `duration`. */
79
+ // `when` (ADR-0007).
80
+ readonly settled: number
81
+ /** Whether it plays over and over. */
82
+ readonly infinite: boolean
83
+ /** The time of each stop kept, in seconds from the start. */
84
+ readonly times: ReadonlyArray<number>
85
+ /** The rule, `@keyframes <name>{…}`. */
86
+ readonly css: string
87
+ /**
88
+ * The SVG geometry properties its stops write (`cx`, `r`…), which some browsers don't draw from CSS: an
89
+ * element playing it is defined under `@supports` for each, so a browser without them keeps it at its
90
+ * starting style. Empty for most rules.
91
+ */
92
+ // #245.
93
+ readonly supports: ReadonlyArray<string>
94
+ }
95
+
96
+ /** Where an element's timing is decided: a spec, and the delay it starts after. */
97
+ export interface Play {
98
+ /** The element's mount animation. */
99
+ readonly spec: Spec
100
+ /** Seconds before it starts: its orchestration's, and any delay on the whole element. */
101
+ readonly delay: number
102
+ }
103
+
104
+ /** The longest mount animation sampled, in seconds; a longer one keeps its Starting style. */
105
+ export const MAX_SECONDS = 60
106
+
107
+ const MAX_STEPS = /*#__PURE__*/ Math.round(MAX_SECONDS / Machine.CATCH_UP_DT)
108
+
109
+ // --- The spec's name ---------------------------------------------------------------------------
110
+
111
+ /** cyrb53, a 53-bit string hash: plenty for a page's specs, and the same in every engine. */
112
+ const hash53 = (text: string): string => {
113
+ const [h1, h2] = Arr.reduce(Array.from(text), [0xdeadbeef, 0x41c6ce57] as const, ([a, b], char): readonly [number, number] => {
114
+ const code = char.codePointAt(0) as number
115
+ return [Math.imul(a ^ code, 2654435761), Math.imul(b ^ code, 1597334677)]
116
+ })
117
+ const a = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
118
+ const b = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
119
+ return (4294967296 * (2097151 & b) + (a >>> 0)).toString(36)
120
+ }
121
+
122
+ /** Each spec's name by its text, so a page's elements sharing a spec hash it once; the oldest dropped past `NAMES_SIZE`. */
123
+ // Module state (#460, Q7): a cache keyed by what it caches: a bounded set of names.
124
+ const names = /*#__PURE__*/ new Map<string, string>()
125
+
126
+ const NAMES_SIZE = 4096
127
+
128
+ /** The rule's name for a spec: its key, tag, repeat and projection, hashed. */
129
+ // Once a text: a server names each element's spec.
130
+ export const nameOf = (spec: Pick<Spec, "key" | "tag" | "infinite" | "projected">): string => {
131
+ const text = specTextOf(spec)
132
+ return Option.getOrElse(Option.fromUndefinedOr(names.get(text)), () => {
133
+ const name = `${PREFIX}${hash53(text)}`
134
+ if (names.size >= NAMES_SIZE) names.clear()
135
+ names.set(text, name)
136
+ return name
137
+ })
138
+ }
139
+
140
+ /** A spec's text, which its rule's name hashes: its tag, repeat, key and projection. */
141
+ const specTextOf = (spec: Pick<Spec, "key" | "tag" | "infinite" | "projected">): string =>
142
+ `${UndefinedOr.match(spec.tag, { onUndefined: () => "", onDefined: (tag: string) => tag })}|${spec.infinite === true}|${spec.key}${
143
+ Bool.match(spec.projected === true, { onTrue: () => "|projected", onFalse: () => "" })
144
+ }`
145
+
146
+ // --- Sampling ----------------------------------------------------------------------------------
147
+
148
+ /**
149
+ * The spec's Frames' values at 0, 1/60 s, 2/60 s… to the settled one: `startAt`'s catch-up steps,
150
+ * so the client's `startAt(k / 60)` draws the `k`th. Each copied, since a machine may rewrite its
151
+ * Frame in place (`springValues`, ADR-0030 decision 11). `None` past `MAX_SECONDS`.
152
+ */
153
+ const framesOf = (machine: Machine.Machine<Frame.Frame<Values.Values>>): Option.Option<ReadonlyArray<Values.Values>> => {
154
+ const step = machine.start()
155
+ // Copied before the next step, which may rewrite it.
156
+ const copy = (frame: Frame.Frame<Values.Values>): Sampled60 => ({ values: { ...frame.value }, done: frame.done })
157
+ return unfoldFrames(copy(step(0)), () => copy(step(Machine.CATCH_UP_DT)))
158
+ }
159
+
160
+ /** One 60 Hz sample: its values, and whether its series has settled there. */
161
+ interface Sampled60 {
162
+ readonly values: Values.Values
163
+ readonly done: boolean
164
+ }
165
+
166
+ /**
167
+ * A series' values from its first sample and each next one, 1/60 s on, to the one that settles: `None`
168
+ * past `MAX_SECONDS`. An element's machine's (`framesOf`) and a Batch's (#706).
169
+ */
170
+ const unfoldFrames = (first: Sampled60, next: () => Sampled60): Option.Option<ReadonlyArray<Values.Values>> => {
171
+ const rest = Arr.unfold({ frame: first, steps: 0 }, ({ frame, steps }) =>
172
+ Bool.match(Bool.or(frame.done, steps >= MAX_STEPS), {
173
+ onTrue: () => Option.none(),
174
+ onFalse: () => {
175
+ const sampled = next()
176
+ return Option.some([sampled, { frame: sampled, steps: steps + 1 }] as const)
177
+ },
178
+ }))
179
+ const frames = Arr.prepend(rest, first)
180
+ return Option.liftPredicate(
181
+ Arr.map(frames, (frame) => frame.values),
182
+ () => Arr.lastNonEmpty(frames).done,
183
+ )
184
+ }
185
+
186
+ /** One key's value split for comparing: its numbers, and the text between them. */
187
+ interface Split {
188
+ readonly skeleton: string
189
+ readonly numbers: ReadonlyArray<number>
190
+ /** The decimals each number was written with: a quantised token can't be judged finer than it. */
191
+ readonly decimals: ReadonlyArray<number>
192
+ /** Each number's unit, the letters after it. */
193
+ readonly units: ReadonlyArray<string>
194
+ }
195
+
196
+ const NUMBER_TOKEN = /(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)([a-z%]*)/gi
197
+
198
+ /** A value split into its numbers and the text around them; a number is one token with no text. */
199
+ const splitOf = (value: number | string): Split =>
200
+ Bool.match(Predicate.isNumber(value), {
201
+ onTrue: () => ({ skeleton: "#", numbers: [value as number], decimals: [Number.POSITIVE_INFINITY], units: [""] }),
202
+ onFalse: () => {
203
+ const text = String(value)
204
+ const tokens = Array.from(text.matchAll(NUMBER_TOKEN))
205
+ return {
206
+ skeleton: text.replace(NUMBER_TOKEN, "#$2"),
207
+ numbers: Arr.map(tokens, (match) => Number(match[1])),
208
+ decimals: Arr.map(tokens, (match) => decimalsOf(String(match[1]))),
209
+ units: Arr.map(tokens, (match) => String(match[2]).toLowerCase()),
210
+ }
211
+ },
212
+ })
213
+
214
+ /** How many decimals `token` is written with: none for `12`, two for `0.53`. */
215
+ const decimalsOf = (token: string): number =>
216
+ Option.match(Option.fromNullishOr(/\.(\d+)/.exec(token)), { onNone: () => 0, onSome: (match) => String(match[1]).length })
217
+
218
+ /**
219
+ * The tolerance per key and token (decision 9): what a straight line between two stops may miss a
220
+ * sample by. A bare number by its key's unit: 0.1 px, 0.1°, 0.001 of a scale, 0.002 for the rest
221
+ * (opacity). A token in a string by its own unit, `px` and `deg` alike; any other by its part of
222
+ * its range, 1/500 (a colour channel's half step), and never finer than the decimals it's written
223
+ * with.
224
+ */
225
+ const tolerancesOf = (key: string, svgInner: boolean, series: ReadonlyArray<Split>): ReadonlyArray<number> =>
226
+ Arr.map(Arr.headNonEmpty(series as Arr.NonEmptyReadonlyArray<Split>).numbers, (_, token) => {
227
+ const values = Arr.map(series, (split) => split.numbers[token] as number)
228
+ const span = Math.max(...values) - Math.min(...values)
229
+ const decimals = Math.min(6, Math.max(...Arr.map(series, (split) => split.decimals[token] as number)))
230
+ const unit = Arr.headNonEmpty(series as Arr.NonEmptyReadonlyArray<Split>).units[token] as string
231
+ const bare = Arr.headNonEmpty(series as Arr.NonEmptyReadonlyArray<Split>).skeleton === "#"
232
+ return Math.max(1e-9, toleranceFor(key, svgInner, bare, unit, span, 10 ** -decimals))
233
+ })
234
+
235
+ const toleranceFor = (key: string, svgInner: boolean, bare: boolean, unit: string, span: number, quantum: number): number =>
236
+ Bool.match(bare, {
237
+ onTrue: () => Bool.match(svgInner, { onTrue: () => svgTolerance(key), onFalse: () => bareTolerance(key) }),
238
+ onFalse: () =>
239
+ Bool.match(unit === "px" || unit === "deg", {
240
+ onTrue: () => Math.max(0.1, quantum),
241
+ onFalse: () => Math.max(span / 500, quantum),
242
+ }),
243
+ })
244
+
245
+ /** A bare number's tolerance, by the unit `project` draws `key` in. */
246
+ const bareTolerance = (key: string): number =>
247
+ Bool.match(drawnUnitOf(key) === "", {
248
+ onTrue: () => Bool.match(BaseValue.TRANSFORM_IDENTITY[key] === 1, { onTrue: () => 0.001, onFalse: () => 0.002 }),
249
+ onFalse: () => 0.1,
250
+ })
251
+
252
+ /** The opacities an svg-inner element draws as attributes, judged as opacity is. */
253
+ const SVG_OPACITIES: ReadonlySet<string> = /*#__PURE__*/ new Set(["opacity", "fillOpacity", "strokeOpacity", "stopOpacity", "floodOpacity"])
254
+
255
+ /**
256
+ * A bare number's tolerance on an svg-inner element (#245), by what its attribute means: a
257
+ * normalised dash (`pathLength`, `pathOffset`, `pathSpacing`: 0 to 1 of the path) 0.001, an
258
+ * opacity 0.002, any other attribute in user units, a CSS px, 0.1. A key drawn as style (the
259
+ * transform's) as on HTML.
260
+ */
261
+ const svgTolerance = (key: string): number =>
262
+ Bool.match(isPathKey(key), {
263
+ onTrue: () => 0.001,
264
+ onFalse: () =>
265
+ Option.match(svgAttrNameOf(key), {
266
+ onNone: () => bareTolerance(key),
267
+ onSome: () => Bool.match(SVG_OPACITIES.has(key), { onTrue: () => 0.002, onFalse: () => 0.1 }),
268
+ }),
269
+ })
270
+
271
+ /** A series of Frames split per key, with each key's tolerances: what the stops are judged on. */
272
+ const judged = (frames: ReadonlyArray<Values.Values>, svgInner: boolean) => {
273
+ const keys = Arr.flatMap(Arr.take(frames, 1), Rec.keys)
274
+ const splits = Arr.map(keys, (key) => Arr.map(frames, (frame) => splitOf(UndefinedOr.match(frame[key], { onUndefined: () => "", onDefined: (v: number | string) => v }))))
275
+ const tolerances = Arr.map(keys, (key, k) => tolerancesOf(key, svgInner, splits[k] as ReadonlyArray<Split>))
276
+ /** Whether stop `i` is within every key's tolerance of where a straight line from `a` to `b` puts it. */
277
+ const onLine = (i: number, a: number, b: number): boolean =>
278
+ Arr.every(splits, (series, k) => {
279
+ const from = series[a] as Split
280
+ const to = series[b] as Split
281
+ const at = series[i] as Split
282
+ return at.skeleton === from.skeleton && at.skeleton === to.skeleton &&
283
+ Arr.every(at.numbers, (value, token) => {
284
+ const line = (from.numbers[token] as number) + (((to.numbers[token] as number) - (from.numbers[token] as number)) * (i - a)) / Math.max(1, b - a)
285
+ return Math.abs(value - line) <= ((tolerances[k] as ReadonlyArray<number>)[token] as number)
286
+ })
287
+ })
288
+ /**
289
+ * Whether the Frame at `k` jumps from the one before: a key's text changes (a discrete value), or
290
+ * one of its numbers moves past its tolerance and four times its moves on either side (a loop's
291
+ * seam, a `steps()` easing, a snap). The engine draws one Frame, then the other; a line between
292
+ * them would draw values it never does.
293
+ */
294
+ const jumpAt = (k: number): boolean =>
295
+ Arr.some(splits, (series, j) => {
296
+ const before = series[k - 1] as Split
297
+ const at = series[k] as Split
298
+ return Bool.or(
299
+ at.skeleton !== before.skeleton,
300
+ Arr.some(at.numbers, (value, token) => {
301
+ const move = (i: number): number =>
302
+ Option.getOrElse(
303
+ Option.map(Option.all([Option.fromUndefinedOr(series[i]), Option.fromUndefinedOr(series[i - 1])]), ([a, b]) => Math.abs((a.numbers[token] as number) - (b.numbers[token] as number))),
304
+ () => 0,
305
+ )
306
+ const step = Math.abs(value - (before.numbers[token] as number))
307
+ return Bool.and(step > ((tolerances[j] as ReadonlyArray<number>)[token] as number), step > 4 * Math.max(move(k - 1), move(k + 1)))
308
+ }),
309
+ )
310
+ })
311
+ return { onLine, jumpAt }
312
+ }
313
+
314
+ /**
315
+ * The stops kept (decision 9), as indices into `frames`, and where the rule ends.
316
+ *
317
+ * - **It ends** at the first Frame from which every one is within tolerance of the settled Frame,
318
+ * drawn as the settled Frame: a tween stepped in 1/60 s settles a frame after it arrives, when
319
+ * its steps' sum crosses its duration.
320
+ * - **The stops kept** are the first, the end, and each one a straight line from the last kept can't
321
+ * reach past, within every key's tolerances.
322
+ * - **A jump** (`jumps`, kept stops): a Frame the one before it can't be drawn into, as `jumpAt`
323
+ * tells. The rule holds the Frame before it to halfway between them, then steps, so a display
324
+ * frame near either draws that Frame, not a value on a line through values the engine never draws.
325
+ */
326
+ export const thin = (
327
+ frames: ReadonlyArray<Values.Values>,
328
+ tag?: string | undefined,
329
+ ): { readonly kept: ReadonlyArray<number>; readonly end: number; readonly jumps: ReadonlyArray<number> } => {
330
+ const last = frames.length - 1
331
+ const svgInner = Predicate.isNotUndefined(tag) && isSvgInnerTag(tag)
332
+ const whole = judged(frames, svgInner)
333
+ const end = Option.match(Arr.findLastIndex(Arr.range(0, last), (i) => !whole.onLine(i, last, last)), {
334
+ onNone: () => 0,
335
+ onSome: (i) => Math.min(last, i + 1),
336
+ })
337
+ // The series drawn: the Frames up to the end, the end drawn as the settled Frame.
338
+ const { onLine, jumpAt } = judged(Arr.append(Arr.take(frames, end), frames[last] as Values.Values), svgInner)
339
+ /** Whether one straight line from stop `a` to stop `b` stands in for every stop between. */
340
+ const fits = (a: number, b: number): boolean => Arr.every(Arr.range(a + 1, b - 1), (i) => onLine(i, a, b))
341
+ /** The farthest stop a line from `a` can reach. */
342
+ const reach = (a: number): number =>
343
+ Option.getOrElse(Arr.findFirst(Arr.range(a + 1, end), (b) => b === end || !fits(a, b + 1)), () => end)
344
+ const kept = Arr.unfold(0, (a) => Bool.match(a >= end, { onTrue: () => Option.none(), onFalse: () => Option.some([reach(a), reach(a)] as const) }))
345
+ return { kept: [0, ...kept], end, jumps: Arr.filter(kept, jumpAt) }
346
+ }
347
+
348
+ /** A number written to at most four decimals, `-0` as `0`: finer than any tolerance, and short. */
349
+ const trimNumbers = (text: string): string =>
350
+ text.replace(/-?(?:\d+\.\d+|\.\d+)(?:e[-+]?\d+)?|-?\d+e[-+]?\d+/gi, (token) => String(Number(Number(token).toFixed(4)) + 0))
351
+
352
+ /** A number for a rule's text: at most four decimals, as every stop's. */
353
+ const numberText = (value: number): string => trimNumbers(String(value))
354
+
355
+ /** Text CSS can't hold inside a declaration, or that would end the `<style>` it sits in. */
356
+ const UNSAFE = /[<>{};]|\/\*|\\/
357
+
358
+ /**
359
+ * The SVG attributes a keyframe draws as their CSS property (#245, ADR-0044 *Amendment (#245)*):
360
+ * presentation attributes, which a stylesheet's or an animation's value overrides, so the attribute
361
+ * the engine writes at the Handoff takes over value for value. Unitless, as the attribute is.
362
+ */
363
+ const SVG_PRESENTATION: ReadonlySet<string> = /*#__PURE__*/ new Set([
364
+ "opacity",
365
+ "fill",
366
+ "stroke",
367
+ "stroke-width",
368
+ "fill-opacity",
369
+ "stroke-opacity",
370
+ "stroke-dasharray",
371
+ "stroke-dashoffset",
372
+ "stop-color",
373
+ "stop-opacity",
374
+ "flood-color",
375
+ "flood-opacity",
376
+ ])
377
+
378
+ /**
379
+ * SVG 2's geometry properties a keyframe draws, in px, behind `@supports` (`Keyframes.supports`):
380
+ * Chrome and Firefox draw them from CSS, Safari only in part. Not `width` and `height`:
381
+ * `@supports (width: 0px)` holds for HTML in every browser, so it can't tell whether one draws a
382
+ * `<rect>`'s from CSS.
383
+ */
384
+ const SVG_GEOMETRY: ReadonlySet<string> = /*#__PURE__*/ new Set(["cx", "cy", "r", "rx", "ry", "x", "y"])
385
+
386
+ /** The attribute the stroke dash writes beside it, `pathLength="1"`: the Starting style writes it too, and it never changes. */
387
+ const SVG_FIXED: ReadonlySet<string> = /*#__PURE__*/ new Set(["pathLength"])
388
+
389
+ const BARE_NUMBER = /^-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?$/i
390
+
391
+ /** An SVG attribute's declaration: a geometry property's bare number in px, what a user unit is. */
392
+ const attributeDeclaration = ([name, value]: readonly [string, string]): string =>
393
+ `${name}:${trimNumbers(Bool.match(Bool.and(SVG_GEOMETRY.has(name), BARE_NUMBER.test(value)), { onTrue: () => `${value}px`, onFalse: () => value }))}`
394
+
395
+ /** Why an attribute can't be a keyframe's: it isn't a CSS property (`d` in Safari, `points`, a filter primitive's). */
396
+ const drawnOnlyAsAttribute = (name: string): boolean => Bool.not(Bool.or(SVG_FIXED.has(name), Bool.or(SVG_PRESENTATION.has(name), SVG_GEOMETRY.has(name))))
397
+
398
+ /** One Frame's declarations and the geometry properties among them. */
399
+ interface Declarations {
400
+ readonly text: string
401
+ readonly supports: ReadonlyArray<string>
402
+ }
403
+
404
+ /**
405
+ * One Frame's declarations, or why it can't be one: a key SVG draws only as an attribute, or unsafe
406
+ * text. An svg-inner element's attributes are drawn as their CSS properties where they have one; a
407
+ * layout node through its projection at rest (#245).
408
+ */
409
+ const declarationsOf = (tag: string | undefined, values: Values.Values, projected: boolean, template: TransformTemplate | undefined): Result.Result<Declarations, string> => {
410
+ const { attrs, style } = splitPatchForTag(tag, project(drawnValuesOf(values, projected, template)))
411
+ const drawn = Arr.filter(Rec.toEntries(attrs), ([name]) => Bool.not(SVG_FIXED.has(name)))
412
+ const declarations = Arr.appendAll(
413
+ Arr.map(Rec.toEntries(style), ([key, value]) => `${dashCase(key)}:${trimNumbers(String(value))}`),
414
+ Arr.map(drawn, attributeDeclaration),
415
+ )
416
+ return Arr.match(Arr.filter(Rec.keys(attrs), drawnOnlyAsAttribute), {
417
+ onNonEmpty: (names) => Result.fail(`a key SVG draws only as an attribute (${names.join(", ")})`),
418
+ onEmpty: () =>
419
+ Option.match(Arr.findFirst(declarations, (declaration) => UNSAFE.test(declaration)), {
420
+ onSome: (declaration) => Result.fail(`a value CSS text can't hold (${declaration})`),
421
+ onNone: () =>
422
+ Result.succeed({ text: declarations.join(";"), supports: Arr.filter(Arr.map(drawn, ([name]) => name), (name) => SVG_GEOMETRY.has(name)) }),
423
+ }),
424
+ })
425
+ }
426
+
427
+ /** A Frame's values as the client draws them: a layout node's through its projection at rest (#245), a templated one's through its template (#443). */
428
+ const drawnValuesOf = (values: Values.Values, projected: boolean, template: TransformTemplate | undefined): Readonly<Record<string, unknown>> => {
429
+ const drawn = Bool.match(projected, { onTrue: () => ({ ...values, [Projection.KEY]: Projection.AT_REST }), onFalse: () => values })
430
+ return UndefinedOr.match(template, { onUndefined: () => drawn, onDefined: (t) => ({ ...drawn, [TEMPLATE_KEY]: t }) })
431
+ }
432
+
433
+ /** A stop's offset in the rule, a percentage to six decimals, so a jump's hold sits before its stop. */
434
+ const percentOf = (stop: number, last: number): string =>
435
+ `${String(Number(Bool.match(last === 0, { onTrue: () => 0, onFalse: () => (stop / last) * 100 }).toFixed(6)) + 0)}%`
436
+
437
+ /**
438
+ * Where a jump falls: halfway between its two Frames, so a display frame drawn near either one, a
439
+ * vsync's jitter early or late, draws that Frame. The step takes a thousandth of a frame.
440
+ */
441
+ const JUMP_AT = 0.5
442
+ const JUMP_TAKES = 0.001
443
+
444
+ /** A rule's stops, by their offsets in 60 Hz frames, and where it ends and settles. */
445
+ interface Stops {
446
+ readonly stops: ReadonlyArray<{ readonly offset: number; readonly frame: Values.Values }>
447
+ readonly kept: ReadonlyArray<number>
448
+ /** The frame it ends at: `thin`'s. */
449
+ readonly end: number
450
+ /** The frame it settles at: the series' last. */
451
+ readonly last: number
452
+ }
453
+
454
+ /**
455
+ * A sampled series' stops (decision 9): each one `thin` keeps, and at a jump, the Frame before it held to
456
+ * halfway, then its own; the end drawn as the settled Frame. An element's rule's and a Batch's.
457
+ */
458
+ const stopsOf = (frames: ReadonlyArray<Values.Values>, tag: string | undefined): Stops => {
459
+ const last = frames.length - 1
460
+ const { kept, end, jumps } = thin(frames, tag)
461
+ /** A kept stop's Frame: the end drawn as the settled Frame. */
462
+ const frameAt = (stop: number): Values.Values => frames[Bool.match(stop === end, { onTrue: () => last, onFalse: () => stop })] as Values.Values
463
+ const stops = Arr.flatMap(kept, (stop): ReadonlyArray<{ readonly offset: number; readonly frame: Values.Values }> =>
464
+ Bool.match(Arr.contains(jumps, stop), {
465
+ onTrue: () => [
466
+ { offset: stop - JUMP_AT, frame: frames[stop - 1] as Values.Values },
467
+ { offset: stop - JUMP_AT + JUMP_TAKES, frame: frameAt(stop) },
468
+ { offset: stop, frame: frameAt(stop) },
469
+ ],
470
+ onFalse: () => [{ offset: stop, frame: frameAt(stop) }],
471
+ }))
472
+ return { stops, kept, end, last }
473
+ }
474
+
475
+ /** A rule's timing from its stops: how long it plays, when it settles, each stop's time. */
476
+ const timingOf = (series: Stops): Pick<Keyframes, "duration" | "settled" | "times"> => ({
477
+ duration: series.end * Machine.CATCH_UP_DT,
478
+ settled: series.last * Machine.CATCH_UP_DT,
479
+ times: Arr.map(series.kept, (stop) => stop * Machine.CATCH_UP_DT),
480
+ })
481
+
482
+ /** A rule's body: each stop's offset and its declarations, one stop of `0%,100%` for a rule that settles at once. */
483
+ const bodyOf = ({ stops, end }: Stops, texts: ReadonlyArray<string>): string =>
484
+ Arr.map(Bool.match(end === 0, { onTrue: () => ["0%,100%"], onFalse: () => Arr.map(stops, ({ offset }) => percentOf(offset, end)) }), (offset, i) =>
485
+ `${offset}{${texts[i] as string}}`).join("")
486
+
487
+ /** A spec sampled into its rule, or why it can't be one. Not cached: {@link keyframes} is. */
488
+ const sample = (spec: Spec): Result.Result<Keyframes, string> =>
489
+ Option.match(framesOf(spec.machine()), {
490
+ onNone: () => Result.fail(`longer than ${MAX_SECONDS} s`),
491
+ onSome: (frames) => {
492
+ const projected = spec.projected === true
493
+ const series = stopsOf(frames, spec.tag)
494
+ return Result.map(
495
+ Result.all(Arr.map(series.stops, ({ frame }) => declarationsOf(spec.tag, frame, projected, spec.template))),
496
+ (declarations): Keyframes => {
497
+ const body = bodyOf(series, Arr.map(declarations, (d) => d.text))
498
+ const name = ruleNameOf(spec, body)
499
+ return {
500
+ name,
501
+ ...timingOf(series),
502
+ infinite: spec.infinite === true,
503
+ css: `@keyframes ${name}{${body}}`,
504
+ supports: supportsOf(Arr.flatMap(declarations, (d) => d.supports)),
505
+ }
506
+ },
507
+ )
508
+ },
509
+ })
510
+
511
+ /**
512
+ * A rule's name: its spec's ({@link nameOf}), or, for a templated spec (#443), its spec's text and
513
+ * its stops hashed, since a function can't name it: two templates that draw the same share one.
514
+ */
515
+ const ruleNameOf = (spec: Spec, body: string): string =>
516
+ UndefinedOr.match(spec.template, {
517
+ onUndefined: () => nameOf(spec),
518
+ onDefined: () => `${PREFIX}${hash53(`${specTextOf(spec)}|template|${body}`)}`,
519
+ })
520
+
521
+ /** Geometry properties once each, in order: a condition's text is the same for the same set. */
522
+ const supportsOf = (properties: ReadonlyArray<string>): ReadonlyArray<string> => Arr.sort(Arr.dedupe(properties), Order.String)
523
+
524
+ /** An `@supports` condition for geometry properties, `(cx:0px) and (r:0px)`; empty for none. */
525
+ const conditionOf = (properties: ReadonlyArray<string>): string => Arr.map(properties, (property) => `(${property}:0px)`).join(" and ")
526
+
527
+
528
+ /**
529
+ * The rules sampled so far, across requests, by name, each with whether every CSS colour space was
530
+ * registered when it was (#511); the oldest dropped past `CACHE_SIZE`.
531
+ */
532
+ // Module state (#460, Q7): a cache keyed by what it caches: each mount animation's sampled keyframes, by its text.
533
+ const cache = /*#__PURE__*/ new Map<string, Sampled>()
534
+
535
+ /** A spec's rule as sampled, and whether the colour spaces were registered then. */
536
+ interface Sampled {
537
+ readonly spaces: boolean
538
+ readonly rule: Result.Result<Keyframes, string>
539
+ }
540
+
541
+ const CACHE_SIZE = 512
542
+
543
+ /**
544
+ * A spec's rule, or why it has none, for a debug log. Sampled once a spec and cached across requests by
545
+ * its name, since a spec's rule changes only once the page registers every colour space
546
+ * (`Color.registerSpaces`): a wide-gamut colour blends as written before, in sRGB after. Its name stays,
547
+ * so a client matches it whatever it had registered. A templated spec's is sampled each time: its name
548
+ * comes from its stops.
549
+ */
550
+ // #511; templates #443.
551
+ export const keyframes = (spec: Spec): Result.Result<Keyframes, string> => {
552
+ if (Predicate.isNotUndefined(spec.template)) return sample(spec)
553
+ const name = nameOf(spec)
554
+ const spaces = spacesRegistered()
555
+ const kept = cache.get(name)
556
+ if (Predicate.isNotUndefined(kept) && kept.spaces === spaces) return kept.rule
557
+ const sampled = sample(spec)
558
+ remember(cache, name, { spaces, rule: sampled })
559
+ return sampled
560
+ }
561
+
562
+ /** `value` kept in `kept` by `name`, the oldest dropped past `CACHE_SIZE`: each rule cache's. */
563
+ const remember = <A>(kept: Map<string, A>, name: string, value: A): A => {
564
+ Option.map(Arr.head(Arr.take(Array.from(kept.keys()), Math.max(0, kept.size + 1 - CACHE_SIZE))), (oldest) => kept.delete(oldest))
565
+ kept.set(name, value)
566
+ return value
567
+ }
568
+
569
+ /**
570
+ * An element's `animation` value for a play of `rule`: its name, length, delay and repeat, filling
571
+ * forwards. Not backwards: through its delay the element shows its inline starting style, which is the
572
+ * rule's first stop for a rule that moves from it.
573
+ */
574
+ // And the start a reduced rule's snap holds until the delay ends (ADR-0029), where the first stop is
575
+ // already snapped.
576
+ export const animationOf = (rule: Keyframes, delay: number): string =>
577
+ `${rule.name} ${numberText(rule.duration)}s linear ${numberText(delay)}s ${
578
+ Bool.match(rule.infinite, { onTrue: () => "infinite", onFalse: () => "1" })
579
+ } forwards`
580
+
581
+ // --- A Batch's rule (#706) ---------------------------------------------------------------------
582
+
583
+ /**
584
+ * A Batch's entrance, as its binding describes it: its members on one set of transitions, each with its
585
+ * own start and target. One rule plays them all, each member's own values read from custom properties
586
+ * on its element (#706).
587
+ */
588
+ export interface BatchSpec {
589
+ /**
590
+ * Its transitions, key by key, and whether motion is reduced, as one string the binding writes the
591
+ * same on the server and the client: the rule's name starts with its hash, which a client checks
592
+ * ({@link matchesBatch}) before it takes a member over.
593
+ */
594
+ readonly key: string
595
+ /** The Batch's keys, in its order: the DOM's transform keys and `opacity`. */
596
+ readonly keys: ReadonlyArray<string>
597
+ /** How its keys move, as `Batch.make` takes it. */
598
+ readonly transition: Batch.Transitions
599
+ /** Each member's start, a number a key, in `keys`' order. */
600
+ readonly starts: ReadonlyArray<ReadonlyArray<number>>
601
+ /** Each member's target, as `starts`. */
602
+ readonly targets: ReadonlyArray<ReadonlyArray<number>>
603
+ }
604
+
605
+ /** A Batch's rule, and each member's own values for it. */
606
+ export interface BatchKeyframes extends Keyframes {
607
+ /**
608
+ * A member's own values as the custom properties the rule reads (`--wardic-x1: 120px`), by its index
609
+ * in the spec; `undefined` for a member none of whose keys moves, which plays nothing.
610
+ */
611
+ readonly memberStyle: (member: number) => Readonly<Record<string, string>> | undefined
612
+ }
613
+
614
+ /** The prefix a Batch rule's name starts with, from its spec's `key`: what a client checks. */
615
+ const batchPrefixOf = (key: string): string => `${PREFIX}b${hash53(key)}-`
616
+
617
+ /** The transform functions a Batch draws, in the renderer's order: its writer's, less a path's turn. */
618
+ const BATCH_FUNCS = /*#__PURE__*/ Arr.filter(TRANSFORM_FUNCS, (func) => func.key !== "pathRotation")
619
+
620
+ /**
621
+ * How a rule writes one key: as a value every member that moves shares, or as each one's own from custom
622
+ * properties, its start's (`--wardic-<key>0`) where starts differ, its target's (`--wardic-<key>1`) where
623
+ * targets do.
624
+ */
625
+ interface Column {
626
+ readonly key: string
627
+ readonly k: number
628
+ readonly unit: string
629
+ /** Whether any member's start and target differ: the key is sampled. */
630
+ readonly moves: boolean
631
+ /** Whether every member starts at one value, and ends at one. */
632
+ readonly sharedStart: boolean
633
+ readonly sharedTarget: boolean
634
+ /** That shared start and target: the first member's. */
635
+ readonly start: number
636
+ readonly target: number
637
+ /** What it's sampled over when its members' values differ: 0 to their longest move, a power of two up (the tolerance's tier). */
638
+ readonly span: number
639
+ }
640
+
641
+ /** Whether every member that moves starts at one value and ends at one: the rule writes the key as it is. */
642
+ const isShared = (column: Column): boolean => Bool.and(column.sharedStart, column.sharedTarget)
643
+
644
+ /** The custom property for a key's start (`0`) or target (`1`). */
645
+ const propertyOf = (key: string, end: 0 | 1): string => `--${PREFIX}${key}${end}`
646
+
647
+ /** A key's value with its unit: `120px`, `45deg`, `0.8`. */
648
+ const unitText = (column: Column, value: number): string => `${numberText(value)}${column.unit}`
649
+
650
+ /** A progress, 0 to 1, for a `calc()`: five decimals, a 0.03 px miss at a move of 4,096 px; `-0` as `0`, as `trimNumbers`. */
651
+ const progressText = (p: number): string => String(Number(p.toFixed(5)) + 0)
652
+
653
+ /** A stop's key whose members' values differ: `p` of the way from its start's text to its target's. */
654
+ interface OwnStop {
655
+ readonly column: Column
656
+ readonly p: number
657
+ readonly start: string
658
+ readonly target: string
659
+ }
660
+
661
+ /** What a stop writes for a key whose members' values differ: the shortest form for where it is. */
662
+ const ownText: (stop: OwnStop) => string = /*#__PURE__*/ Match.type<OwnStop>().pipe(
663
+ Match.when(({ column }) => Bool.not(column.moves), ({ target }) => target),
664
+ Match.when(({ p }) => p === 0, ({ start }) => start),
665
+ Match.when(({ p }) => p === 1, ({ target }) => target),
666
+ Match.when(({ column }) => Bool.and(column.sharedStart, column.start === 0), ({ p, target }) => `calc(${target} * ${progressText(p)})`),
667
+ Match.when(({ column }) => Bool.and(column.sharedTarget, column.target === 0), ({ p, start }) => `calc(${start} * ${progressText(1 - p)})`),
668
+ Match.orElse(({ p, start, target }) => `calc(${start} + (${target} - ${start}) * ${progressText(p)})`),
669
+ )
670
+
671
+ /** What a stop writes for a key, from its sampled value: a shared one as it is, an own one as its progress. */
672
+ const valueText = (column: Column, frame: Values.Values): string => {
673
+ const value = UndefinedOr.match(frame[column.key] as number | undefined, { onUndefined: () => column.target, onDefined: identity })
674
+ return Bool.match(isShared(column), {
675
+ onTrue: () => unitText(column, value),
676
+ onFalse: () =>
677
+ ownText({
678
+ column,
679
+ p: value / column.span,
680
+ start: Bool.match(column.sharedStart, { onTrue: () => unitText(column, column.start), onFalse: () => `var(${propertyOf(column.key, 0)})` }),
681
+ target: Bool.match(column.sharedTarget, { onTrue: () => unitText(column, column.target), onFalse: () => `var(${propertyOf(column.key, 1)})` }),
682
+ }),
683
+ })
684
+ }
685
+
686
+ /** The power of two at or above `move`: a span shared by Batches whose longest moves are near. */
687
+ const spanOf = (move: number): number => 2 ** Math.ceil(Math.log2(move))
688
+
689
+ /** A spec's members that move, some key's start not its target: the ones a rule plays, and all it reads. */
690
+ interface Movers {
691
+ readonly starts: ReadonlyArray<ReadonlyArray<number>>
692
+ readonly targets: ReadonlyArray<ReadonlyArray<number>>
693
+ }
694
+
695
+ /** Whether a member moves: some key's start isn't its target. */
696
+ const moves = (start: ReadonlyArray<number>, target: ReadonlyArray<number>): boolean => Arr.some(start, (s, k) => s !== target[k])
697
+
698
+ /** The members that move: one that plays nothing shares nothing with the rule. */
699
+ const moversOf = (spec: BatchSpec): Movers => {
700
+ const moving = Arr.filter(Arr.range(0, spec.starts.length - 1), (m) => moves(spec.starts[m] as ReadonlyArray<number>, spec.targets[m] as ReadonlyArray<number>))
701
+ return {
702
+ starts: Arr.map(moving, (m) => spec.starts[m] as ReadonlyArray<number>),
703
+ targets: Arr.map(moving, (m) => spec.targets[m] as ReadonlyArray<number>),
704
+ }
705
+ }
706
+
707
+ /** Each of the spec's keys as a rule writes it, from the members that move. */
708
+ const columnsOf = (keys: ReadonlyArray<string>, movers: Movers): ReadonlyArray<Column> =>
709
+ Arr.map(keys, (key, k): Column => {
710
+ const starts = Arr.map(movers.starts, (start) => start[k] as number)
711
+ const targets = Arr.map(movers.targets, (target) => target[k] as number)
712
+ const start = UndefinedOr.match(starts[0], { onUndefined: () => 0, onDefined: identity })
713
+ const target = UndefinedOr.match(targets[0], { onUndefined: () => 0, onDefined: identity })
714
+ const longest = Math.max(0, ...Arr.map(starts, (s, m) => Math.abs((targets[m] as number) - s)))
715
+ return {
716
+ key,
717
+ k,
718
+ unit: Bool.match(key === "opacity", { onTrue: () => "", onFalse: () => unitOf(key) }),
719
+ moves: longest > 0,
720
+ sharedStart: Arr.every(starts, (s) => s === start),
721
+ sharedTarget: Arr.every(targets, (t) => t === target),
722
+ start,
723
+ target,
724
+ span: Bool.match(longest > 0, { onTrue: () => spanOf(longest), onFalse: () => 1 }),
725
+ }
726
+ })
727
+
728
+ /** What a rule writes: its `transform`'s keys, each with its function, and its `opacity`. */
729
+ interface Written {
730
+ readonly transform: ReadonlyArray<Column & { readonly fn: string }>
731
+ readonly opacity: Option.Option<Column>
732
+ }
733
+
734
+ /**
735
+ * The columns a rule writes: `opacity` when it moves; and when any transform key moves, every transform
736
+ * key off its identity for some member, in the renderer's order, since the rule's `transform` replaces the
737
+ * element's whole.
738
+ */
739
+ const writtenOf = (movers: Movers, columns: ReadonlyArray<Column>): Written => {
740
+ const byKey = new Map(Arr.map(columns, (column) => [column.key, column] as const))
741
+ const transform = Arr.filterMap(BATCH_FUNCS, (func) =>
742
+ Option.match(Option.fromUndefinedOr(byKey.get(func.key)), {
743
+ onNone: () => Result.failVoid,
744
+ onSome: (column) => {
745
+ const off = (value: ReadonlyArray<number>): boolean => value[column.k] !== func.identity
746
+ return Bool.match(Bool.or(Arr.some(movers.starts, off), Arr.some(movers.targets, off)), {
747
+ onTrue: () => Result.succeed({ ...column, fn: func.fn }),
748
+ onFalse: () => Result.failVoid,
749
+ })
750
+ },
751
+ }))
752
+ return {
753
+ transform: Bool.match(Arr.some(transform, (column) => column.moves), { onTrue: () => transform, onFalse: () => [] }),
754
+ opacity: Option.filter(Option.fromUndefinedOr(byKey.get("opacity")), (column) => column.moves),
755
+ }
756
+ }
757
+
758
+ /** A writer that draws nothing: the sampler reads a Batch's values, not its writes. */
759
+ const UNDRAWN: Batch.Writer<null> = { writes: () => true, forKeys: () => () => undefined }
760
+
761
+ /**
762
+ * The Batch's own frames for its moving keys, at 0, 1/60 s, 2/60 s… to rest: one member from each key's
763
+ * shared start to its shared target, or from 0 to its span, stepped as a client's Batch steps it. `None`
764
+ * past `MAX_SECONDS`.
765
+ */
766
+ const batchFramesOf = (spec: BatchSpec, columns: ReadonlyArray<Column>): Option.Option<ReadonlyArray<Values.Values>> => {
767
+ const moving = Arr.filter(columns, (column) => column.moves)
768
+ const batch = Batch.make({ keys: spec.keys, writer: UNDRAWN, transition: spec.transition })
769
+ const slot = Batch.enter(batch, null, Rec.fromEntries(Arr.map(moving, (column) => [column.key, Bool.match(isShared(column), { onTrue: () => column.start, onFalse: () => 0 })] as const)))
770
+ const targets = Arr.map(columns, (column) =>
771
+ Bool.match(column.moves, {
772
+ onTrue: () => Bool.match(isShared(column), { onTrue: () => column.target, onFalse: () => column.span }),
773
+ onFalse: () => Number.NaN,
774
+ }))
775
+ Batch.retarget(batch, [slot], (_, k) => targets[k] as number)
776
+ // Each step's values, and whether the Batch rests after it; the first at 0 s, as `framesOf`'s.
777
+ const after = (done: boolean): Sampled60 => ({ values: Rec.fromEntries(Arr.map(moving, (column) => [column.key, Batch.get(batch, slot, column.key)] as const)), done })
778
+ return unfoldFrames(after(Batch.step(batch, 0)), () => after(Batch.step(batch, Machine.CATCH_UP_DT)))
779
+ }
780
+
781
+ /**
782
+ * A Batch's rule's name: its key's hash, then the hash of what it writes and how: each key's shared start
783
+ * and target, written into it, and an own key's span. Members' own values aren't in it, so Batches whose
784
+ * members differ but whose longest moves share a span share a rule.
785
+ */
786
+ const batchNameOf = (spec: BatchSpec, columns: ReadonlyArray<Column>): string => {
787
+ const shape = Arr.map(columns, (column) => {
788
+ const start = Bool.match(column.sharedStart, { onTrue: () => String(column.start), onFalse: () => "*" })
789
+ const target = Bool.match(column.sharedTarget, { onTrue: () => String(column.target), onFalse: () => "*" })
790
+ return `${column.key}:${column.moves}:${start}:${target}:${column.span}`
791
+ }).join("|")
792
+ return `${batchPrefixOf(spec.key)}${hash53(`${spec.keys.join(",")}|${shape}`)}`
793
+ }
794
+
795
+ /** The Batch rules sampled so far, across requests, by name (as {@link keyframes}' cache): each member's own values aren't in them. */
796
+ // Module state (#460, Q7): a cache keyed by what it caches.
797
+ const batchCache = /*#__PURE__*/ new Map<string, Result.Result<Keyframes, string>>()
798
+
799
+ /** A spec's first key with a start or target that isn't a finite number: a rule can't write it. */
800
+ const unfiniteKeyOf = (spec: BatchSpec): Option.Option<string> =>
801
+ Arr.findFirst(spec.keys, (_, k) => Arr.some(Arr.appendAll(spec.starts, spec.targets), (values) => Bool.not(Number.isFinite(values[k] as number))))
802
+
803
+ /**
804
+ * A Batch's rule for its members' entrance, or why it has none: one `@keyframes` for every member, each
805
+ * key's stops sampled from the Batch's own spring or tween at 60 Hz and thinned within its tolerance at
806
+ * its longest move. A key whose start and target every member that moves shares is written as it is;
807
+ * one whose values differ, as each member's custom properties and its progress between them.
808
+ */
809
+ // #706, Q2 A. Sampled once a shape a process, as an element's spec is.
810
+ export const batchKeyframes = (spec: BatchSpec): Result.Result<BatchKeyframes, string> => {
811
+ const unfinite = unfiniteKeyOf(spec)
812
+ if (Option.isSome(unfinite)) return Result.fail(`a start or target that isn't a finite number (${unfinite.value})`)
813
+ const movers = moversOf(spec)
814
+ const columns = columnsOf(spec.keys, movers)
815
+ const written = writtenOf(movers, columns)
816
+ if (Bool.and(Arr.isReadonlyArrayEmpty(written.transform), Option.isNone(written.opacity))) return Result.fail("no key moves")
817
+ const name = batchNameOf(spec, columns)
818
+ const rule = Option.getOrElse(Option.fromUndefinedOr(batchCache.get(name)), () => remember(batchCache, name, sampleBatch(spec, columns, written, name)))
819
+ const own = Arr.filter(Arr.appendAll(written.transform, Option.toArray(written.opacity)), (column) => Bool.not(isShared(column)))
820
+ return Result.map(rule, (keyframes) => ({
821
+ ...keyframes,
822
+ memberStyle: (member) => {
823
+ const start = spec.starts[member] as ReadonlyArray<number>
824
+ const target = spec.targets[member] as ReadonlyArray<number>
825
+ return Bool.match(moves(start, target), {
826
+ onFalse: () => undefined,
827
+ onTrue: () =>
828
+ Rec.fromEntries(Arr.flatMap(own, (column): ReadonlyArray<readonly [string, string]> => [
829
+ ...Bool.match(Bool.and(column.moves, Bool.not(column.sharedStart)), { onTrue: () => [[propertyOf(column.key, 0), unitText(column, start[column.k] as number)] as const], onFalse: () => [] }),
830
+ ...Bool.match(column.sharedTarget, { onTrue: () => [], onFalse: () => [[propertyOf(column.key, 1), unitText(column, target[column.k] as number)] as const] }),
831
+ ])),
832
+ })
833
+ },
834
+ }))
835
+ }
836
+
837
+ /** A Batch's rule sampled, or why it can't be. Not cached: {@link batchKeyframes} is. */
838
+ const sampleBatch = (spec: BatchSpec, columns: ReadonlyArray<Column>, written: Written, name: string): Result.Result<Keyframes, string> =>
839
+ Option.match(batchFramesOf(spec, columns), {
840
+ onNone: () => Result.fail(`longer than ${MAX_SECONDS} s`),
841
+ onSome: (frames) => {
842
+ const series = stopsOf(frames, undefined)
843
+ const texts = Arr.map(series.stops, ({ frame }) => {
844
+ const transform = Arr.map(written.transform, (column) => `${column.fn}(${valueText(column, frame)})`).join(" ")
845
+ const declarations = Arr.appendAll(
846
+ Bool.match(transform === "", { onTrue: () => [], onFalse: () => [`transform:${transform}`] }),
847
+ Option.toArray(Option.map(written.opacity, (column) => `opacity:${valueText(column, frame)}`)),
848
+ )
849
+ return declarations.join(";")
850
+ })
851
+ const body = bodyOf(series, texts)
852
+ return Result.succeed({ name, ...timingOf(series), infinite: false, css: `@keyframes ${name}{${body}}`, supports: [] })
853
+ },
854
+ })
855
+
856
+ /**
857
+ * A Batch slot's `animation`, less a delay: each member's inline `animation` names the slot and gives its
858
+ * own after it, `var(--wardic-aN) 0.035s`, the shorthand's second time. A delay here too would be a third,
859
+ * and the member's `animation` invalid: it would keep its start.
860
+ */
861
+ // #706, Q2 and Q6: one `:root` line a rule group, which reduced motion's media query switches; a member's stagger its own.
862
+ const slotAnimationOf = (rule: Keyframes): string => `${rule.name} ${numberText(rule.duration)}s linear 1 forwards`
863
+
864
+ // --- A render's sheet --------------------------------------------------------------------------
865
+
866
+ /** One element's place in a sheet. */
867
+ export interface Slot {
868
+ /** The element's inline `animation`: `var(--wardic-aN)`, which the sheet defines once `define` is called. */
869
+ readonly animation: string
870
+ /**
871
+ * The element's timing: `play`, and under `prefers-reduced-motion: reduce` `reduced` when given
872
+ * (a provider's `"user"`). Undefined until called, and left so when either spec has no rule: the
873
+ * element keeps its Starting style. The reason comes back for the debug log.
874
+ *
875
+ * Defined under `@supports` for the geometry properties its rules write and `supports`: a binding
876
+ * passes the ones every element it orchestrates with writes, so a browser without them keeps the whole
877
+ * group at its starting style, not half of it.
878
+ */
879
+ // #245.
880
+ readonly define: (play: Play, reduced?: Play | undefined, supports?: ReadonlyArray<string>) => Result.Result<void, string>
881
+ }
882
+
883
+ /** A Batch's members' place in a sheet: one slot for every member on one rule (#706). */
884
+ export interface BatchSlot {
885
+ /**
886
+ * A member's inline style, by its index in the rule's spec: its own values, and its `animation`, the slot
887
+ * and, when it waits (its stagger), its delay after it. `undefined` for a member that doesn't move.
888
+ */
889
+ readonly styleOf: (member: number, delay: number) => Readonly<Record<string, string>> | undefined
890
+ }
891
+
892
+ /** One render's Appear rules: a slot per element, and the `<style>` text for the head and each late chunk. */
893
+ export interface Sheet {
894
+ /** A slot for the next element. */
895
+ readonly slot: () => Slot
896
+ /**
897
+ * A slot for a Batch's members on `play`'s rule, and under `prefers-reduced-motion: reduce` `reduced`'s
898
+ * when given (a provider's `"user"`): both rules, and the slot's `:root` lines naming each with no delay,
899
+ * since each member gives its own.
900
+ */
901
+ // #706, Q2 and Q6: one `:root` line a rule group, not a member.
902
+ readonly batch: (play: BatchKeyframes, reduced?: BatchKeyframes | undefined) => BatchSlot
903
+ /**
904
+ * The CSS since the last call: each rule this render hasn't written yet, and the custom property of
905
+ * each slot defined since, the reduced ones under the media query. Called once for the head, and again
906
+ * for each chunk a stream sends after its shell, with only what that chunk adds.
907
+ */
908
+ // #245.
909
+ readonly css: () => string
910
+ }
911
+
912
+ /** Each `@supports` condition's `:root` declarations, the unconditional ones under `""`. */
913
+ type Blocks = Map<string, Array<string>>
914
+
915
+ /** A block's declarations added under its condition. */
916
+ const addTo = (blocks: Blocks, condition: string, line: string): void => {
917
+ Option.match(Option.fromUndefinedOr(blocks.get(condition)), {
918
+ onNone: () => blocks.set(condition, [line]),
919
+ onSome: (lines) => lines.push(line),
920
+ })
921
+ }
922
+
923
+ /** The blocks' CSS: the unconditional `:root` first, then each condition's under `@supports`. */
924
+ const blocksCss = (blocks: Blocks): string =>
925
+ Arr.map(Arr.sort(Array.from(blocks.keys()), Order.String), (condition) => {
926
+ const root = `:root{${(blocks.get(condition) as Array<string>).join(";")}}`
927
+ return Bool.match(condition === "", { onTrue: () => root, onFalse: () => `@supports ${condition}{${root}}` })
928
+ }).join("")
929
+
930
+ /** A sheet for one render: a slot per element, and the CSS for the head. */
931
+ export const sheet = (): Sheet => {
932
+ let slots = 0
933
+ // The rules to write, and the names of those written: a chunk doesn't send a rule the head has.
934
+ const rules = new Map<string, string>()
935
+ const written = new Set<string>()
936
+ const blocks: Blocks = new Map()
937
+ const reducedBlocks: Blocks = new Map()
938
+ /** A rule added to the sheet, unless it has been written. */
939
+ const add = (rule: Keyframes): void => {
940
+ if (Bool.not(written.has(rule.name))) rules.set(rule.name, rule.css)
941
+ }
942
+ /** A play's rule added to the sheet: its `animation` value, and the geometry properties it writes. */
943
+ const animationFor = (play: Play): Result.Result<{ readonly animation: string; readonly supports: ReadonlyArray<string> }, string> =>
944
+ Result.map(keyframes(play.spec), (rule) => {
945
+ add(rule)
946
+ return { animation: animationOf(rule, play.delay), supports: rule.supports }
947
+ })
948
+ return {
949
+ batch: (play, reduced) => {
950
+ const property = `--${PREFIX}a${slots++}`
951
+ add(play)
952
+ addTo(blocks, "", `${property}:${slotAnimationOf(play)}`)
953
+ UndefinedOr.map(reduced, (rule) => {
954
+ add(rule)
955
+ addTo(reducedBlocks, "", `${property}:${slotAnimationOf(rule)}`)
956
+ })
957
+ return {
958
+ styleOf: (member, delay) =>
959
+ UndefinedOr.map(play.memberStyle(member), (own) => {
960
+ // Once a member a render, on a server: its own values (both rules', which read the same), and the
961
+ // slot with its delay after it, the shorthand's second time: a longhand after a `var()` shorthand
962
+ // leaves the inline `animation` unreadable, which `pending` reads.
963
+ const reducedOwn = UndefinedOr.match(reduced, { onUndefined: () => ({}), onDefined: (rule) => rule.memberStyle(member) })
964
+ const wait = Bool.match(delay === 0, { onTrue: () => "", onFalse: () => ` ${numberText(delay)}s` })
965
+ return { ...own, ...reducedOwn, animation: `var(${property})${wait}` }
966
+ }),
967
+ }
968
+ },
969
+ slot: () => {
970
+ const property = `--${PREFIX}a${slots++}`
971
+ return {
972
+ animation: `var(${property})`,
973
+ define: (play, reduced, supports = []) =>
974
+ Result.map(
975
+ Result.all([animationFor(play), UndefinedOr.match(reduced, { onUndefined: () => Result.succeed(undefined), onDefined: animationFor })]),
976
+ ([normal, reducedPlay]) => {
977
+ const reducedSupports = UndefinedOr.match(reducedPlay, { onUndefined: () => supports, onDefined: (r) => r.supports })
978
+ const condition = Bool.match(
979
+ Bool.and(Arr.isReadonlyArrayEmpty(normal.supports), Bool.and(Arr.isReadonlyArrayEmpty(reducedSupports), Arr.isReadonlyArrayEmpty(supports))),
980
+ { onTrue: () => "", onFalse: () => conditionOf(supportsOf(Arr.flatten([normal.supports, reducedSupports, supports]))) },
981
+ )
982
+ addTo(blocks, condition, `${property}:${normal.animation}`)
983
+ UndefinedOr.map(reducedPlay, (r) => addTo(reducedBlocks, condition, `${property}:${r.animation}`))
984
+ },
985
+ ),
986
+ }
987
+ },
988
+ css: () => {
989
+ const text = `${Array.from(rules.values()).join("")}${blocksCss(blocks)}${
990
+ Bool.match(reducedBlocks.size === 0, {
991
+ onTrue: () => "",
992
+ onFalse: () => `@media (prefers-reduced-motion: reduce){${blocksCss(reducedBlocks)}}`,
993
+ })
994
+ }`
995
+ Arr.forEach(Array.from(rules.keys()), (name) => written.add(name))
996
+ rules.clear()
997
+ blocks.clear()
998
+ reducedBlocks.clear()
999
+ return text
1000
+ },
1001
+ }
1002
+ }
1003
+
1004
+ // --- A late chunk's rules ----------------------------------------------------------------------
1005
+
1006
+ /**
1007
+ * The attribute a late chunk's `<style>` carries: a chunk a stream sends after its shell brings its own
1008
+ * rules, in a node its client doesn't render.
1009
+ */
1010
+ // #245, ADR-0044 *Amendment (#245)*.
1011
+ export const CHUNK_ATTRIBUTE = "data-wardic-appear-chunk"
1012
+
1013
+ /**
1014
+ * A late chunk's `<style>` for `css`, as server text; "" for none. With a `nonce`, the one the page's
1015
+ * Content Security Policy gives inline styles, it carries it.
1016
+ */
1017
+ // `nonce`: #618 (P1), Motion's `MotionConfig` `nonce`.
1018
+ export const chunkStyle = (css: string, nonce?: string): string => {
1019
+ if (css === "") return ""
1020
+ if (Predicate.isUndefined(nonce)) return `<style ${CHUNK_ATTRIBUTE}>${css}</style>`
1021
+ return `<style ${CHUNK_ATTRIBUTE} nonce="${escapeAttribute(nonce)}">${css}</style>`
1022
+ }
1023
+
1024
+ /** `value` safe inside a double-quoted attribute. */
1025
+ const escapeAttribute = (value: string): string => value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;")
1026
+
1027
+ /** The documents {@link adoptChunks} watches, or has: one observer a document. */
1028
+ // Module state (#460, Q7): the documents already watched, held weakly.
1029
+ const watched = /*#__PURE__*/ new WeakSet<Document>()
1030
+
1031
+ /**
1032
+ * Moves each late chunk's Appear rules into the head: its `<style data-wardic-appear-chunk>`'s text into a
1033
+ * head `<style>`, then the node out, before the chunk hydrates, since a hydrating client expects no node it
1034
+ * doesn't render. The text goes first, so the rule a running animation plays is never missing. Chunks
1035
+ * already in the document move at once; while it's still loading, a stream still coming, a
1036
+ * `MutationObserver` moves each as it lands, until `DOMContentLoaded`. Every call moves what's there; one
1037
+ * observer a document.
1038
+ */
1039
+ // #245. Leaving the node would shift sibling selectors. Each provider hydrating asks before its subtree
1040
+ // hydrates.
1041
+ export const adoptChunks = (doc: Document): void => {
1042
+ const adopt = (): void =>
1043
+ Arr.forEach(Array.from(doc.querySelectorAll(`style[${CHUNK_ATTRIBUTE}]`)), (node) => {
1044
+ const style = doc.createElement("style")
1045
+ style.setAttribute("data-wardic-appear", "")
1046
+ style.textContent = node.textContent
1047
+ doc.head.append(style)
1048
+ node.remove()
1049
+ })
1050
+ adopt()
1051
+ if (Bool.or(doc.readyState !== "loading", watched.has(doc))) return
1052
+ watched.add(doc)
1053
+ const observer = new MutationObserver(adopt)
1054
+ observer.observe(doc.documentElement, { childList: true, subtree: true })
1055
+ doc.addEventListener("DOMContentLoaded", () => {
1056
+ adopt()
1057
+ observer.disconnect()
1058
+ }, { once: true })
1059
+ }
1060
+
1061
+ // --- The Handoff -------------------------------------------------------------------------------
1062
+
1063
+ /** A `CSSAnimation`'s name, where the animation has one. */
1064
+ const nameOfAnimation = (animation: Animation): Option.Option<string> =>
1065
+ Option.filter(Option.some((animation as Animation & { readonly animationName?: unknown }).animationName), Predicate.isString)
1066
+
1067
+ /** Whether `animation` is an Appear one: a `wardic-…` CSS animation. */
1068
+ const isAppearAnimation = (animation: Animation): boolean => Option.exists(nameOfAnimation(animation), (name) => name.startsWith(PREFIX))
1069
+
1070
+ /**
1071
+ * Whether `name` is a Batch's rule's (#706): `wardic-b<key>-<shape>`, two hashes, where an element's is
1072
+ * `wardic-<hash>`, one, and a hash has no `-`.
1073
+ */
1074
+ const isBatchRuleName = (name: string): boolean => name.includes("-", PREFIX.length)
1075
+
1076
+ /** Whether `animation` is an element's own Appear one: a `wardic-…` CSS animation, not a Batch's rule. */
1077
+ const isElementAppearAnimation = (animation: Animation): boolean =>
1078
+ Option.exists(nameOfAnimation(animation), (name) => Bool.and(name.startsWith(PREFIX), Bool.not(isBatchRuleName(name))))
1079
+
1080
+ /** The element an animation draws, where it has one. */
1081
+ const targetOf = (animation: Animation): Option.Option<Element> =>
1082
+ Option.flatMap(Option.fromNullishOr(animation.effect), (effect) => Option.fromNullishOr((effect as KeyframeEffect).target))
1083
+
1084
+ /**
1085
+ * The element's Appear animation: its `wardic-…` CSS animation, running, or finished and filling. A
1086
+ * Batch's rule on a member's element isn't one (#706): its Batch takes it over, not a Wardic element there.
1087
+ */
1088
+ // ADR-0044, decision 6.
1089
+ export const find = (element: Element): Option.Option<Animation> =>
1090
+ Bool.match(Predicate.hasProperty(element, "getAnimations"), {
1091
+ onFalse: () => Option.none(),
1092
+ onTrue: () => Arr.findFirst(element.getAnimations(), isElementAppearAnimation),
1093
+ })
1094
+
1095
+ /**
1096
+ * A document's Appear animations by element, running or finished and filling: one `getAnimations()` for
1097
+ * the page, for a Handoff of many elements at once, a Batch's members (#706). Each element's first: a
1098
+ * member's Batch rule, or the one `find` gets.
1099
+ */
1100
+ // #706, Q3: measured at a Batch's 1,000 members in one list, Chromium's `Element.getAnimations()` cost
1101
+ // about a whole document's each (5.6 s for every member; the document's, 5.6 ms); Firefox's, alike either way.
1102
+ export const findAll = (doc: Document): ReadonlyMap<Element, Animation> => {
1103
+ const byElement = new Map<Element, Animation>()
1104
+ if (Bool.not(Predicate.hasProperty(doc, "getAnimations"))) return byElement
1105
+ // Once a Handoff, over the page's animations: the first per element, as `find`'s.
1106
+ Arr.forEach(Arr.filter(doc.getAnimations(), isAppearAnimation), (animation) =>
1107
+ Option.map(Option.filter(targetOf(animation), (target) => Bool.not(byElement.has(target))), (target) => byElement.set(target, animation)))
1108
+ return byElement
1109
+ }
1110
+
1111
+ /** Whether `animation` is `spec`'s: the rule the server sampled from the same spec. */
1112
+ export const matches = (animation: Animation, spec: Pick<Spec, "key" | "tag" | "infinite" | "projected">): boolean =>
1113
+ Option.exists(nameOfAnimation(animation), (name) => name === nameOf(spec))
1114
+
1115
+ /**
1116
+ * Whether `animation` is a Batch rule for a spec's `key`: its name starts with the key's prefix, so the
1117
+ * server's transitions and reduced motion are the client's. Its members' values aren't checked (#706, Q9).
1118
+ */
1119
+ export const matchesBatch = (animation: Animation, key: string): boolean =>
1120
+ Option.exists(nameOfAnimation(animation), (name) => name.startsWith(batchPrefixOf(key)))
1121
+
1122
+ /** How far `animation` has got, in seconds since it started (its delay included): 0 before it has. */
1123
+ export const elapsedOf = (animation: Animation): number =>
1124
+ Option.match(Option.filter(Option.fromNullishOr(animation.currentTime), Predicate.isNumber), {
1125
+ onNone: () => 0,
1126
+ onSome: (ms) => Math.max(0, ms / 1000),
1127
+ })
1128
+
1129
+ /** The delay `animation` started after, in seconds: what its element's `animation-delay` holds. */
1130
+ export const delayOf = (animation: Animation): number =>
1131
+ Option.match(Option.filter(Option.fromNullishOr(animation.effect), (effect) => Predicate.isNotUndefined(effect.getTiming)), {
1132
+ onNone: () => 0,
1133
+ onSome: (effect) => Option.getOrElse(Option.filter(Option.some(effect.getTiming().delay), Predicate.isNumber), () => 0) / 1000,
1134
+ })