@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,740 @@
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 * as Machine from "@wardic/core/Machine";
21
+ import * as Projection from "@wardic/core/Projection";
22
+ import * as Arr from "effect/Array";
23
+ import * as Bool from "effect/Boolean";
24
+ import { identity } from "effect/Function";
25
+ import * as Match from "effect/Match";
26
+ import * as Option from "effect/Option";
27
+ import * as Order from "effect/Order";
28
+ import * as Predicate from "effect/Predicate";
29
+ import * as Rec from "effect/Record";
30
+ import * as Result from "effect/Result";
31
+ import * as UndefinedOr from "effect/UndefinedOr";
32
+ import { spacesRegistered } from "./colors.js";
33
+ import { drawnUnitOf, project, TEMPLATE_KEY, TRANSFORM_FUNCS, unitOf } from "./renderer.js";
34
+ import { PREFIX } from "./appear-slot.js";
35
+ import { dashCase, isPathKey, isSvgInnerTag, splitPatchForTag, svgAttrNameOf } from "./svg.js";
36
+ /** The longest mount animation sampled, in seconds; a longer one keeps its Starting style. */
37
+ export const MAX_SECONDS = 60;
38
+ const MAX_STEPS = /*#__PURE__*/ Math.round(MAX_SECONDS / Machine.CATCH_UP_DT);
39
+ // --- The spec's name ---------------------------------------------------------------------------
40
+ /** cyrb53, a 53-bit string hash: plenty for a page's specs, and the same in every engine. */
41
+ const hash53 = (text) => {
42
+ const [h1, h2] = Arr.reduce(Array.from(text), [0xdeadbeef, 0x41c6ce57], ([a, b], char) => {
43
+ const code = char.codePointAt(0);
44
+ return [Math.imul(a ^ code, 2654435761), Math.imul(b ^ code, 1597334677)];
45
+ });
46
+ const a = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
47
+ const b = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
48
+ return (4294967296 * (2097151 & b) + (a >>> 0)).toString(36);
49
+ };
50
+ /** Each spec's name by its text, so a page's elements sharing a spec hash it once; the oldest dropped past `NAMES_SIZE`. */
51
+ // Module state (#460, Q7): a cache keyed by what it caches: a bounded set of names.
52
+ const names = /*#__PURE__*/ new Map();
53
+ const NAMES_SIZE = 4096;
54
+ /** The rule's name for a spec: its key, tag, repeat and projection, hashed. */
55
+ // Once a text: a server names each element's spec.
56
+ export const nameOf = (spec) => {
57
+ const text = specTextOf(spec);
58
+ return Option.getOrElse(Option.fromUndefinedOr(names.get(text)), () => {
59
+ const name = `${PREFIX}${hash53(text)}`;
60
+ if (names.size >= NAMES_SIZE)
61
+ names.clear();
62
+ names.set(text, name);
63
+ return name;
64
+ });
65
+ };
66
+ /** A spec's text, which its rule's name hashes: its tag, repeat, key and projection. */
67
+ const specTextOf = (spec) => `${UndefinedOr.match(spec.tag, { onUndefined: () => "", onDefined: (tag) => tag })}|${spec.infinite === true}|${spec.key}${Bool.match(spec.projected === true, { onTrue: () => "|projected", onFalse: () => "" })}`;
68
+ // --- Sampling ----------------------------------------------------------------------------------
69
+ /**
70
+ * The spec's Frames' values at 0, 1/60 s, 2/60 s… to the settled one: `startAt`'s catch-up steps,
71
+ * so the client's `startAt(k / 60)` draws the `k`th. Each copied, since a machine may rewrite its
72
+ * Frame in place (`springValues`, ADR-0030 decision 11). `None` past `MAX_SECONDS`.
73
+ */
74
+ const framesOf = (machine) => {
75
+ const step = machine.start();
76
+ // Copied before the next step, which may rewrite it.
77
+ const copy = (frame) => ({ values: { ...frame.value }, done: frame.done });
78
+ return unfoldFrames(copy(step(0)), () => copy(step(Machine.CATCH_UP_DT)));
79
+ };
80
+ /**
81
+ * A series' values from its first sample and each next one, 1/60 s on, to the one that settles: `None`
82
+ * past `MAX_SECONDS`. An element's machine's (`framesOf`) and a Batch's (#706).
83
+ */
84
+ const unfoldFrames = (first, next) => {
85
+ const rest = Arr.unfold({ frame: first, steps: 0 }, ({ frame, steps }) => Bool.match(Bool.or(frame.done, steps >= MAX_STEPS), {
86
+ onTrue: () => Option.none(),
87
+ onFalse: () => {
88
+ const sampled = next();
89
+ return Option.some([sampled, { frame: sampled, steps: steps + 1 }]);
90
+ },
91
+ }));
92
+ const frames = Arr.prepend(rest, first);
93
+ return Option.liftPredicate(Arr.map(frames, (frame) => frame.values), () => Arr.lastNonEmpty(frames).done);
94
+ };
95
+ const NUMBER_TOKEN = /(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)([a-z%]*)/gi;
96
+ /** A value split into its numbers and the text around them; a number is one token with no text. */
97
+ const splitOf = (value) => Bool.match(Predicate.isNumber(value), {
98
+ onTrue: () => ({ skeleton: "#", numbers: [value], decimals: [Number.POSITIVE_INFINITY], units: [""] }),
99
+ onFalse: () => {
100
+ const text = String(value);
101
+ const tokens = Array.from(text.matchAll(NUMBER_TOKEN));
102
+ return {
103
+ skeleton: text.replace(NUMBER_TOKEN, "#$2"),
104
+ numbers: Arr.map(tokens, (match) => Number(match[1])),
105
+ decimals: Arr.map(tokens, (match) => decimalsOf(String(match[1]))),
106
+ units: Arr.map(tokens, (match) => String(match[2]).toLowerCase()),
107
+ };
108
+ },
109
+ });
110
+ /** How many decimals `token` is written with: none for `12`, two for `0.53`. */
111
+ const decimalsOf = (token) => Option.match(Option.fromNullishOr(/\.(\d+)/.exec(token)), { onNone: () => 0, onSome: (match) => String(match[1]).length });
112
+ /**
113
+ * The tolerance per key and token (decision 9): what a straight line between two stops may miss a
114
+ * 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
115
+ * (opacity). A token in a string by its own unit, `px` and `deg` alike; any other by its part of
116
+ * its range, 1/500 (a colour channel's half step), and never finer than the decimals it's written
117
+ * with.
118
+ */
119
+ const tolerancesOf = (key, svgInner, series) => Arr.map(Arr.headNonEmpty(series).numbers, (_, token) => {
120
+ const values = Arr.map(series, (split) => split.numbers[token]);
121
+ const span = Math.max(...values) - Math.min(...values);
122
+ const decimals = Math.min(6, Math.max(...Arr.map(series, (split) => split.decimals[token])));
123
+ const unit = Arr.headNonEmpty(series).units[token];
124
+ const bare = Arr.headNonEmpty(series).skeleton === "#";
125
+ return Math.max(1e-9, toleranceFor(key, svgInner, bare, unit, span, 10 ** -decimals));
126
+ });
127
+ const toleranceFor = (key, svgInner, bare, unit, span, quantum) => Bool.match(bare, {
128
+ onTrue: () => Bool.match(svgInner, { onTrue: () => svgTolerance(key), onFalse: () => bareTolerance(key) }),
129
+ onFalse: () => Bool.match(unit === "px" || unit === "deg", {
130
+ onTrue: () => Math.max(0.1, quantum),
131
+ onFalse: () => Math.max(span / 500, quantum),
132
+ }),
133
+ });
134
+ /** A bare number's tolerance, by the unit `project` draws `key` in. */
135
+ const bareTolerance = (key) => Bool.match(drawnUnitOf(key) === "", {
136
+ onTrue: () => Bool.match(BaseValue.TRANSFORM_IDENTITY[key] === 1, { onTrue: () => 0.001, onFalse: () => 0.002 }),
137
+ onFalse: () => 0.1,
138
+ });
139
+ /** The opacities an svg-inner element draws as attributes, judged as opacity is. */
140
+ const SVG_OPACITIES = /*#__PURE__*/ new Set(["opacity", "fillOpacity", "strokeOpacity", "stopOpacity", "floodOpacity"]);
141
+ /**
142
+ * A bare number's tolerance on an svg-inner element (#245), by what its attribute means: a
143
+ * normalised dash (`pathLength`, `pathOffset`, `pathSpacing`: 0 to 1 of the path) 0.001, an
144
+ * opacity 0.002, any other attribute in user units, a CSS px, 0.1. A key drawn as style (the
145
+ * transform's) as on HTML.
146
+ */
147
+ const svgTolerance = (key) => Bool.match(isPathKey(key), {
148
+ onTrue: () => 0.001,
149
+ onFalse: () => Option.match(svgAttrNameOf(key), {
150
+ onNone: () => bareTolerance(key),
151
+ onSome: () => Bool.match(SVG_OPACITIES.has(key), { onTrue: () => 0.002, onFalse: () => 0.1 }),
152
+ }),
153
+ });
154
+ /** A series of Frames split per key, with each key's tolerances: what the stops are judged on. */
155
+ const judged = (frames, svgInner) => {
156
+ const keys = Arr.flatMap(Arr.take(frames, 1), Rec.keys);
157
+ const splits = Arr.map(keys, (key) => Arr.map(frames, (frame) => splitOf(UndefinedOr.match(frame[key], { onUndefined: () => "", onDefined: (v) => v }))));
158
+ const tolerances = Arr.map(keys, (key, k) => tolerancesOf(key, svgInner, splits[k]));
159
+ /** Whether stop `i` is within every key's tolerance of where a straight line from `a` to `b` puts it. */
160
+ const onLine = (i, a, b) => Arr.every(splits, (series, k) => {
161
+ const from = series[a];
162
+ const to = series[b];
163
+ const at = series[i];
164
+ return at.skeleton === from.skeleton && at.skeleton === to.skeleton &&
165
+ Arr.every(at.numbers, (value, token) => {
166
+ const line = from.numbers[token] + ((to.numbers[token] - from.numbers[token]) * (i - a)) / Math.max(1, b - a);
167
+ return Math.abs(value - line) <= tolerances[k][token];
168
+ });
169
+ });
170
+ /**
171
+ * Whether the Frame at `k` jumps from the one before: a key's text changes (a discrete value), or
172
+ * one of its numbers moves past its tolerance and four times its moves on either side (a loop's
173
+ * seam, a `steps()` easing, a snap). The engine draws one Frame, then the other; a line between
174
+ * them would draw values it never does.
175
+ */
176
+ const jumpAt = (k) => Arr.some(splits, (series, j) => {
177
+ const before = series[k - 1];
178
+ const at = series[k];
179
+ return Bool.or(at.skeleton !== before.skeleton, Arr.some(at.numbers, (value, token) => {
180
+ const move = (i) => Option.getOrElse(Option.map(Option.all([Option.fromUndefinedOr(series[i]), Option.fromUndefinedOr(series[i - 1])]), ([a, b]) => Math.abs(a.numbers[token] - b.numbers[token])), () => 0);
181
+ const step = Math.abs(value - before.numbers[token]);
182
+ return Bool.and(step > tolerances[j][token], step > 4 * Math.max(move(k - 1), move(k + 1)));
183
+ }));
184
+ });
185
+ return { onLine, jumpAt };
186
+ };
187
+ /**
188
+ * The stops kept (decision 9), as indices into `frames`, and where the rule ends.
189
+ *
190
+ * - **It ends** at the first Frame from which every one is within tolerance of the settled Frame,
191
+ * drawn as the settled Frame: a tween stepped in 1/60 s settles a frame after it arrives, when
192
+ * its steps' sum crosses its duration.
193
+ * - **The stops kept** are the first, the end, and each one a straight line from the last kept can't
194
+ * reach past, within every key's tolerances.
195
+ * - **A jump** (`jumps`, kept stops): a Frame the one before it can't be drawn into, as `jumpAt`
196
+ * tells. The rule holds the Frame before it to halfway between them, then steps, so a display
197
+ * frame near either draws that Frame, not a value on a line through values the engine never draws.
198
+ */
199
+ export const thin = (frames, tag) => {
200
+ const last = frames.length - 1;
201
+ const svgInner = Predicate.isNotUndefined(tag) && isSvgInnerTag(tag);
202
+ const whole = judged(frames, svgInner);
203
+ const end = Option.match(Arr.findLastIndex(Arr.range(0, last), (i) => !whole.onLine(i, last, last)), {
204
+ onNone: () => 0,
205
+ onSome: (i) => Math.min(last, i + 1),
206
+ });
207
+ // The series drawn: the Frames up to the end, the end drawn as the settled Frame.
208
+ const { onLine, jumpAt } = judged(Arr.append(Arr.take(frames, end), frames[last]), svgInner);
209
+ /** Whether one straight line from stop `a` to stop `b` stands in for every stop between. */
210
+ const fits = (a, b) => Arr.every(Arr.range(a + 1, b - 1), (i) => onLine(i, a, b));
211
+ /** The farthest stop a line from `a` can reach. */
212
+ const reach = (a) => Option.getOrElse(Arr.findFirst(Arr.range(a + 1, end), (b) => b === end || !fits(a, b + 1)), () => end);
213
+ const kept = Arr.unfold(0, (a) => Bool.match(a >= end, { onTrue: () => Option.none(), onFalse: () => Option.some([reach(a), reach(a)]) }));
214
+ return { kept: [0, ...kept], end, jumps: Arr.filter(kept, jumpAt) };
215
+ };
216
+ /** A number written to at most four decimals, `-0` as `0`: finer than any tolerance, and short. */
217
+ const trimNumbers = (text) => text.replace(/-?(?:\d+\.\d+|\.\d+)(?:e[-+]?\d+)?|-?\d+e[-+]?\d+/gi, (token) => String(Number(Number(token).toFixed(4)) + 0));
218
+ /** A number for a rule's text: at most four decimals, as every stop's. */
219
+ const numberText = (value) => trimNumbers(String(value));
220
+ /** Text CSS can't hold inside a declaration, or that would end the `<style>` it sits in. */
221
+ const UNSAFE = /[<>{};]|\/\*|\\/;
222
+ /**
223
+ * The SVG attributes a keyframe draws as their CSS property (#245, ADR-0044 *Amendment (#245)*):
224
+ * presentation attributes, which a stylesheet's or an animation's value overrides, so the attribute
225
+ * the engine writes at the Handoff takes over value for value. Unitless, as the attribute is.
226
+ */
227
+ const SVG_PRESENTATION = /*#__PURE__*/ new Set([
228
+ "opacity",
229
+ "fill",
230
+ "stroke",
231
+ "stroke-width",
232
+ "fill-opacity",
233
+ "stroke-opacity",
234
+ "stroke-dasharray",
235
+ "stroke-dashoffset",
236
+ "stop-color",
237
+ "stop-opacity",
238
+ "flood-color",
239
+ "flood-opacity",
240
+ ]);
241
+ /**
242
+ * SVG 2's geometry properties a keyframe draws, in px, behind `@supports` (`Keyframes.supports`):
243
+ * Chrome and Firefox draw them from CSS, Safari only in part. Not `width` and `height`:
244
+ * `@supports (width: 0px)` holds for HTML in every browser, so it can't tell whether one draws a
245
+ * `<rect>`'s from CSS.
246
+ */
247
+ const SVG_GEOMETRY = /*#__PURE__*/ new Set(["cx", "cy", "r", "rx", "ry", "x", "y"]);
248
+ /** The attribute the stroke dash writes beside it, `pathLength="1"`: the Starting style writes it too, and it never changes. */
249
+ const SVG_FIXED = /*#__PURE__*/ new Set(["pathLength"]);
250
+ const BARE_NUMBER = /^-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?$/i;
251
+ /** An SVG attribute's declaration: a geometry property's bare number in px, what a user unit is. */
252
+ const attributeDeclaration = ([name, value]) => `${name}:${trimNumbers(Bool.match(Bool.and(SVG_GEOMETRY.has(name), BARE_NUMBER.test(value)), { onTrue: () => `${value}px`, onFalse: () => value }))}`;
253
+ /** Why an attribute can't be a keyframe's: it isn't a CSS property (`d` in Safari, `points`, a filter primitive's). */
254
+ const drawnOnlyAsAttribute = (name) => Bool.not(Bool.or(SVG_FIXED.has(name), Bool.or(SVG_PRESENTATION.has(name), SVG_GEOMETRY.has(name))));
255
+ /**
256
+ * One Frame's declarations, or why it can't be one: a key SVG draws only as an attribute, or unsafe
257
+ * text. An svg-inner element's attributes are drawn as their CSS properties where they have one; a
258
+ * layout node through its projection at rest (#245).
259
+ */
260
+ const declarationsOf = (tag, values, projected, template) => {
261
+ const { attrs, style } = splitPatchForTag(tag, project(drawnValuesOf(values, projected, template)));
262
+ const drawn = Arr.filter(Rec.toEntries(attrs), ([name]) => Bool.not(SVG_FIXED.has(name)));
263
+ const declarations = Arr.appendAll(Arr.map(Rec.toEntries(style), ([key, value]) => `${dashCase(key)}:${trimNumbers(String(value))}`), Arr.map(drawn, attributeDeclaration));
264
+ return Arr.match(Arr.filter(Rec.keys(attrs), drawnOnlyAsAttribute), {
265
+ onNonEmpty: (names) => Result.fail(`a key SVG draws only as an attribute (${names.join(", ")})`),
266
+ onEmpty: () => Option.match(Arr.findFirst(declarations, (declaration) => UNSAFE.test(declaration)), {
267
+ onSome: (declaration) => Result.fail(`a value CSS text can't hold (${declaration})`),
268
+ onNone: () => Result.succeed({ text: declarations.join(";"), supports: Arr.filter(Arr.map(drawn, ([name]) => name), (name) => SVG_GEOMETRY.has(name)) }),
269
+ }),
270
+ });
271
+ };
272
+ /** 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). */
273
+ const drawnValuesOf = (values, projected, template) => {
274
+ const drawn = Bool.match(projected, { onTrue: () => ({ ...values, [Projection.KEY]: Projection.AT_REST }), onFalse: () => values });
275
+ return UndefinedOr.match(template, { onUndefined: () => drawn, onDefined: (t) => ({ ...drawn, [TEMPLATE_KEY]: t }) });
276
+ };
277
+ /** A stop's offset in the rule, a percentage to six decimals, so a jump's hold sits before its stop. */
278
+ const percentOf = (stop, last) => `${String(Number(Bool.match(last === 0, { onTrue: () => 0, onFalse: () => (stop / last) * 100 }).toFixed(6)) + 0)}%`;
279
+ /**
280
+ * Where a jump falls: halfway between its two Frames, so a display frame drawn near either one, a
281
+ * vsync's jitter early or late, draws that Frame. The step takes a thousandth of a frame.
282
+ */
283
+ const JUMP_AT = 0.5;
284
+ const JUMP_TAKES = 0.001;
285
+ /**
286
+ * A sampled series' stops (decision 9): each one `thin` keeps, and at a jump, the Frame before it held to
287
+ * halfway, then its own; the end drawn as the settled Frame. An element's rule's and a Batch's.
288
+ */
289
+ const stopsOf = (frames, tag) => {
290
+ const last = frames.length - 1;
291
+ const { kept, end, jumps } = thin(frames, tag);
292
+ /** A kept stop's Frame: the end drawn as the settled Frame. */
293
+ const frameAt = (stop) => frames[Bool.match(stop === end, { onTrue: () => last, onFalse: () => stop })];
294
+ const stops = Arr.flatMap(kept, (stop) => Bool.match(Arr.contains(jumps, stop), {
295
+ onTrue: () => [
296
+ { offset: stop - JUMP_AT, frame: frames[stop - 1] },
297
+ { offset: stop - JUMP_AT + JUMP_TAKES, frame: frameAt(stop) },
298
+ { offset: stop, frame: frameAt(stop) },
299
+ ],
300
+ onFalse: () => [{ offset: stop, frame: frameAt(stop) }],
301
+ }));
302
+ return { stops, kept, end, last };
303
+ };
304
+ /** A rule's timing from its stops: how long it plays, when it settles, each stop's time. */
305
+ const timingOf = (series) => ({
306
+ duration: series.end * Machine.CATCH_UP_DT,
307
+ settled: series.last * Machine.CATCH_UP_DT,
308
+ times: Arr.map(series.kept, (stop) => stop * Machine.CATCH_UP_DT),
309
+ });
310
+ /** A rule's body: each stop's offset and its declarations, one stop of `0%,100%` for a rule that settles at once. */
311
+ const bodyOf = ({ stops, end }, texts) => Arr.map(Bool.match(end === 0, { onTrue: () => ["0%,100%"], onFalse: () => Arr.map(stops, ({ offset }) => percentOf(offset, end)) }), (offset, i) => `${offset}{${texts[i]}}`).join("");
312
+ /** A spec sampled into its rule, or why it can't be one. Not cached: {@link keyframes} is. */
313
+ const sample = (spec) => Option.match(framesOf(spec.machine()), {
314
+ onNone: () => Result.fail(`longer than ${MAX_SECONDS} s`),
315
+ onSome: (frames) => {
316
+ const projected = spec.projected === true;
317
+ const series = stopsOf(frames, spec.tag);
318
+ return Result.map(Result.all(Arr.map(series.stops, ({ frame }) => declarationsOf(spec.tag, frame, projected, spec.template))), (declarations) => {
319
+ const body = bodyOf(series, Arr.map(declarations, (d) => d.text));
320
+ const name = ruleNameOf(spec, body);
321
+ return {
322
+ name,
323
+ ...timingOf(series),
324
+ infinite: spec.infinite === true,
325
+ css: `@keyframes ${name}{${body}}`,
326
+ supports: supportsOf(Arr.flatMap(declarations, (d) => d.supports)),
327
+ };
328
+ });
329
+ },
330
+ });
331
+ /**
332
+ * A rule's name: its spec's ({@link nameOf}), or, for a templated spec (#443), its spec's text and
333
+ * its stops hashed, since a function can't name it: two templates that draw the same share one.
334
+ */
335
+ const ruleNameOf = (spec, body) => UndefinedOr.match(spec.template, {
336
+ onUndefined: () => nameOf(spec),
337
+ onDefined: () => `${PREFIX}${hash53(`${specTextOf(spec)}|template|${body}`)}`,
338
+ });
339
+ /** Geometry properties once each, in order: a condition's text is the same for the same set. */
340
+ const supportsOf = (properties) => Arr.sort(Arr.dedupe(properties), Order.String);
341
+ /** An `@supports` condition for geometry properties, `(cx:0px) and (r:0px)`; empty for none. */
342
+ const conditionOf = (properties) => Arr.map(properties, (property) => `(${property}:0px)`).join(" and ");
343
+ /**
344
+ * The rules sampled so far, across requests, by name, each with whether every CSS colour space was
345
+ * registered when it was (#511); the oldest dropped past `CACHE_SIZE`.
346
+ */
347
+ // Module state (#460, Q7): a cache keyed by what it caches: each mount animation's sampled keyframes, by its text.
348
+ const cache = /*#__PURE__*/ new Map();
349
+ const CACHE_SIZE = 512;
350
+ /**
351
+ * A spec's rule, or why it has none, for a debug log. Sampled once a spec and cached across requests by
352
+ * its name, since a spec's rule changes only once the page registers every colour space
353
+ * (`Color.registerSpaces`): a wide-gamut colour blends as written before, in sRGB after. Its name stays,
354
+ * so a client matches it whatever it had registered. A templated spec's is sampled each time: its name
355
+ * comes from its stops.
356
+ */
357
+ // #511; templates #443.
358
+ export const keyframes = (spec) => {
359
+ if (Predicate.isNotUndefined(spec.template))
360
+ return sample(spec);
361
+ const name = nameOf(spec);
362
+ const spaces = spacesRegistered();
363
+ const kept = cache.get(name);
364
+ if (Predicate.isNotUndefined(kept) && kept.spaces === spaces)
365
+ return kept.rule;
366
+ const sampled = sample(spec);
367
+ remember(cache, name, { spaces, rule: sampled });
368
+ return sampled;
369
+ };
370
+ /** `value` kept in `kept` by `name`, the oldest dropped past `CACHE_SIZE`: each rule cache's. */
371
+ const remember = (kept, name, value) => {
372
+ Option.map(Arr.head(Arr.take(Array.from(kept.keys()), Math.max(0, kept.size + 1 - CACHE_SIZE))), (oldest) => kept.delete(oldest));
373
+ kept.set(name, value);
374
+ return value;
375
+ };
376
+ /**
377
+ * An element's `animation` value for a play of `rule`: its name, length, delay and repeat, filling
378
+ * forwards. Not backwards: through its delay the element shows its inline starting style, which is the
379
+ * rule's first stop for a rule that moves from it.
380
+ */
381
+ // And the start a reduced rule's snap holds until the delay ends (ADR-0029), where the first stop is
382
+ // already snapped.
383
+ export const animationOf = (rule, delay) => `${rule.name} ${numberText(rule.duration)}s linear ${numberText(delay)}s ${Bool.match(rule.infinite, { onTrue: () => "infinite", onFalse: () => "1" })} forwards`;
384
+ /** The prefix a Batch rule's name starts with, from its spec's `key`: what a client checks. */
385
+ const batchPrefixOf = (key) => `${PREFIX}b${hash53(key)}-`;
386
+ /** The transform functions a Batch draws, in the renderer's order: its writer's, less a path's turn. */
387
+ const BATCH_FUNCS = /*#__PURE__*/ Arr.filter(TRANSFORM_FUNCS, (func) => func.key !== "pathRotation");
388
+ /** Whether every member that moves starts at one value and ends at one: the rule writes the key as it is. */
389
+ const isShared = (column) => Bool.and(column.sharedStart, column.sharedTarget);
390
+ /** The custom property for a key's start (`0`) or target (`1`). */
391
+ const propertyOf = (key, end) => `--${PREFIX}${key}${end}`;
392
+ /** A key's value with its unit: `120px`, `45deg`, `0.8`. */
393
+ const unitText = (column, value) => `${numberText(value)}${column.unit}`;
394
+ /** 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`. */
395
+ const progressText = (p) => String(Number(p.toFixed(5)) + 0);
396
+ /** What a stop writes for a key whose members' values differ: the shortest form for where it is. */
397
+ const ownText = /*#__PURE__*/ Match.type().pipe(Match.when(({ column }) => Bool.not(column.moves), ({ target }) => target), Match.when(({ p }) => p === 0, ({ start }) => start), Match.when(({ p }) => p === 1, ({ target }) => target), Match.when(({ column }) => Bool.and(column.sharedStart, column.start === 0), ({ p, target }) => `calc(${target} * ${progressText(p)})`), Match.when(({ column }) => Bool.and(column.sharedTarget, column.target === 0), ({ p, start }) => `calc(${start} * ${progressText(1 - p)})`), Match.orElse(({ p, start, target }) => `calc(${start} + (${target} - ${start}) * ${progressText(p)})`));
398
+ /** What a stop writes for a key, from its sampled value: a shared one as it is, an own one as its progress. */
399
+ const valueText = (column, frame) => {
400
+ const value = UndefinedOr.match(frame[column.key], { onUndefined: () => column.target, onDefined: identity });
401
+ return Bool.match(isShared(column), {
402
+ onTrue: () => unitText(column, value),
403
+ onFalse: () => ownText({
404
+ column,
405
+ p: value / column.span,
406
+ start: Bool.match(column.sharedStart, { onTrue: () => unitText(column, column.start), onFalse: () => `var(${propertyOf(column.key, 0)})` }),
407
+ target: Bool.match(column.sharedTarget, { onTrue: () => unitText(column, column.target), onFalse: () => `var(${propertyOf(column.key, 1)})` }),
408
+ }),
409
+ });
410
+ };
411
+ /** The power of two at or above `move`: a span shared by Batches whose longest moves are near. */
412
+ const spanOf = (move) => 2 ** Math.ceil(Math.log2(move));
413
+ /** Whether a member moves: some key's start isn't its target. */
414
+ const moves = (start, target) => Arr.some(start, (s, k) => s !== target[k]);
415
+ /** The members that move: one that plays nothing shares nothing with the rule. */
416
+ const moversOf = (spec) => {
417
+ const moving = Arr.filter(Arr.range(0, spec.starts.length - 1), (m) => moves(spec.starts[m], spec.targets[m]));
418
+ return {
419
+ starts: Arr.map(moving, (m) => spec.starts[m]),
420
+ targets: Arr.map(moving, (m) => spec.targets[m]),
421
+ };
422
+ };
423
+ /** Each of the spec's keys as a rule writes it, from the members that move. */
424
+ const columnsOf = (keys, movers) => Arr.map(keys, (key, k) => {
425
+ const starts = Arr.map(movers.starts, (start) => start[k]);
426
+ const targets = Arr.map(movers.targets, (target) => target[k]);
427
+ const start = UndefinedOr.match(starts[0], { onUndefined: () => 0, onDefined: identity });
428
+ const target = UndefinedOr.match(targets[0], { onUndefined: () => 0, onDefined: identity });
429
+ const longest = Math.max(0, ...Arr.map(starts, (s, m) => Math.abs(targets[m] - s)));
430
+ return {
431
+ key,
432
+ k,
433
+ unit: Bool.match(key === "opacity", { onTrue: () => "", onFalse: () => unitOf(key) }),
434
+ moves: longest > 0,
435
+ sharedStart: Arr.every(starts, (s) => s === start),
436
+ sharedTarget: Arr.every(targets, (t) => t === target),
437
+ start,
438
+ target,
439
+ span: Bool.match(longest > 0, { onTrue: () => spanOf(longest), onFalse: () => 1 }),
440
+ };
441
+ });
442
+ /**
443
+ * The columns a rule writes: `opacity` when it moves; and when any transform key moves, every transform
444
+ * key off its identity for some member, in the renderer's order, since the rule's `transform` replaces the
445
+ * element's whole.
446
+ */
447
+ const writtenOf = (movers, columns) => {
448
+ const byKey = new Map(Arr.map(columns, (column) => [column.key, column]));
449
+ const transform = Arr.filterMap(BATCH_FUNCS, (func) => Option.match(Option.fromUndefinedOr(byKey.get(func.key)), {
450
+ onNone: () => Result.failVoid,
451
+ onSome: (column) => {
452
+ const off = (value) => value[column.k] !== func.identity;
453
+ return Bool.match(Bool.or(Arr.some(movers.starts, off), Arr.some(movers.targets, off)), {
454
+ onTrue: () => Result.succeed({ ...column, fn: func.fn }),
455
+ onFalse: () => Result.failVoid,
456
+ });
457
+ },
458
+ }));
459
+ return {
460
+ transform: Bool.match(Arr.some(transform, (column) => column.moves), { onTrue: () => transform, onFalse: () => [] }),
461
+ opacity: Option.filter(Option.fromUndefinedOr(byKey.get("opacity")), (column) => column.moves),
462
+ };
463
+ };
464
+ /** A writer that draws nothing: the sampler reads a Batch's values, not its writes. */
465
+ const UNDRAWN = { writes: () => true, forKeys: () => () => undefined };
466
+ /**
467
+ * 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
468
+ * shared start to its shared target, or from 0 to its span, stepped as a client's Batch steps it. `None`
469
+ * past `MAX_SECONDS`.
470
+ */
471
+ const batchFramesOf = (spec, columns) => {
472
+ const moving = Arr.filter(columns, (column) => column.moves);
473
+ const batch = Batch.make({ keys: spec.keys, writer: UNDRAWN, transition: spec.transition });
474
+ const slot = Batch.enter(batch, null, Rec.fromEntries(Arr.map(moving, (column) => [column.key, Bool.match(isShared(column), { onTrue: () => column.start, onFalse: () => 0 })])));
475
+ const targets = Arr.map(columns, (column) => Bool.match(column.moves, {
476
+ onTrue: () => Bool.match(isShared(column), { onTrue: () => column.target, onFalse: () => column.span }),
477
+ onFalse: () => Number.NaN,
478
+ }));
479
+ Batch.retarget(batch, [slot], (_, k) => targets[k]);
480
+ // Each step's values, and whether the Batch rests after it; the first at 0 s, as `framesOf`'s.
481
+ const after = (done) => ({ values: Rec.fromEntries(Arr.map(moving, (column) => [column.key, Batch.get(batch, slot, column.key)])), done });
482
+ return unfoldFrames(after(Batch.step(batch, 0)), () => after(Batch.step(batch, Machine.CATCH_UP_DT)));
483
+ };
484
+ /**
485
+ * A Batch's rule's name: its key's hash, then the hash of what it writes and how: each key's shared start
486
+ * and target, written into it, and an own key's span. Members' own values aren't in it, so Batches whose
487
+ * members differ but whose longest moves share a span share a rule.
488
+ */
489
+ const batchNameOf = (spec, columns) => {
490
+ const shape = Arr.map(columns, (column) => {
491
+ const start = Bool.match(column.sharedStart, { onTrue: () => String(column.start), onFalse: () => "*" });
492
+ const target = Bool.match(column.sharedTarget, { onTrue: () => String(column.target), onFalse: () => "*" });
493
+ return `${column.key}:${column.moves}:${start}:${target}:${column.span}`;
494
+ }).join("|");
495
+ return `${batchPrefixOf(spec.key)}${hash53(`${spec.keys.join(",")}|${shape}`)}`;
496
+ };
497
+ /** The Batch rules sampled so far, across requests, by name (as {@link keyframes}' cache): each member's own values aren't in them. */
498
+ // Module state (#460, Q7): a cache keyed by what it caches.
499
+ const batchCache = /*#__PURE__*/ new Map();
500
+ /** A spec's first key with a start or target that isn't a finite number: a rule can't write it. */
501
+ const unfiniteKeyOf = (spec) => Arr.findFirst(spec.keys, (_, k) => Arr.some(Arr.appendAll(spec.starts, spec.targets), (values) => Bool.not(Number.isFinite(values[k]))));
502
+ /**
503
+ * A Batch's rule for its members' entrance, or why it has none: one `@keyframes` for every member, each
504
+ * key's stops sampled from the Batch's own spring or tween at 60 Hz and thinned within its tolerance at
505
+ * its longest move. A key whose start and target every member that moves shares is written as it is;
506
+ * one whose values differ, as each member's custom properties and its progress between them.
507
+ */
508
+ // #706, Q2 A. Sampled once a shape a process, as an element's spec is.
509
+ export const batchKeyframes = (spec) => {
510
+ const unfinite = unfiniteKeyOf(spec);
511
+ if (Option.isSome(unfinite))
512
+ return Result.fail(`a start or target that isn't a finite number (${unfinite.value})`);
513
+ const movers = moversOf(spec);
514
+ const columns = columnsOf(spec.keys, movers);
515
+ const written = writtenOf(movers, columns);
516
+ if (Bool.and(Arr.isReadonlyArrayEmpty(written.transform), Option.isNone(written.opacity)))
517
+ return Result.fail("no key moves");
518
+ const name = batchNameOf(spec, columns);
519
+ const rule = Option.getOrElse(Option.fromUndefinedOr(batchCache.get(name)), () => remember(batchCache, name, sampleBatch(spec, columns, written, name)));
520
+ const own = Arr.filter(Arr.appendAll(written.transform, Option.toArray(written.opacity)), (column) => Bool.not(isShared(column)));
521
+ return Result.map(rule, (keyframes) => ({
522
+ ...keyframes,
523
+ memberStyle: (member) => {
524
+ const start = spec.starts[member];
525
+ const target = spec.targets[member];
526
+ return Bool.match(moves(start, target), {
527
+ onFalse: () => undefined,
528
+ onTrue: () => Rec.fromEntries(Arr.flatMap(own, (column) => [
529
+ ...Bool.match(Bool.and(column.moves, Bool.not(column.sharedStart)), { onTrue: () => [[propertyOf(column.key, 0), unitText(column, start[column.k])]], onFalse: () => [] }),
530
+ ...Bool.match(column.sharedTarget, { onTrue: () => [], onFalse: () => [[propertyOf(column.key, 1), unitText(column, target[column.k])]] }),
531
+ ])),
532
+ });
533
+ },
534
+ }));
535
+ };
536
+ /** A Batch's rule sampled, or why it can't be. Not cached: {@link batchKeyframes} is. */
537
+ const sampleBatch = (spec, columns, written, name) => Option.match(batchFramesOf(spec, columns), {
538
+ onNone: () => Result.fail(`longer than ${MAX_SECONDS} s`),
539
+ onSome: (frames) => {
540
+ const series = stopsOf(frames, undefined);
541
+ const texts = Arr.map(series.stops, ({ frame }) => {
542
+ const transform = Arr.map(written.transform, (column) => `${column.fn}(${valueText(column, frame)})`).join(" ");
543
+ const declarations = Arr.appendAll(Bool.match(transform === "", { onTrue: () => [], onFalse: () => [`transform:${transform}`] }), Option.toArray(Option.map(written.opacity, (column) => `opacity:${valueText(column, frame)}`)));
544
+ return declarations.join(";");
545
+ });
546
+ const body = bodyOf(series, texts);
547
+ return Result.succeed({ name, ...timingOf(series), infinite: false, css: `@keyframes ${name}{${body}}`, supports: [] });
548
+ },
549
+ });
550
+ /**
551
+ * A Batch slot's `animation`, less a delay: each member's inline `animation` names the slot and gives its
552
+ * own after it, `var(--wardic-aN) 0.035s`, the shorthand's second time. A delay here too would be a third,
553
+ * and the member's `animation` invalid: it would keep its start.
554
+ */
555
+ // #706, Q2 and Q6: one `:root` line a rule group, which reduced motion's media query switches; a member's stagger its own.
556
+ const slotAnimationOf = (rule) => `${rule.name} ${numberText(rule.duration)}s linear 1 forwards`;
557
+ /** A block's declarations added under its condition. */
558
+ const addTo = (blocks, condition, line) => {
559
+ Option.match(Option.fromUndefinedOr(blocks.get(condition)), {
560
+ onNone: () => blocks.set(condition, [line]),
561
+ onSome: (lines) => lines.push(line),
562
+ });
563
+ };
564
+ /** The blocks' CSS: the unconditional `:root` first, then each condition's under `@supports`. */
565
+ const blocksCss = (blocks) => Arr.map(Arr.sort(Array.from(blocks.keys()), Order.String), (condition) => {
566
+ const root = `:root{${blocks.get(condition).join(";")}}`;
567
+ return Bool.match(condition === "", { onTrue: () => root, onFalse: () => `@supports ${condition}{${root}}` });
568
+ }).join("");
569
+ /** A sheet for one render: a slot per element, and the CSS for the head. */
570
+ export const sheet = () => {
571
+ let slots = 0;
572
+ // The rules to write, and the names of those written: a chunk doesn't send a rule the head has.
573
+ const rules = new Map();
574
+ const written = new Set();
575
+ const blocks = new Map();
576
+ const reducedBlocks = new Map();
577
+ /** A rule added to the sheet, unless it has been written. */
578
+ const add = (rule) => {
579
+ if (Bool.not(written.has(rule.name)))
580
+ rules.set(rule.name, rule.css);
581
+ };
582
+ /** A play's rule added to the sheet: its `animation` value, and the geometry properties it writes. */
583
+ const animationFor = (play) => Result.map(keyframes(play.spec), (rule) => {
584
+ add(rule);
585
+ return { animation: animationOf(rule, play.delay), supports: rule.supports };
586
+ });
587
+ return {
588
+ batch: (play, reduced) => {
589
+ const property = `--${PREFIX}a${slots++}`;
590
+ add(play);
591
+ addTo(blocks, "", `${property}:${slotAnimationOf(play)}`);
592
+ UndefinedOr.map(reduced, (rule) => {
593
+ add(rule);
594
+ addTo(reducedBlocks, "", `${property}:${slotAnimationOf(rule)}`);
595
+ });
596
+ return {
597
+ styleOf: (member, delay) => UndefinedOr.map(play.memberStyle(member), (own) => {
598
+ // Once a member a render, on a server: its own values (both rules', which read the same), and the
599
+ // slot with its delay after it, the shorthand's second time: a longhand after a `var()` shorthand
600
+ // leaves the inline `animation` unreadable, which `pending` reads.
601
+ const reducedOwn = UndefinedOr.match(reduced, { onUndefined: () => ({}), onDefined: (rule) => rule.memberStyle(member) });
602
+ const wait = Bool.match(delay === 0, { onTrue: () => "", onFalse: () => ` ${numberText(delay)}s` });
603
+ return { ...own, ...reducedOwn, animation: `var(${property})${wait}` };
604
+ }),
605
+ };
606
+ },
607
+ slot: () => {
608
+ const property = `--${PREFIX}a${slots++}`;
609
+ return {
610
+ animation: `var(${property})`,
611
+ define: (play, reduced, supports = []) => Result.map(Result.all([animationFor(play), UndefinedOr.match(reduced, { onUndefined: () => Result.succeed(undefined), onDefined: animationFor })]), ([normal, reducedPlay]) => {
612
+ const reducedSupports = UndefinedOr.match(reducedPlay, { onUndefined: () => supports, onDefined: (r) => r.supports });
613
+ const condition = Bool.match(Bool.and(Arr.isReadonlyArrayEmpty(normal.supports), Bool.and(Arr.isReadonlyArrayEmpty(reducedSupports), Arr.isReadonlyArrayEmpty(supports))), { onTrue: () => "", onFalse: () => conditionOf(supportsOf(Arr.flatten([normal.supports, reducedSupports, supports]))) });
614
+ addTo(blocks, condition, `${property}:${normal.animation}`);
615
+ UndefinedOr.map(reducedPlay, (r) => addTo(reducedBlocks, condition, `${property}:${r.animation}`));
616
+ }),
617
+ };
618
+ },
619
+ css: () => {
620
+ const text = `${Array.from(rules.values()).join("")}${blocksCss(blocks)}${Bool.match(reducedBlocks.size === 0, {
621
+ onTrue: () => "",
622
+ onFalse: () => `@media (prefers-reduced-motion: reduce){${blocksCss(reducedBlocks)}}`,
623
+ })}`;
624
+ Arr.forEach(Array.from(rules.keys()), (name) => written.add(name));
625
+ rules.clear();
626
+ blocks.clear();
627
+ reducedBlocks.clear();
628
+ return text;
629
+ },
630
+ };
631
+ };
632
+ // --- A late chunk's rules ----------------------------------------------------------------------
633
+ /**
634
+ * The attribute a late chunk's `<style>` carries: a chunk a stream sends after its shell brings its own
635
+ * rules, in a node its client doesn't render.
636
+ */
637
+ // #245, ADR-0044 *Amendment (#245)*.
638
+ export const CHUNK_ATTRIBUTE = "data-wardic-appear-chunk";
639
+ /**
640
+ * A late chunk's `<style>` for `css`, as server text; "" for none. With a `nonce`, the one the page's
641
+ * Content Security Policy gives inline styles, it carries it.
642
+ */
643
+ // `nonce`: #618 (P1), Motion's `MotionConfig` `nonce`.
644
+ export const chunkStyle = (css, nonce) => {
645
+ if (css === "")
646
+ return "";
647
+ if (Predicate.isUndefined(nonce))
648
+ return `<style ${CHUNK_ATTRIBUTE}>${css}</style>`;
649
+ return `<style ${CHUNK_ATTRIBUTE} nonce="${escapeAttribute(nonce)}">${css}</style>`;
650
+ };
651
+ /** `value` safe inside a double-quoted attribute. */
652
+ const escapeAttribute = (value) => value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;");
653
+ /** The documents {@link adoptChunks} watches, or has: one observer a document. */
654
+ // Module state (#460, Q7): the documents already watched, held weakly.
655
+ const watched = /*#__PURE__*/ new WeakSet();
656
+ /**
657
+ * Moves each late chunk's Appear rules into the head: its `<style data-wardic-appear-chunk>`'s text into a
658
+ * head `<style>`, then the node out, before the chunk hydrates, since a hydrating client expects no node it
659
+ * doesn't render. The text goes first, so the rule a running animation plays is never missing. Chunks
660
+ * already in the document move at once; while it's still loading, a stream still coming, a
661
+ * `MutationObserver` moves each as it lands, until `DOMContentLoaded`. Every call moves what's there; one
662
+ * observer a document.
663
+ */
664
+ // #245. Leaving the node would shift sibling selectors. Each provider hydrating asks before its subtree
665
+ // hydrates.
666
+ export const adoptChunks = (doc) => {
667
+ const adopt = () => Arr.forEach(Array.from(doc.querySelectorAll(`style[${CHUNK_ATTRIBUTE}]`)), (node) => {
668
+ const style = doc.createElement("style");
669
+ style.setAttribute("data-wardic-appear", "");
670
+ style.textContent = node.textContent;
671
+ doc.head.append(style);
672
+ node.remove();
673
+ });
674
+ adopt();
675
+ if (Bool.or(doc.readyState !== "loading", watched.has(doc)))
676
+ return;
677
+ watched.add(doc);
678
+ const observer = new MutationObserver(adopt);
679
+ observer.observe(doc.documentElement, { childList: true, subtree: true });
680
+ doc.addEventListener("DOMContentLoaded", () => {
681
+ adopt();
682
+ observer.disconnect();
683
+ }, { once: true });
684
+ };
685
+ // --- The Handoff -------------------------------------------------------------------------------
686
+ /** A `CSSAnimation`'s name, where the animation has one. */
687
+ const nameOfAnimation = (animation) => Option.filter(Option.some(animation.animationName), Predicate.isString);
688
+ /** Whether `animation` is an Appear one: a `wardic-…` CSS animation. */
689
+ const isAppearAnimation = (animation) => Option.exists(nameOfAnimation(animation), (name) => name.startsWith(PREFIX));
690
+ /**
691
+ * Whether `name` is a Batch's rule's (#706): `wardic-b<key>-<shape>`, two hashes, where an element's is
692
+ * `wardic-<hash>`, one, and a hash has no `-`.
693
+ */
694
+ const isBatchRuleName = (name) => name.includes("-", PREFIX.length);
695
+ /** Whether `animation` is an element's own Appear one: a `wardic-…` CSS animation, not a Batch's rule. */
696
+ const isElementAppearAnimation = (animation) => Option.exists(nameOfAnimation(animation), (name) => Bool.and(name.startsWith(PREFIX), Bool.not(isBatchRuleName(name))));
697
+ /** The element an animation draws, where it has one. */
698
+ const targetOf = (animation) => Option.flatMap(Option.fromNullishOr(animation.effect), (effect) => Option.fromNullishOr(effect.target));
699
+ /**
700
+ * The element's Appear animation: its `wardic-…` CSS animation, running, or finished and filling. A
701
+ * Batch's rule on a member's element isn't one (#706): its Batch takes it over, not a Wardic element there.
702
+ */
703
+ // ADR-0044, decision 6.
704
+ export const find = (element) => Bool.match(Predicate.hasProperty(element, "getAnimations"), {
705
+ onFalse: () => Option.none(),
706
+ onTrue: () => Arr.findFirst(element.getAnimations(), isElementAppearAnimation),
707
+ });
708
+ /**
709
+ * A document's Appear animations by element, running or finished and filling: one `getAnimations()` for
710
+ * the page, for a Handoff of many elements at once, a Batch's members (#706). Each element's first: a
711
+ * member's Batch rule, or the one `find` gets.
712
+ */
713
+ // #706, Q3: measured at a Batch's 1,000 members in one list, Chromium's `Element.getAnimations()` cost
714
+ // about a whole document's each (5.6 s for every member; the document's, 5.6 ms); Firefox's, alike either way.
715
+ export const findAll = (doc) => {
716
+ const byElement = new Map();
717
+ if (Bool.not(Predicate.hasProperty(doc, "getAnimations")))
718
+ return byElement;
719
+ // Once a Handoff, over the page's animations: the first per element, as `find`'s.
720
+ Arr.forEach(Arr.filter(doc.getAnimations(), isAppearAnimation), (animation) => Option.map(Option.filter(targetOf(animation), (target) => Bool.not(byElement.has(target))), (target) => byElement.set(target, animation)));
721
+ return byElement;
722
+ };
723
+ /** Whether `animation` is `spec`'s: the rule the server sampled from the same spec. */
724
+ export const matches = (animation, spec) => Option.exists(nameOfAnimation(animation), (name) => name === nameOf(spec));
725
+ /**
726
+ * Whether `animation` is a Batch rule for a spec's `key`: its name starts with the key's prefix, so the
727
+ * server's transitions and reduced motion are the client's. Its members' values aren't checked (#706, Q9).
728
+ */
729
+ export const matchesBatch = (animation, key) => Option.exists(nameOfAnimation(animation), (name) => name.startsWith(batchPrefixOf(key)));
730
+ /** How far `animation` has got, in seconds since it started (its delay included): 0 before it has. */
731
+ export const elapsedOf = (animation) => Option.match(Option.filter(Option.fromNullishOr(animation.currentTime), Predicate.isNumber), {
732
+ onNone: () => 0,
733
+ onSome: (ms) => Math.max(0, ms / 1000),
734
+ });
735
+ /** The delay `animation` started after, in seconds: what its element's `animation-delay` holds. */
736
+ export const delayOf = (animation) => Option.match(Option.filter(Option.fromNullishOr(animation.effect), (effect) => Predicate.isNotUndefined(effect.getTiming)), {
737
+ onNone: () => 0,
738
+ onSome: (effect) => Option.getOrElse(Option.filter(Option.some(effect.getTiming().delay), Predicate.isNumber), () => 0) / 1000,
739
+ });
740
+ //# sourceMappingURL=appear.js.map