@wardic/dom 1.0.1 → 1.1.1

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 (289) hide show
  1. package/dist/Appear.d.ts +3 -2
  2. package/dist/Appear.d.ts.map +1 -1
  3. package/dist/Appear.js +4 -3
  4. package/dist/Appear.js.map +1 -1
  5. package/dist/DomProjectionSystem.js +3 -3
  6. package/dist/DomProjectionSystem.js.map +1 -1
  7. package/dist/FlushGate.d.ts +6 -6
  8. package/dist/FlushGate.d.ts.map +1 -1
  9. package/dist/FlushGate.js +11 -8
  10. package/dist/FlushGate.js.map +1 -1
  11. package/dist/ReorderController.js +3 -3
  12. package/dist/ReorderController.js.map +1 -1
  13. package/dist/Report.d.ts +1 -1
  14. package/dist/Report.d.ts.map +1 -1
  15. package/dist/Report.js +3 -2
  16. package/dist/Report.js.map +1 -1
  17. package/dist/Style.d.ts +2 -1
  18. package/dist/Style.d.ts.map +1 -1
  19. package/dist/Style.js +3 -1
  20. package/dist/Style.js.map +1 -1
  21. package/dist/TimelineValue.d.ts +18 -0
  22. package/dist/TimelineValue.d.ts.map +1 -0
  23. package/dist/TimelineValue.js +20 -0
  24. package/dist/TimelineValue.js.map +1 -0
  25. package/dist/index.d.ts +13 -5
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +10 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/internal/appear.d.ts +10 -4
  30. package/dist/internal/appear.d.ts.map +1 -1
  31. package/dist/internal/appear.js +18 -8
  32. package/dist/internal/appear.js.map +1 -1
  33. package/dist/internal/batch-handoff.d.ts +25 -0
  34. package/dist/internal/batch-handoff.d.ts.map +1 -0
  35. package/dist/internal/batch-handoff.js +64 -0
  36. package/dist/internal/batch-handoff.js.map +1 -0
  37. package/dist/internal/drag-defaults.js +4 -1
  38. package/dist/internal/drag-defaults.js.map +1 -1
  39. package/dist/internal/gate-environment.d.ts +4 -0
  40. package/dist/internal/gate-environment.d.ts.map +1 -0
  41. package/dist/internal/gate-environment.js +21 -0
  42. package/dist/internal/gate-environment.js.map +1 -0
  43. package/dist/internal/projection.d.ts.map +1 -1
  44. package/dist/internal/projection.js +22 -21
  45. package/dist/internal/projection.js.map +1 -1
  46. package/dist/internal/renderer.d.ts +13 -0
  47. package/dist/internal/renderer.d.ts.map +1 -1
  48. package/dist/internal/renderer.js +21 -0
  49. package/dist/internal/renderer.js.map +1 -1
  50. package/dist/internal/reorder.d.ts +2 -2
  51. package/dist/internal/reorder.d.ts.map +1 -1
  52. package/dist/internal/reorder.js +2 -2
  53. package/dist/internal/reorder.js.map +1 -1
  54. package/dist/internal/scroll.d.ts +17 -0
  55. package/dist/internal/scroll.d.ts.map +1 -1
  56. package/dist/internal/scroll.js +23 -15
  57. package/dist/internal/scroll.js.map +1 -1
  58. package/dist/internal/starting-style.d.ts +0 -83
  59. package/dist/internal/starting-style.d.ts.map +1 -1
  60. package/dist/internal/starting-style.js +16 -143
  61. package/dist/internal/starting-style.js.map +1 -1
  62. package/dist/internal/timeline.d.ts +56 -0
  63. package/dist/internal/timeline.d.ts.map +1 -0
  64. package/dist/internal/timeline.js +389 -0
  65. package/dist/internal/timeline.js.map +1 -0
  66. package/dist/unstable/AppearAnimations.d.ts +191 -0
  67. package/dist/unstable/AppearAnimations.d.ts.map +1 -0
  68. package/dist/unstable/AppearAnimations.js +561 -0
  69. package/dist/unstable/AppearAnimations.js.map +1 -0
  70. package/dist/unstable/BatchMembers.d.ts +513 -0
  71. package/dist/unstable/BatchMembers.d.ts.map +1 -0
  72. package/dist/unstable/BatchMembers.js +2490 -0
  73. package/dist/unstable/BatchMembers.js.map +1 -0
  74. package/dist/unstable/DomValues.d.ts +25 -0
  75. package/dist/unstable/DomValues.d.ts.map +1 -0
  76. package/dist/unstable/DomValues.js +45 -0
  77. package/dist/unstable/DomValues.js.map +1 -0
  78. package/dist/unstable/DragConstraints.d.ts +48 -0
  79. package/dist/unstable/DragConstraints.d.ts.map +1 -0
  80. package/dist/unstable/DragConstraints.js +49 -0
  81. package/dist/unstable/DragConstraints.js.map +1 -0
  82. package/dist/unstable/DragControls.d.ts +50 -0
  83. package/dist/unstable/DragControls.d.ts.map +1 -0
  84. package/dist/unstable/DragControls.js +55 -0
  85. package/dist/unstable/DragControls.js.map +1 -0
  86. package/dist/unstable/DragDefaults.d.ts +34 -0
  87. package/dist/unstable/DragDefaults.d.ts.map +1 -0
  88. package/dist/unstable/DragDefaults.js +47 -0
  89. package/dist/unstable/DragDefaults.js.map +1 -0
  90. package/dist/unstable/DragTrack.d.ts +236 -0
  91. package/dist/unstable/DragTrack.d.ts.map +1 -0
  92. package/dist/unstable/DragTrack.js +646 -0
  93. package/dist/unstable/DragTrack.js.map +1 -0
  94. package/dist/unstable/DragTransition.d.ts +22 -0
  95. package/dist/unstable/DragTransition.d.ts.map +1 -0
  96. package/dist/unstable/DragTransition.js +31 -0
  97. package/dist/unstable/DragTransition.js.map +1 -0
  98. package/dist/unstable/ElementSetup.d.ts +144 -0
  99. package/dist/unstable/ElementSetup.d.ts.map +1 -0
  100. package/dist/unstable/ElementSetup.js +297 -0
  101. package/dist/unstable/ElementSetup.js.map +1 -0
  102. package/dist/unstable/Feature.d.ts +221 -0
  103. package/dist/unstable/Feature.d.ts.map +1 -0
  104. package/dist/unstable/Feature.js +281 -0
  105. package/dist/unstable/Feature.js.map +1 -0
  106. package/dist/unstable/GestureFeatures.d.ts +30 -0
  107. package/dist/unstable/GestureFeatures.d.ts.map +1 -0
  108. package/dist/unstable/GestureFeatures.js +32 -0
  109. package/dist/unstable/GestureFeatures.js.map +1 -0
  110. package/dist/unstable/GestureInfo.d.ts +61 -0
  111. package/dist/unstable/GestureInfo.d.ts.map +1 -0
  112. package/dist/unstable/GestureInfo.js +23 -0
  113. package/dist/unstable/GestureInfo.js.map +1 -0
  114. package/dist/unstable/Imperative.d.ts +214 -0
  115. package/dist/unstable/Imperative.d.ts.map +1 -0
  116. package/dist/unstable/Imperative.js +768 -0
  117. package/dist/unstable/Imperative.js.map +1 -0
  118. package/dist/unstable/Instant.d.ts +46 -0
  119. package/dist/unstable/Instant.d.ts.map +1 -0
  120. package/dist/unstable/Instant.js +49 -0
  121. package/dist/unstable/Instant.js.map +1 -0
  122. package/dist/unstable/LayoutGroup.d.ts +14 -0
  123. package/dist/unstable/LayoutGroup.d.ts.map +1 -0
  124. package/dist/unstable/LayoutGroup.js +31 -0
  125. package/dist/unstable/LayoutGroup.js.map +1 -0
  126. package/dist/unstable/LayoutMember.d.ts +127 -0
  127. package/dist/unstable/LayoutMember.d.ts.map +1 -0
  128. package/dist/unstable/LayoutMember.js +176 -0
  129. package/dist/unstable/LayoutMember.js.map +1 -0
  130. package/dist/unstable/LiveStyle.d.ts +171 -0
  131. package/dist/unstable/LiveStyle.d.ts.map +1 -0
  132. package/dist/unstable/LiveStyle.js +329 -0
  133. package/dist/unstable/LiveStyle.js.map +1 -0
  134. package/dist/unstable/MemberHold.d.ts +3 -0
  135. package/dist/unstable/MemberHold.d.ts.map +1 -0
  136. package/dist/unstable/MemberHold.js +223 -0
  137. package/dist/unstable/MemberHold.js.map +1 -0
  138. package/dist/unstable/OwnerScope.d.ts +16 -0
  139. package/dist/unstable/OwnerScope.d.ts.map +1 -0
  140. package/dist/unstable/OwnerScope.js +35 -0
  141. package/dist/unstable/OwnerScope.js.map +1 -0
  142. package/dist/unstable/PresenceController.d.ts +128 -0
  143. package/dist/unstable/PresenceController.d.ts.map +1 -0
  144. package/dist/unstable/PresenceController.js +1427 -0
  145. package/dist/unstable/PresenceController.js.map +1 -0
  146. package/dist/unstable/Press.d.ts +26 -0
  147. package/dist/unstable/Press.d.ts.map +1 -0
  148. package/dist/unstable/Press.js +19 -0
  149. package/dist/unstable/Press.js.map +1 -0
  150. package/dist/unstable/ServerInterpolators.d.ts +17 -0
  151. package/dist/unstable/ServerInterpolators.d.ts.map +1 -0
  152. package/dist/unstable/ServerInterpolators.js +20 -0
  153. package/dist/unstable/ServerInterpolators.js.map +1 -0
  154. package/dist/unstable/WardConfig.d.ts +567 -0
  155. package/dist/unstable/WardConfig.d.ts.map +1 -0
  156. package/dist/unstable/WardConfig.js +2 -0
  157. package/dist/unstable/WardConfig.js.map +1 -0
  158. package/dist/unstable/features/All.d.ts +24 -0
  159. package/dist/unstable/features/All.d.ts.map +1 -0
  160. package/dist/unstable/features/All.js +20 -0
  161. package/dist/unstable/features/All.js.map +1 -0
  162. package/dist/unstable/features/Colors.d.ts +12 -0
  163. package/dist/unstable/features/Colors.d.ts.map +1 -0
  164. package/dist/unstable/features/Colors.js +38 -0
  165. package/dist/unstable/features/Colors.js.map +1 -0
  166. package/dist/unstable/features/DomAnimation.d.ts +16 -0
  167. package/dist/unstable/features/DomAnimation.d.ts.map +1 -0
  168. package/dist/unstable/features/DomAnimation.js +19 -0
  169. package/dist/unstable/features/DomAnimation.js.map +1 -0
  170. package/dist/unstable/features/DomMax.d.ts +12 -0
  171. package/dist/unstable/features/DomMax.d.ts.map +1 -0
  172. package/dist/unstable/features/DomMax.js +14 -0
  173. package/dist/unstable/features/DomMax.js.map +1 -0
  174. package/dist/unstable/features/Drag.d.ts +5 -0
  175. package/dist/unstable/features/Drag.d.ts.map +1 -0
  176. package/dist/unstable/features/Drag.js +32 -0
  177. package/dist/unstable/features/Drag.js.map +1 -0
  178. package/dist/unstable/features/Focus.d.ts +5 -0
  179. package/dist/unstable/features/Focus.d.ts.map +1 -0
  180. package/dist/unstable/features/Focus.js +20 -0
  181. package/dist/unstable/features/Focus.js.map +1 -0
  182. package/dist/unstable/features/Hover.d.ts +5 -0
  183. package/dist/unstable/features/Hover.d.ts.map +1 -0
  184. package/dist/unstable/features/Hover.js +20 -0
  185. package/dist/unstable/features/Hover.js.map +1 -0
  186. package/dist/unstable/features/InView.d.ts +5 -0
  187. package/dist/unstable/features/InView.d.ts.map +1 -0
  188. package/dist/unstable/features/InView.js +20 -0
  189. package/dist/unstable/features/InView.js.map +1 -0
  190. package/dist/unstable/features/Input.d.ts +28 -0
  191. package/dist/unstable/features/Input.d.ts.map +1 -0
  192. package/dist/unstable/features/Input.js +31 -0
  193. package/dist/unstable/features/Input.js.map +1 -0
  194. package/dist/unstable/features/Keys.d.ts +95 -0
  195. package/dist/unstable/features/Keys.d.ts.map +1 -0
  196. package/dist/unstable/features/Keys.js +44 -0
  197. package/dist/unstable/features/Keys.js.map +1 -0
  198. package/dist/unstable/features/Layout.d.ts +43 -0
  199. package/dist/unstable/features/Layout.d.ts.map +1 -0
  200. package/dist/unstable/features/Layout.js +44 -0
  201. package/dist/unstable/features/Layout.js.map +1 -0
  202. package/dist/unstable/features/Pan.d.ts +5 -0
  203. package/dist/unstable/features/Pan.d.ts.map +1 -0
  204. package/dist/unstable/features/Pan.js +20 -0
  205. package/dist/unstable/features/Pan.js.map +1 -0
  206. package/dist/unstable/features/Press.d.ts +13 -0
  207. package/dist/unstable/features/Press.d.ts.map +1 -0
  208. package/dist/unstable/features/Press.js +10 -0
  209. package/dist/unstable/features/Press.js.map +1 -0
  210. package/dist/unstable/features/Scroll.d.ts +20 -0
  211. package/dist/unstable/features/Scroll.d.ts.map +1 -0
  212. package/dist/unstable/features/Scroll.js +34 -0
  213. package/dist/unstable/features/Scroll.js.map +1 -0
  214. package/dist/unstable/features/TimelineKeys.d.ts +7 -0
  215. package/dist/unstable/features/TimelineKeys.d.ts.map +1 -0
  216. package/dist/unstable/features/TimelineKeys.js +103 -0
  217. package/dist/unstable/features/TimelineKeys.js.map +1 -0
  218. package/package.json +4 -3
  219. package/src/Appear.ts +4 -2
  220. package/src/DomProjectionSystem.ts +3 -3
  221. package/src/FlushGate.ts +15 -12
  222. package/src/ReorderController.ts +3 -3
  223. package/src/Report.ts +3 -7
  224. package/src/Style.ts +4 -1
  225. package/src/TimelineValue.ts +19 -0
  226. package/src/index.ts +15 -5
  227. package/src/internal/appear.ts +20 -8
  228. package/src/internal/batch-handoff.ts +75 -0
  229. package/src/internal/drag-defaults.ts +4 -4
  230. package/src/internal/gate-environment.ts +21 -0
  231. package/src/internal/projection.ts +22 -21
  232. package/src/internal/renderer.ts +22 -0
  233. package/src/internal/reorder.ts +4 -4
  234. package/src/internal/scroll.ts +32 -15
  235. package/src/internal/starting-style.ts +5 -204
  236. package/src/internal/timeline.ts +480 -0
  237. package/src/unstable/AppearAnimations.ts +837 -0
  238. package/src/unstable/BatchMembers.ts +3085 -0
  239. package/src/unstable/DomValues.ts +53 -0
  240. package/src/unstable/DragConstraints.ts +107 -0
  241. package/src/unstable/DragControls.ts +98 -0
  242. package/src/unstable/DragDefaults.ts +57 -0
  243. package/src/unstable/DragTrack.ts +959 -0
  244. package/src/unstable/DragTransition.ts +46 -0
  245. package/src/unstable/ElementSetup.ts +411 -0
  246. package/src/unstable/Feature.ts +494 -0
  247. package/src/unstable/GestureFeatures.ts +38 -0
  248. package/src/unstable/GestureInfo.ts +85 -0
  249. package/src/unstable/Imperative.ts +1037 -0
  250. package/src/unstable/Instant.ts +93 -0
  251. package/src/unstable/LayoutGroup.ts +36 -0
  252. package/src/unstable/LayoutMember.ts +319 -0
  253. package/src/unstable/LiveStyle.ts +497 -0
  254. package/src/unstable/MemberHold.ts +211 -0
  255. package/src/unstable/OwnerScope.ts +35 -0
  256. package/src/unstable/PresenceController.ts +1747 -0
  257. package/src/unstable/Press.ts +43 -0
  258. package/src/unstable/ServerInterpolators.ts +39 -0
  259. package/src/unstable/WardConfig.ts +704 -0
  260. package/src/unstable/features/All.ts +39 -0
  261. package/src/unstable/features/Colors.ts +40 -0
  262. package/src/unstable/features/DomAnimation.ts +19 -0
  263. package/src/unstable/features/DomMax.ts +14 -0
  264. package/src/unstable/features/Drag.ts +34 -0
  265. package/src/unstable/features/Focus.ts +21 -0
  266. package/src/unstable/features/Hover.ts +21 -0
  267. package/src/unstable/features/InView.ts +21 -0
  268. package/src/unstable/features/Input.ts +37 -0
  269. package/src/unstable/features/Keys.ts +124 -0
  270. package/src/unstable/features/Layout.ts +75 -0
  271. package/src/unstable/features/Pan.ts +21 -0
  272. package/src/unstable/features/Press.ts +21 -0
  273. package/src/unstable/features/Scroll.ts +35 -0
  274. package/src/unstable/features/TimelineKeys.ts +115 -0
  275. package/dist/internal/gate.d.ts +0 -188
  276. package/dist/internal/gate.d.ts.map +0 -1
  277. package/dist/internal/gate.js +0 -458
  278. package/dist/internal/gate.js.map +0 -1
  279. package/dist/internal/report.d.ts +0 -30
  280. package/dist/internal/report.d.ts.map +0 -1
  281. package/dist/internal/report.js +0 -60
  282. package/dist/internal/report.js.map +0 -1
  283. package/dist/internal/runner.d.ts +0 -21
  284. package/dist/internal/runner.d.ts.map +0 -1
  285. package/dist/internal/runner.js +0 -48
  286. package/dist/internal/runner.js.map +0 -1
  287. package/src/internal/gate.ts +0 -598
  288. package/src/internal/report.ts +0 -69
  289. package/src/internal/runner.ts +0 -64
@@ -0,0 +1,837 @@
1
+ /**
2
+ * Appear animations as a DOM binding runs them (#48, ADR-0044): a server-rendered mount animation played
3
+ * in CSS from first paint, and taken over at mount (the **Handoff**).
4
+ *
5
+ * - **Both sides** describe an element's mount animation the same way ({@link AppearHandoff.MountAnimation}): its
6
+ * starting values, its targets, its own transition and whether motion is reduced. The rule's name
7
+ * is the hash of that description ({@link keyOf}), so the client tells a Handoff it can continue
8
+ * from one it can't.
9
+ * - **On a server** the provider holds one render's {@link ServerAppear}. Each element that
10
+ * qualifies takes a slot (its inline `animation: var(--wardic-aN)`); a Variant child joins its
11
+ * parent's group, in render order. Once the render is done, `css()` works out each one's timing
12
+ * (its stagger, its `when`) and writes the head's `<style>`.
13
+ * - **At mount** the spine finds the element's animation ({@link handoffOf}), starts its first legs
14
+ * that far in, and removes it in its first commit.
15
+ *
16
+ * Unstable, for Wardic's own packages: public, with no semver promise.
17
+ *
18
+ * @module
19
+ */
20
+ // Unstable: ADR-0071, decision 5. #672 (PR5-Q2): solid's `appear.ts` but what the spine reads (core's
21
+ // `AppearHandoff`), moved to dom for every DOM binding: its server sampler, the key that matches a
22
+ // server's to a client's, and the DOM's Handoff reads.
23
+ import type * as DefaultTransition from "@wardic/core/DefaultTransition"
24
+ import * as Easing from "@wardic/core/Easing"
25
+ import type * as Frame from "@wardic/core/Frame"
26
+ import * as Machine from "@wardic/core/Machine"
27
+ import type * as InterpolatorRegistry from "@wardic/core/InterpolatorRegistry"
28
+ import type * as ReducedMotion from "@wardic/core/ReducedMotion"
29
+ import type * as Values from "@wardic/core/Values"
30
+ import * as Appear from "../Appear.ts"
31
+ import type * as DomRenderer from "../DomRenderer.ts"
32
+ import * as DomDefaultTransition from "../DomDefaultTransition.ts"
33
+ import * as DomPositionalKeys from "../DomPositionalKeys.ts"
34
+ import * as OwnValues from "../OwnValues.ts"
35
+ import * as Arr from "effect/Array"
36
+ import * as Bool from "effect/Boolean"
37
+ import * as Effect from "effect/Effect"
38
+ import { identity } from "effect/Function"
39
+ import * as Match from "effect/Match"
40
+ import * as Option from "effect/Option"
41
+ import * as Order from "effect/Order"
42
+ import * as Predicate from "effect/Predicate"
43
+ import * as Rec from "effect/Record"
44
+ import * as Result from "effect/Result"
45
+ import * as UndefinedOr from "effect/UndefinedOr"
46
+ import * as AppearHandoff from "@wardic/core/unstable/AppearHandoff"
47
+ import type * as WardConfig from "./WardConfig.ts"
48
+ import * as RetargetLegs from "@wardic/core/unstable/RetargetLegs"
49
+ import * as ServerInterpolators from "./ServerInterpolators.ts"
50
+ import type * as VariantTarget from "@wardic/core/unstable/VariantTarget"
51
+ import * as VariantTree from "@wardic/core/unstable/VariantTree"
52
+
53
+ // --- The mount animation, on both sides -------------------------------------------------------
54
+
55
+ /** What stands in for a function with no easing name: canonical text holding it is no key. */
56
+ const UNNAMED = "\u0000unnamed"
57
+
58
+ /**
59
+ * A value as canonical text: JSON with each object's keys in order, `undefined`s left out, and a
60
+ * function by its easing name (`Easing.nameOf`), else {@link UNNAMED}. Written directly, its cases
61
+ * built once at module load: it runs per element (#69's PR 2).
62
+ */
63
+ const textOf: (value: unknown) => string = /*#__PURE__*/ Match.type<unknown>().pipe(
64
+ Match.when(Predicate.isFunction, (fn) => Option.match(Easing.nameOf(fn as Easing.Easing), { onNone: () => UNNAMED, onSome: (easing) => `{"easing":${JSON.stringify(easing)}}` })),
65
+ Match.when(Arr.isArray, (items) => `[${Arr.map(items as ReadonlyArray<unknown>, (item) => textOf(item)).join(",")}]`),
66
+ Match.when(Predicate.isObject, (record) => {
67
+ const keys = Arr.sort(Arr.filter(Object.keys(record), (key) => Predicate.isNotUndefined((record as Record<string, unknown>)[key])), Order.String)
68
+ return `{${Arr.map(keys, (key) => `${JSON.stringify(key)}:${textOf((record as Record<string, unknown>)[key])}`).join(",")}}`
69
+ }),
70
+ Match.orElse((v) => String(JSON.stringify(v))),
71
+ )
72
+
73
+ /** Where a Path's key samples it (#438): nine points, its ends among them. */
74
+ const PATH_SAMPLES = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] as const
75
+
76
+ /** An axis's number in `values`, its identity 0 when it has none (#438), as the leg reads it on a server. */
77
+ const axisIn = (values: Values.Values, key: "x" | "y"): number => UndefinedOr.match(values[key], { onUndefined: () => 0, onDefined: (v) => Number(v) })
78
+
79
+ /**
80
+ * A mount animation's transition as its key holds it: a Path (#438), a function, as its samples
81
+ * between the mount's ends, so two paths key apart and one path keys the same each time. Sampling it
82
+ * again is safe: an arc's memory of its side changes only with the way it travels.
83
+ */
84
+ const keyedTransitionOf = (m: AppearHandoff.MountAnimation): unknown =>
85
+ UndefinedOr.match(m.transition, {
86
+ onUndefined: () => null,
87
+ onDefined: (t: WardConfig.WardicTransition) =>
88
+ UndefinedOr.match(t.path, {
89
+ onUndefined: () => t,
90
+ onDefined: (path) => {
91
+ const from = { x: axisIn(m.from, "x"), y: axisIn(m.from, "y") }
92
+ const at = path(from, { x: UndefinedOr.match(m.to.x, { onUndefined: () => from.x, onDefined: Number }), y: UndefinedOr.match(m.to.y, { onUndefined: () => from.y, onDefined: Number }) })
93
+ return { ...t, path: Arr.map(PATH_SAMPLES, (p) => at(p)) }
94
+ },
95
+ }),
96
+ })
97
+
98
+ /** A value as canonical text; `None` when a function in it has no easing name. */
99
+ const canonical = (value: unknown): Option.Option<string> => Option.filter(Option.some(textOf(value)), (text) => Bool.not(text.includes(UNNAMED)))
100
+
101
+ /** Each mount animation's canonical starts, targets and transition, by its `from`: both its plays share one. */
102
+ // Module state (#460, Q7): a cache held weakly by the object it's for, so it goes with it.
103
+ const baseKeys = /*#__PURE__*/ new WeakMap<Values.Values, Option.Option<string>>()
104
+
105
+ /**
106
+ * The mount animation's key: its starts, targets and transition as one canonical text, and whether
107
+ * motion is reduced. `None` when the transition holds a function with no easing name
108
+ * (`Easing.nameOf`): the server can't tell it from another, so the element keeps its Starting style.
109
+ */
110
+ export const keyOf = (m: AppearHandoff.MountAnimation): Option.Option<string> => {
111
+ const base = Option.getOrElse(Option.fromUndefinedOr(baseKeys.get(m.from)), () => {
112
+ const computed = canonical({ from: m.from, to: m.to, transition: keyedTransitionOf(m), stops: m.stops })
113
+ baseKeys.set(m.from, computed)
114
+ return computed
115
+ })
116
+ // A skipped one's (#468) named apart: an unskipped one's name is as it was.
117
+ return Option.map(base, (text) => Bool.match(m.skipped === true, { onTrue: () => `${text}|skipped`, onFalse: () => `${text}|reduced:${m.reduced}` }))
118
+ }
119
+
120
+ /**
121
+ * A Batch's entrance's key (#706, Q9): its keys and each one's transition as a member's change runs them,
122
+ * as canonical text, and whether motion is reduced, or the change is skipped (#468). The server's rule
123
+ * group's, and what a client checks a member's Appear animation against. `None` when a transition holds
124
+ * a function with no easing name: the Batch waits for the JavaScript (Q4).
125
+ */
126
+ export const batchKeyOf = (keys: ReadonlyArray<string>, transitions: ReadonlyArray<unknown>, reduced: boolean, skipped: boolean): Option.Option<string> =>
127
+ Option.map(canonical({ keys, transitions }), (text) => Bool.match(skipped, { onTrue: () => `${text}|skipped`, onFalse: () => `${text}|reduced:${reduced}` }))
128
+
129
+ /** Whether a mount animation plays for ever: its transition repeats for ever, and it isn't skipped (#468), which lands it. */
130
+ const playsForever = (m: AppearHandoff.MountAnimation): boolean => Bool.and(m.skipped !== true, AppearHandoff.repeatsForever(m.transition))
131
+
132
+ /**
133
+ * The transition a server samples: as given, but for one that repeats for ever, two runs and the
134
+ * delay that follows them, with no delay before (one cycle of the CSS, played `infinite`). Two
135
+ * runs, so a cycle is exact for every `repeatType`, `reverse` and `mirror` included.
136
+ */
137
+ const sampledTransition = (transition: WardConfig.WardicTransition | undefined): WardConfig.WardicTransition | undefined =>
138
+ Bool.match(AppearHandoff.repeatsForever(transition), {
139
+ onTrue: () => ({ ...transition, delay: 0, repeat: 1 }) as WardConfig.WardicTransition,
140
+ onFalse: () => transition,
141
+ })
142
+
143
+ /**
144
+ * One machine of a Retarget's legs, run together: each step steps every leg not yet settled, and
145
+ * merges their values; it settles with the last. What a server samples. Built with the DOM's
146
+ * Interpolators (a server projects with the DOM's `project`, ADR-0021 decision 2).
147
+ */
148
+ const together = (legs: ReadonlyArray<RetargetLegs.Leg>): Machine.Machine<Frame.Frame<Values.Values>> => {
149
+ const machines = Effect.runSync(
150
+ ServerInterpolators.withServerInterpolators(Effect.all(Arr.map(legs, (leg): Effect.Effect<Machine.Machine<Frame.Frame<unknown>>, never, InterpolatorRegistry.InterpolatorRegistry> => machineOfLeg(leg)))),
151
+ )
152
+ return Machine.make({
153
+ settles: true,
154
+ span: { name: "wardic.appear", attributes: { legs: legs.length } },
155
+ start: () => {
156
+ const runs = Arr.map(machines, (machine, i) => ({ step: machine.start(), key: keyOfLeg(legs[i] as RetargetLegs.Leg), last: Option.none<Frame.Frame<unknown>>() }))
157
+ return (dt) => {
158
+ const value: Record<string, number | string> = {}
159
+ const done = Arr.reduce(runs, true, (all, run) => {
160
+ const frame = Option.getOrElse(Option.filter(run.last, (last) => last.done), () => run.step(dt))
161
+ run.last = Option.some(frame)
162
+ Option.match(run.key, {
163
+ onNone: () => Object.assign(value, frame.value as Values.Values),
164
+ onSome: (key) => Object.assign(value, { [key]: frame.value as number }),
165
+ })
166
+ return Bool.and(all, frame.done)
167
+ })
168
+ return { value, done }
169
+ }
170
+ },
171
+ })
172
+ }
173
+
174
+ /** A leg's machine, built: a Blend's through the Interpolators `together` provides. */
175
+ const machineOfLeg = (leg: RetargetLegs.Leg): Effect.Effect<Machine.Machine<Frame.Frame<unknown>>, never, InterpolatorRegistry.InterpolatorRegistry> =>
176
+ Bool.match(leg._tag === "Blend", {
177
+ onTrue: () => (leg as Extract<RetargetLegs.Leg, { _tag: "Blend" }>).machine(),
178
+ onFalse: () => Effect.sync(() => (leg as Exclude<RetargetLegs.Leg, { _tag: "Blend" }>).machine() as Machine.Machine<Frame.Frame<unknown>>),
179
+ })
180
+
181
+ /** The key a Follow leg's single value is: its own. */
182
+ const keyOfLeg = (leg: RetargetLegs.Leg): Option.Option<string> =>
183
+ Bool.match(leg._tag === "Follow", { onTrue: () => Option.some((leg as Extract<RetargetLegs.Leg, { _tag: "Follow" }>).key), onFalse: () => Option.none() })
184
+
185
+ /** The DOM's Positional keys, which a server's reduced rule snaps (ADR-0029, ADR-0036). */
186
+ const DOM_POSITIONAL: ReducedMotion.PositionalKeys["Service"] = { isPositional: DomPositionalKeys.isPositional }
187
+
188
+ /** The DOM's Default transition, which a key with no transition defined samples as the client runs it (ADR-0051). */
189
+ const DOM_DEFAULTS: DefaultTransition.DefaultTransition["Service"] = { transitionFor: DomDefaultTransition.transitionFor, keyframes: DomDefaultTransition.keyframes }
190
+
191
+ /**
192
+ * Whether a value's own transition drives one of its keys while anything repeats for ever (#301): one
193
+ * CSS cycle can't hold a key that stops beside one that repeats, nor two cycles' lengths. With every
194
+ * key on the transition's own fields (a `layout` entry alone), it plays as before.
195
+ */
196
+ const foreverByValue = (m: AppearHandoff.MountAnimation): boolean => {
197
+ const entries = RetargetLegs.entriesOf(m.transition)
198
+ if (Predicate.isUndefined(entries)) return false
199
+ const runsOn = Arr.map(Rec.keys(m.to), (key) => RetargetLegs.transitionForKey(m.transition, key))
200
+ if (Arr.every(runsOn, (transition) => transition === entries.own)) return false
201
+ return Bool.or(AppearHandoff.repeatsForever(m.transition), Arr.some(runsOn, AppearHandoff.repeatsForever))
202
+ }
203
+
204
+ /** A mount animation's spec for the DOM's sampler, or why it has none. */
205
+ export const specOf = (m: AppearHandoff.MountAnimation): Result.Result<Appear.Spec, string> =>
206
+ Option.match(keyOf(m), {
207
+ onNone: () => Result.fail("its transition holds a function with no easing name"),
208
+ onSome: (key) => {
209
+ const skipped = m.skipped === true
210
+ if (Bool.and(Bool.not(skipped), foreverByValue(m))) return Result.fail("a value's own transition repeats for ever beside another")
211
+ const forever = playsForever(m)
212
+ const transition = Bool.match(skipped, { onTrue: () => m.transition, onFalse: () => sampledTransition(m.transition) })
213
+ const repeatDelay = UndefinedOr.match(m.transition, { onUndefined: () => 0, onDefined: (t) => Option.getOrElse(Option.fromUndefinedOr((t as Machine.AnimateOptions).repeatDelay), () => 0) })
214
+ return Result.succeed({
215
+ key,
216
+ tag: m.tag,
217
+ infinite: forever,
218
+ projected: m.layout,
219
+ template: m.template,
220
+ // Skipped (#468): every key's snap, landing on its first frame, a rule of 0 s.
221
+ machine: () =>
222
+ Bool.match(forever, {
223
+ onTrue: () => Machine.holdAfter(together(RetargetLegs.legsOf(m.from, m.to, transition, m.reduced, skipped, DOM_POSITIONAL, DOM_DEFAULTS, RetargetLegs.NO_VELOCITY, undefined, m.stops)), repeatDelay),
224
+ onFalse: () => together(RetargetLegs.legsOf(m.from, m.to, transition, m.reduced, skipped, DOM_POSITIONAL, DOM_DEFAULTS, RetargetLegs.NO_VELOCITY, undefined, m.stops)),
225
+ }),
226
+ })
227
+ },
228
+ })
229
+
230
+ /**
231
+ * Why a mount animation can't play before hydration, or `None` when it can (decision 4): a key
232
+ * starting from anything but `initial`, a value the DOM reads from the element (`auto`, `var()`),
233
+ * or a start that can't take its target's shape (a length pair in two units).
234
+ */
235
+ export const unplayable = (initial: Values.Values, to: Values.Values): Option.Option<string> =>
236
+ Arr.findFirst(Rec.toEntries(to), ([key, target]) =>
237
+ Option.match(Option.fromUndefinedOr(initial[key]), {
238
+ onNone: () => Option.some(`${key} starts from the element's own value (no initial)`),
239
+ onSome: (start) =>
240
+ Bool.match(Bool.or(readsElement(start), readsElement(target)), {
241
+ onTrue: () => Option.some(`${key} is a value the DOM reads from the element`),
242
+ onFalse: () =>
243
+ // A start that can't take its target's shape, a length in another unit among them (ADR-0024).
244
+ Bool.match(Option.isNone(OwnValues.valueLike(start, target)), {
245
+ onTrue: () => Option.some(`${key}'s start and target don't take one shape`),
246
+ onFalse: () => Option.none(),
247
+ }),
248
+ }),
249
+ }))
250
+
251
+ /** Whether a value is one the DOM reads from the element: `auto`, or a custom property. */
252
+ const readsElement = (value: number | string): boolean => Predicate.isString(value) && /\bauto\b|var\(/.test(value)
253
+
254
+ /** Whether an `initial` value, coerced to its target's shape, is that target: its key starts no leg (#448). */
255
+ const atTarget = (start: number | string | undefined, target: number | string): boolean =>
256
+ Option.exists(OwnValues.valueLike(start, target), (like) => like === target)
257
+
258
+ // --- The server --------------------------------------------------------------------------------
259
+
260
+ /** A variant parent's orchestration, on a server: its children in render order, its stagger and `when`. */
261
+ export interface AppearGroup {
262
+ readonly leader: Entry
263
+ readonly stagger: VariantTree.WardicStaggerConfig
264
+ readonly when: "beforeChildren" | "afterChildren" | undefined
265
+ readonly children: Array<Entry>
266
+ }
267
+
268
+ /** One element's place in a server render's Appear animations. */
269
+ export interface Entry {
270
+ /** Its mount animation per motion setting, or why it has none; `None` when nothing animates. */
271
+ readonly plays: { readonly normal: Option.Option<Result.Result<AppearHandoff.MountAnimation, string>>; readonly reduced: Option.Option<Result.Result<AppearHandoff.MountAnimation, string>> }
272
+ readonly slot: Option.Option<Appear.Slot>
273
+ /** The group it staggers in, as a Variant child. */
274
+ readonly group: Option.Option<AppearGroup>
275
+ /** Why it was ruled out after it rendered: its user style, read when `ward()` is called (ADR-0044, decision 4). */
276
+ readonly vetoes: Array<string>
277
+ /**
278
+ * Whether it follows the user's preference (`"user"`, #434): its reduced play goes under the head's
279
+ * media query. With `"always"` or `"never"` its plays are already that setting's.
280
+ */
281
+ readonly user: boolean
282
+ /** Whether it's skipped (#468): its rule lands on first paint, and its own stagger holds it back no more than its client does. */
283
+ readonly skipped: boolean
284
+ /** Its tag, and the keys its mount animates: what names it when the provider explains (#585). */
285
+ readonly tag: string | undefined
286
+ readonly to: Option.Option<Values.Values>
287
+ }
288
+
289
+ /** One server render's Appear animations: the provider's (ADR-0044, decisions 3 and 5). */
290
+ export interface ServerAppear {
291
+ /** The provider's reduced motion: an element's, unless its nearest `WardicConfig` sets its own (#434). */
292
+ readonly reducedMotion: ReducedMotion.Config
293
+ /**
294
+ * An element's entry, and its inline `animation` when it plays: its plays as its reduced motion has
295
+ * them, `setting` (its nearest `WardicConfig`'s, #434) else the provider's. A skipped one's (#468)
296
+ * are one play in both slots, whatever its reduced motion.
297
+ */
298
+ readonly enter: (
299
+ animation: { readonly normal: Option.Option<Result.Result<AppearHandoff.MountAnimation, string>>; readonly reduced: Option.Option<Result.Result<AppearHandoff.MountAnimation, string>> },
300
+ group: Option.Option<AppearGroup>,
301
+ setting: ReducedMotion.Config | undefined,
302
+ skipped: boolean,
303
+ /** Its tag and its targets at mount, which name it when the provider explains (#585). */
304
+ tag: string | undefined,
305
+ to: Option.Option<Values.Values>,
306
+ ) => {
307
+ readonly entry: Entry
308
+ readonly animation: Option.Option<string>
309
+ /**
310
+ * Entered after the shell was flushed, so in a chunk a stream sends later (#245), and no late
311
+ * element around it: the chunk's root, which puts the chunk's `<style>` after itself.
312
+ */
313
+ readonly chunkRoot: boolean
314
+ readonly late: boolean
315
+ }
316
+ /** A variant parent's group, its children to come. */
317
+ readonly group: (leader: Entry, transition: WardConfig.WardicTransition | undefined) => AppearGroup
318
+ /**
319
+ * The head's CSS, once the shell is done: every element entered so far, its timing worked out,
320
+ * and the rules. Called once, by the provider's `useAssets`: what enters after is late (#245).
321
+ */
322
+ readonly css: () => string
323
+ /** Render a late element's subtree: an element inside it isn't a chunk's root (#245). */
324
+ readonly within: <A>(late: boolean, render: () => A) => A
325
+ /**
326
+ * A late chunk's CSS (#245): the rules and timings of every element entered since the last
327
+ * write, those the head sent left out; "" for none. The Solid 2 binding hands it to `useHead`,
328
+ * which streams it with the chunk as a head patch (#209 PR 4a).
329
+ */
330
+ readonly chunkCss: () => string
331
+ /**
332
+ * A late chunk's `<style>` (#245), as server text: {@link chunkCss} in a `<style>`. The Solid 1
333
+ * binding's chunk root's thunk asks for it once the chunk has rendered.
334
+ */
335
+ readonly chunk: () => string
336
+ /** The nonce the page's Content Security Policy gives inline styles, which each `<style>` carries (#618, P1). */
337
+ readonly nonce: string | undefined
338
+ /**
339
+ * A Batch's rule group's slot (#706): `play`'s rule, and `reduced`'s under the media query when given;
340
+ * each member's style its own values, the slot and its delay. In the head's CSS, or a late chunk's.
341
+ */
342
+ readonly batch: (play: Appear.BatchKeyframes, reduced?: Appear.BatchKeyframes | undefined) => Appear.BatchSlot
343
+ /** Says why a Batch, or one of its members, named by `name`, waits for the JavaScript, when the provider explains (#585, #706). */
344
+ readonly waits: (name: string, reason: string) => void
345
+ }
346
+
347
+ /** No transition: no orchestration. */
348
+ const NO_TRANSITION: WardConfig.WardicTransition = {}
349
+
350
+ /** An element's reduced motion (#434): its nearest config's, else the provider's. */
351
+ const settingOr = (setting: ReducedMotion.Config | undefined, provider: ReducedMotion.Config): ReducedMotion.Config => {
352
+ if (Predicate.isNotUndefined(setting)) return setting
353
+ return provider
354
+ }
355
+
356
+ /**
357
+ * An element's plays under its reduced motion (#434): `"always"` plays its reduced one in both
358
+ * settings, `"never"` its normal one, and `"user"` each in its own, the reduced under the media query.
359
+ */
360
+ const playsUnder = (plays: Entry["plays"], setting: ReducedMotion.Config): Entry["plays"] => {
361
+ if (setting === "always") return { normal: plays.reduced, reduced: plays.reduced }
362
+ if (setting === "never") return { normal: plays.normal, reduced: plays.normal }
363
+ return plays
364
+ }
365
+
366
+ /** Whether an entry follows the user's preference (#434). */
367
+ const isUser = (entry: Entry): boolean => entry.user
368
+
369
+ /**
370
+ * What a provider's `appear` explains with (#585): with `"explain"`, a Warning for each element that
371
+ * waits for the JavaScript, logged as the render finds it with Effect's own logger, since a server
372
+ * builds no runtime from the app's `env`; nothing otherwise.
373
+ */
374
+ export const explainerOf = (appear: boolean | "explain" | undefined): ((message: string) => void) | undefined => {
375
+ if (appear !== "explain") return undefined
376
+ return (message) => Effect.runSync(Effect.logWarning(message))
377
+ }
378
+
379
+ /** An element as the provider's explanation names it (#585): its tag and the keys its mount animates. */
380
+ const nameOf = (entry: Entry): string => {
381
+ const element = UndefinedOr.match(entry.tag, { onUndefined: () => "an element", onDefined: (tag) => `<${tag}>` })
382
+ return Option.match(entry.to, { onNone: () => element, onSome: (to) => `${element} (${Rec.keys(to).join(", ")})` })
383
+ }
384
+
385
+ /**
386
+ * A server render's Appear animations, for a provider whose reduced motion is `reducedMotion`. With
387
+ * `explain` (the provider's `appear="explain"`, #585), it says why each element that doesn't play
388
+ * waits for the JavaScript, as it finds out; without it, nothing is kept or said.
389
+ */
390
+ export const serverAppear = (reducedMotion: ReducedMotion.Config, explain?: (message: string) => void, nonce?: string): ServerAppear => {
391
+ const sheet = Appear.sheet()
392
+ const entries: Array<Entry> = []
393
+ /** Says why what `name` names waits for the JavaScript, when the provider explains. */
394
+ const waitsNamed = (name: string, reason: string): void => {
395
+ if (Predicate.isNotUndefined(explain)) explain(`wardic.appear: ${name} waits for the JavaScript: ${reason}`)
396
+ }
397
+ /** Says why `entry` waits for the JavaScript, when the provider explains. */
398
+ const waits = (entry: Entry, reason: string): void => waitsNamed(nameOf(entry), reason)
399
+ // The shell is flushed once the head's CSS is asked for: what enters after is late (#245).
400
+ let flushed = false
401
+ // The entries written so far, and how deep the render is in late elements.
402
+ let written = 0
403
+ let lateDepth = 0
404
+ /** The entries since the last write, now written. */
405
+ const nextBatch = (): ReadonlyArray<Entry> => {
406
+ const batch = entries.slice(written)
407
+ written = entries.length
408
+ return batch
409
+ }
410
+ /** A batch's timing, each slot defined, and the sheet's CSS for them (decision 5). */
411
+ const write = (batch: ReadonlyArray<Entry>): string => {
412
+ // Each entry's plays are its own setting's (#434): the normal ones always, the reduced ones under
413
+ // the media query when an entry follows the user.
414
+ const resolve = (pick: "normal" | "reduced") => timings(batch, pick)
415
+ const normal = resolve("normal")
416
+ const reduced = Bool.match(Arr.some(batch, isUser), { onTrue: () => Option.some(resolve("reduced")), onFalse: () => Option.none<Timings>() })
417
+ const settings = Arr.prepend(Option.toArray(reduced), normal)
418
+ // Most renders write no SVG geometry: no group pass.
419
+ const supports = Bool.match(Arr.some(settings, (byEntry) => byEntry.geometry), {
420
+ onTrue: () => groupSupports(batch, settings),
421
+ onFalse: () => () => NO_SUPPORTS,
422
+ })
423
+ Arr.forEach(batch, (entry) =>
424
+ Option.map(entry.slot, (slot) => {
425
+ const play = UndefinedOr.getOrThrow(normal.get(entry))
426
+ const reducedPlay = Option.map(Option.filter(reduced, () => entry.user), (byEntry) => UndefinedOr.getOrThrow(byEntry.get(entry)))
427
+ const defined = Result.flatMap(play, (p) =>
428
+ Option.match(reducedPlay, {
429
+ onNone: () => slot.define(p, undefined, supports(entry)),
430
+ onSome: (r) => Result.flatMap(r, (rp) => slot.define(p, rp, supports(entry))),
431
+ }))
432
+ Result.match(defined, { onFailure: (reason) => waits(entry, reason), onSuccess: () => undefined })
433
+ }))
434
+ return sheet.css()
435
+ }
436
+ const plays = (animation: Entry["plays"]): boolean =>
437
+ Bool.or(Option.exists(animation.normal, Result.isSuccess), Option.exists(animation.reduced, Result.isSuccess))
438
+ const chunkCss = (): string => write(nextBatch())
439
+ return {
440
+ reducedMotion,
441
+ enter: (given, group, setting, skipped, tag, to) => {
442
+ // Skipped (#468): its one play in both slots, under no media query.
443
+ const own = Bool.match(skipped, { onTrue: (): ReducedMotion.Config => "never", onFalse: () => settingOr(setting, reducedMotion) })
444
+ const animation = playsUnder(given, own)
445
+ const slot = Option.liftPredicate(animation, plays).pipe(Option.map(() => sheet.slot()))
446
+ const entry: Entry = { plays: animation, slot, group, vetoes: [], user: own === "user", skipped, tag, to }
447
+ // Why it plays neither: its normal play's reason, its reduced one's when that differs (#585).
448
+ if (Predicate.isNotUndefined(explain)) {
449
+ const reasons = Arr.dedupe(Arr.flatMap([animation.normal, animation.reduced], (play) => Option.toArray(Option.flatMap(play, (p) => Result.getFailure(p)))))
450
+ Arr.forEach(reasons, (reason) => waits(entry, reason))
451
+ }
452
+ entries.push(entry)
453
+ Option.map(group, (g) => g.children.push(entry))
454
+ return { entry, animation: Option.map(slot, (s) => s.animation), late: flushed, chunkRoot: Bool.and(flushed, lateDepth === 0) }
455
+ },
456
+ within: (late, render) => {
457
+ // Per element on a server: a guard, no allocation.
458
+ if (Bool.not(late)) return render()
459
+ lateDepth++
460
+ try {
461
+ return render()
462
+ } finally {
463
+ lateDepth--
464
+ }
465
+ },
466
+ chunkCss,
467
+ chunk: () => Appear.chunkStyle(chunkCss(), nonce),
468
+ nonce,
469
+ batch: (play, reduced) => sheet.batch(play, reduced),
470
+ waits: waitsNamed,
471
+ group: (leader, transition) => {
472
+ const { staggerChildren = 0, delayChildren = 0, from = "first", staggerDirection = 1, when } = UndefinedOr.match(transition, {
473
+ onUndefined: () => NO_TRANSITION,
474
+ onDefined: (t: WardConfig.WardicTransition) => t,
475
+ })
476
+ return { leader, stagger: { amount: staggerChildren, delayChildren, from, direction: staggerDirection }, when, children: [] }
477
+ },
478
+ css: () => {
479
+ flushed = true
480
+ return write(nextBatch())
481
+ },
482
+ }
483
+ }
484
+
485
+ /**
486
+ * Each entry's play for one motion setting: its spec and its delay, or why it has none. A Variant
487
+ * child starts after its stagger (`delayChildren` plus its place, ADR-0007), and after its parent
488
+ * settles under `when: "beforeChildren"`; a parent under `"afterChildren"` starts once its last
489
+ * child settles. A start that depends on an element with no rule has none.
490
+ *
491
+ * Timed a batch at a time (#245): the shell's, then each late chunk's, whose CSS starts when the
492
+ * chunk lands. A late Variant child of a group led earlier is a fresh mount from then: its stagger
493
+ * is among that group's children in its batch, and it doesn't wait on the leader (decision 5 of
494
+ * *Amendment (#245)*). The shell's batch is every entry, so nothing changes for it.
495
+ */
496
+ const timings = (entries: ReadonlyArray<Entry>, pick: "normal" | "reduced"): Timings => {
497
+ const memo = new Map<Entry, Result.Result<{ readonly play: TimedPlay; readonly settled: number }, string>>()
498
+ let geometry = false
499
+ const inBatch = new Set(entries)
500
+ // Each group's children in this batch, once a group.
501
+ const batchChildren = new Map<AppearGroup, ReadonlyArray<Entry>>()
502
+ const childrenOf = (g: AppearGroup): ReadonlyArray<Entry> =>
503
+ Option.getOrElse(Option.fromUndefinedOr(batchChildren.get(g)), () => {
504
+ const children = Arr.filter(g.children, (child) => inBatch.has(child))
505
+ batchChildren.set(g, children)
506
+ return children
507
+ })
508
+ /** An entry's spec and rule, or why it has none; a missing play (nothing animates) is a rule of 0 s. */
509
+ const ruleOf = (entry: Entry): Result.Result<Option.Option<{ readonly spec: Appear.Spec; readonly rule: Appear.Keyframes }>, string> =>
510
+ Arr.match(entry.vetoes, {
511
+ onNonEmpty: (vetoes) => Result.fail(vetoes.join("; ")),
512
+ onEmpty: () => playOf(entry),
513
+ })
514
+ const playOf = (entry: Entry): Result.Result<Option.Option<{ readonly spec: Appear.Spec; readonly rule: Appear.Keyframes }>, string> =>
515
+ Option.match(entry.plays[pick], {
516
+ onNone: () => Result.succeed(Option.none()),
517
+ onSome: (animation) =>
518
+ Result.flatMap(Result.flatMap(animation, specOf), (spec) => Result.map(Appear.keyframes(spec), (rule) => Option.some({ spec, rule }))),
519
+ })
520
+ /** The seconds from first paint to when `entry` starts, and its play. */
521
+ const timingOf = (entry: Entry): Result.Result<{ readonly play: TimedPlay; readonly settled: number }, string> =>
522
+ Option.getOrElse(Option.fromUndefinedOr(memo.get(entry)), () => {
523
+ const computed = Result.flatMap(ruleOf(entry), (rule) =>
524
+ Result.map(startOf(entry), (start) => {
525
+ const spec = Option.match(rule, { onNone: () => undefined, onSome: (r) => r.spec })
526
+ // A forever-repeating rule is a cycle: its own delay plays before it, and it never settles.
527
+ const mount = Option.match(entry.plays[pick], { onNone: () => undefined, onSome: (p) => Result.match(p, { onFailure: () => undefined, onSuccess: identity }) })
528
+ const transition = UndefinedOr.map(mount, (m) => m.transition)
529
+ const forever = UndefinedOr.match(mount, { onUndefined: () => false, onDefined: playsForever })
530
+ const before = Bool.match(forever, { onTrue: () => AppearHandoff.ownDelayOf(transition), onFalse: () => 0 })
531
+ const settled = Option.match(rule, { onNone: () => 0, onSome: (r) => Bool.match(forever, { onTrue: () => Number.POSITIVE_INFINITY, onFalse: () => r.rule.settled }) })
532
+ const supports = Option.match(rule, { onNone: () => NO_SUPPORTS, onSome: (r) => r.rule.supports })
533
+ geometry = Bool.or(geometry, Arr.isReadonlyArrayNonEmpty(supports))
534
+ return { play: { spec: spec as Appear.Spec, delay: start + before, supports }, settled: start + before + settled }
535
+ }))
536
+ memo.set(entry, computed)
537
+ return computed
538
+ })
539
+ /** When `entry` starts: its stagger, after its parent under `beforeChildren`, after its children under `afterChildren`. */
540
+ const startOf = (entry: Entry): Result.Result<number, string> =>
541
+ Result.flatMap(afterParent(entry), (afterLeader) => Result.map(afterChildren(entry), (afterKids) => Math.max(afterLeader, afterKids) + ownStaggerOf(entry, childrenOf)))
542
+ // A leader written earlier started at first paint: a late child doesn't wait on it.
543
+ const afterParent = (entry: Entry): Result.Result<number, string> =>
544
+ Option.match(Option.filter(entry.group, (g) => Bool.and(g.when === "beforeChildren", inBatch.has(g.leader))), {
545
+ onNone: () => Result.succeed(0),
546
+ onSome: (g) =>
547
+ Result.flatMap(
548
+ Result.mapError(Result.map(timingOf(g.leader), (t) => t.settled), (reason) => `its parent has no rule (${reason})`),
549
+ (settled) => Bool.match(Number.isFinite(settled), { onTrue: () => Result.succeed(settled), onFalse: () => Result.fail("its parent never settles") }),
550
+ ),
551
+ })
552
+ const afterChildren = (entry: Entry): Result.Result<number, string> =>
553
+ Option.match(Option.fromUndefinedOr(groupsLed.get(entry)), {
554
+ onNone: () => Result.succeed(0),
555
+ onSome: (g) =>
556
+ Bool.match(g.when === "afterChildren", {
557
+ onFalse: () => Result.succeed(0),
558
+ onTrue: () =>
559
+ Result.mapError(
560
+ Result.map(Result.all(Arr.map(childrenOf(g), timingOf)), (kids) => Arr.reduce(kids, 0, (latest, t) => Math.max(latest, t.settled))),
561
+ (reason) => `a child has no rule (${reason})`,
562
+ ),
563
+ }),
564
+ })
565
+ const groupsLed = new Map<Entry, AppearGroup>()
566
+ Arr.forEach(entries, (entry) => Option.map(entry.group, (g) => groupsLed.set(g.leader, g)))
567
+ const plays = new Map(Arr.map(entries, (entry) => [entry, Result.flatMap(timingOf(entry), (t) => Bool.match(Predicate.isUndefined(t.play.spec), {
568
+ onTrue: () => Result.fail("nothing animates"),
569
+ onFalse: () => Result.succeed(t.play),
570
+ }))] as const))
571
+ return Object.assign(plays, { geometry })
572
+ }
573
+
574
+ /** Each entry's play for one motion setting, and whether any of their rules writes SVG geometry. */
575
+ type Timings = Map<Entry, Result.Result<TimedPlay, string>> & { readonly geometry: boolean }
576
+
577
+ /** An element's play, with the SVG geometry properties its rule writes (#245, `Appear.Keyframes.supports`). */
578
+ interface TimedPlay extends Appear.Play {
579
+ readonly supports: ReadonlyArray<string>
580
+ }
581
+
582
+ const NO_SUPPORTS: ReadonlyArray<string> = []
583
+
584
+ /**
585
+ * The SVG geometry properties each entry's orchestrated group writes, over every play (#245,
586
+ * `Appear.Keyframes.supports`): the whole tree a top leader orchestrates is defined under one
587
+ * `@supports`, so a browser without them keeps all of it at its Starting style, not part of it
588
+ * (decision 4: an element qualifies whole, and so does what it orchestrates). Per element on a
589
+ * server: a render whose rules write none (most) pays a look at each play.
590
+ */
591
+ const groupSupports = (
592
+ entries: ReadonlyArray<Entry>,
593
+ settings: ReadonlyArray<Map<Entry, Result.Result<TimedPlay, string>>>,
594
+ ): ((entry: Entry) => ReadonlyArray<string>) => {
595
+ /** The leader at the top of an entry's orchestration: itself, outside any group. */
596
+ const topOf = (entry: Entry): Entry => Option.match(entry.group, { onNone: () => entry, onSome: (g) => topOf(g.leader) })
597
+ /** What an entry's own rules write, over every play. */
598
+ const own = (entry: Entry): ReadonlyArray<string> =>
599
+ Arr.flatMap(settings, (byEntry) =>
600
+ Option.match(Option.fromUndefinedOr(byEntry.get(entry)), {
601
+ onNone: () => NO_SUPPORTS,
602
+ onSome: (play) => Result.match(play, { onFailure: () => NO_SUPPORTS, onSuccess: (p) => p.supports }),
603
+ }))
604
+ const byTop = new Map<Entry, ReadonlyArray<string>>()
605
+ Arr.forEach(entries, (entry) =>
606
+ Arr.match(own(entry), {
607
+ onEmpty: () => undefined,
608
+ onNonEmpty: (mine) => {
609
+ const top = topOf(entry)
610
+ byTop.set(top, Arr.appendAll(Option.getOrElse(Option.fromUndefinedOr(byTop.get(top)), () => NO_SUPPORTS), mine))
611
+ },
612
+ }))
613
+ return (entry) =>
614
+ Bool.match(byTop.size === 0, {
615
+ onTrue: () => NO_SUPPORTS,
616
+ onFalse: () => Option.getOrElse(Option.fromUndefinedOr(byTop.get(topOf(entry))), () => NO_SUPPORTS),
617
+ })
618
+ }
619
+
620
+ /** An entry's own stagger: none when it's skipped (#468), as its client's snap has no delay; its `when` waits still hold. */
621
+ const ownStaggerOf = (entry: Entry, childrenOf: (g: AppearGroup) => ReadonlyArray<Entry>): number => {
622
+ if (entry.skipped) return 0
623
+ return staggerOf(entry, childrenOf)
624
+ }
625
+
626
+ /**
627
+ * A Variant child's stagger: its parent's `delayChildren` plus its place (ADR-0007), as the client
628
+ * works it out, among the group's children in its batch (`childrenOf`, #245).
629
+ */
630
+ const staggerOf = (entry: Entry, childrenOf: (g: AppearGroup) => ReadonlyArray<Entry>): number =>
631
+ Option.match(entry.group, {
632
+ onNone: () => 0,
633
+ onSome: (g) => {
634
+ const children = childrenOf(g)
635
+ const n = children.length
636
+ const i = children.indexOf(entry)
637
+ return VariantTree.childDelayOf(g.stagger, i, n)
638
+ },
639
+ })
640
+
641
+ /** What the server knows of an element when it renders it. */
642
+ export interface ServerElement {
643
+ /** The element's own `appear` (the provider's is the render's {@link ServerAppear}). */
644
+ readonly appear: boolean | undefined
645
+ readonly tag: string | undefined
646
+ /** Its starting values: `initial`, an inherited `initial` name, or `animate` under `initial={false}`. */
647
+ readonly initial: Values.Values
648
+ /** Its targets at mount: `animate`, or an inherited variant name resolved against its `variants`; `None` with neither. */
649
+ readonly to: Option.Option<Values.Values>
650
+ /** Its targets' Keyframes (#429), each such key's value in `to` their last stop; `undefined` with none. */
651
+ readonly keyframes: VariantTarget.Keyframes | undefined
652
+ /** Whether its mount starts at its `animate` (#448, `startsQuiet`): nothing plays, its Keyframes included (#429). */
653
+ readonly quiet: boolean
654
+ /** Its own transition, else the one it inherits (ADR-0007). */
655
+ readonly transition: WardConfig.WardicTransition | undefined
656
+ /** Whether it's a layout node (`layout` or `layoutId`): drawn through its projection at rest (#245). */
657
+ readonly layout: boolean
658
+ /** Its **Transform template** (#443), when it has one. */
659
+ readonly template?: DomRenderer.TransformTemplate | undefined
660
+ /** The group it staggers in, as a Variant child: its parent's (`node.inherited`). */
661
+ readonly group: Option.Option<AppearGroup>
662
+ /** Whether it orchestrates its Variant children: it has variants of its own (ADR-0007). */
663
+ readonly leads: boolean
664
+ /** Its own transition, whose stagger and `when` its Variant children follow. */
665
+ readonly ownTransition: WardConfig.WardicTransition | undefined
666
+ /** Its nearest `WardicConfig`'s reduced motion (#434), over the provider's: `undefined` for none. */
667
+ readonly reducedMotion?: ReducedMotion.Config | undefined
668
+ /** Whether its nearest `WardicConfig` skips its animations (#468). Its transition's own `skipAnimations` counts too. */
669
+ readonly skipAnimations?: boolean | undefined
670
+ }
671
+
672
+ /**
673
+ * An element's entry in a server render's Appear animations: its inline `animation` when it plays
674
+ * one, and the group its Variant children join when it leads one.
675
+ */
676
+ export const enterServer = (
677
+ appear: ServerAppear,
678
+ el: ServerElement,
679
+ ): {
680
+ readonly animation: Option.Option<string>
681
+ readonly group: Option.Option<AppearGroup>
682
+ readonly veto: (reason: string) => void
683
+ /** Rendered after the shell (#245): in a late chunk, and that chunk's root when no late element is around it. */
684
+ readonly late: boolean
685
+ readonly chunkRoot: boolean
686
+ } => {
687
+ // Its starts and targets once, both plays sharing them (and so their key's text, `keyOf`). A key
688
+ // already at its target, coerced to its shape, is left out, as the client's first Retarget starts
689
+ // it no leg (#448); a Keyframes key never is, and starts at its first stop, unless the mount starts
690
+ // at its `animate`, when nothing plays (#429, Motion's).
691
+ const mount = Option.flatMap(el.to, (to) => {
692
+ const moving = Rec.filter(to, (target, key) =>
693
+ Bool.match(hasStops(el.keyframes, key), { onTrue: () => Bool.not(el.quiet), onFalse: () => Bool.not(atTarget(el.initial[key], target)) }))
694
+ return Bool.match(Rec.isEmptyRecord(moving), {
695
+ onTrue: () => Option.none(),
696
+ onFalse: () => Option.some(Result.map(playable(el, moving), (prepared): RetargetLegs.KeyframesStart & { readonly to: Values.Values } => startedOf(prepared, el.keyframes))),
697
+ })
698
+ })
699
+ // Skipped (#468): its config's, or its whole transition's own, as the client's legs read them.
700
+ const skipped = Bool.or(el.skipAnimations === true, UndefinedOr.match(el.transition, { onUndefined: () => false, onDefined: (t) => t.skipAnimations === true }))
701
+ const play = (reduced: boolean): Option.Option<Result.Result<AppearHandoff.MountAnimation, string>> =>
702
+ Option.map(mount, (prepared) =>
703
+ Result.map(prepared, ({ from, to, stops }): AppearHandoff.MountAnimation => ({
704
+ tag: el.tag,
705
+ from,
706
+ to,
707
+ transition: el.transition,
708
+ reduced,
709
+ layout: el.layout,
710
+ stops,
711
+ ...AppearHandoff.skippedField(skipped),
712
+ ...UndefinedOr.match(el.template, { onUndefined: () => ({}), onDefined: (template) => ({ template }) }),
713
+ })))
714
+ const plays = Bool.match(skipped, {
715
+ onTrue: () => {
716
+ const one = play(false)
717
+ return { normal: one, reduced: one }
718
+ },
719
+ onFalse: () => ({ normal: play(false), reduced: play(true) }),
720
+ })
721
+ const { entry, animation: inline, late, chunkRoot } = appear.enter(plays, el.group, el.reducedMotion, skipped, el.tag, el.to)
722
+ return {
723
+ late,
724
+ chunkRoot,
725
+ animation: inline,
726
+ group: Option.liftPredicate(entry, () => el.leads).pipe(Option.map((leader) => appear.group(leader, el.ownTransition))),
727
+ veto: (reason) => {
728
+ entry.vetoes.push(reason)
729
+ },
730
+ }
731
+ }
732
+
733
+ /** Whether `key` has Keyframes in `keyframes` (#429). */
734
+ const hasStops = (keyframes: VariantTarget.Keyframes | undefined, key: string): boolean => {
735
+ if (Predicate.isUndefined(keyframes)) return false
736
+ return Object.hasOwn(keyframes, key)
737
+ }
738
+
739
+ /** A mount's starts with its Keyframes resolved (#429, `keyframesFrom`), as the client's first Retarget resolves them. */
740
+ const startedOf = (prepared: { readonly from: Values.Values; readonly to: Values.Values }, keyframes: VariantTarget.Keyframes | undefined): RetargetLegs.KeyframesStart & { readonly to: Values.Values } =>
741
+ UndefinedOr.match(keyframes, {
742
+ onUndefined: () => ({ from: prepared.from, to: prepared.to, stops: undefined }),
743
+ onDefined: (byKey) => ({ ...RetargetLegs.keyframesFrom(prepared.from, prepared.to, byKey), to: prepared.to }),
744
+ })
745
+
746
+ /** An element's starts and targets, or why its mount animation can't play before hydration (decision 4). */
747
+ const playable = (el: ServerElement, to: Values.Values): Result.Result<{ readonly from: Values.Values; readonly to: Values.Values }, string> => playableMatch({ el, to })
748
+
749
+ /** {@link playable}'s cases, built once at module load: it runs per element (#69's PR 2). */
750
+ const playableMatch: (input: { readonly el: ServerElement; readonly to: Values.Values }) => Result.Result<{ readonly from: Values.Values; readonly to: Values.Values }, string> =
751
+ /*#__PURE__*/ Match.type<{ readonly el: ServerElement; readonly to: Values.Values }>().pipe(
752
+ Match.when({ el: { appear: false } }, () => Result.fail("appear={false}")),
753
+ Match.orElse(({ el, to }) =>
754
+ Option.match(unplayable(el.initial, to), {
755
+ onSome: (reason): Result.Result<{ readonly from: Values.Values; readonly to: Values.Values }, string> => Result.fail(reason),
756
+ onNone: () => Result.succeed({ from: Rec.map(to, (target, key) => Option.getOrThrow(OwnValues.valueLike(el.initial[key] as number | string, target))), to }),
757
+ })),
758
+ )
759
+
760
+ /** Whether a user style sets an `animation` of its own: the element's one CSS animation would be taken. */
761
+ export const setsAnimation: (css: object | string | undefined) => boolean = /*#__PURE__*/ Match.type<object | string | undefined>().pipe(
762
+ Match.when(Predicate.isString, (text) => /(^|;)\s*animation(-name)?\s*:/i.test(text)),
763
+ Match.when(Predicate.isObject, (record) => Bool.or(Object.hasOwn(record, "animation"), Object.hasOwn(record, "animationName"))),
764
+ Match.orElse(() => false),
765
+ )
766
+
767
+ // --- The Handoff -------------------------------------------------------------------------------
768
+
769
+ /** A Handoff in the DOM: its animation, which development's check matches against the mount animation (`checkHandoff`). */
770
+ export interface DomHandoff extends AppearHandoff.Handoff {
771
+ readonly animation: Animation
772
+ }
773
+
774
+ /** Whether `node` is a shadow root: a fragment with a host. */
775
+ const isShadowRoot = (node: Node): node is ShadowRoot =>
776
+ Bool.and(node.nodeType === Node.DOCUMENT_FRAGMENT_NODE, Predicate.isNotUndefined((node as Partial<ShadowRoot>).host))
777
+
778
+ /** What `Appear.findAll` reads: a document, or a shadow root, whose animations a document's read doesn't reach. */
779
+ type Root = Document | ShadowRoot
780
+
781
+ /** A root's Appear animations by element, as `Appear.findAll` reads them. */
782
+ type RootRead = ReadonlyMap<Element, Animation>
783
+
784
+ /**
785
+ * The root `element` is in, as `Appear.findAll` reads it: the shadow root it's in, or its document (#724).
786
+ * A detached element, its root its own tree, reads its document, where it runs no animation.
787
+ */
788
+ const rootOf = (element: Element): Root =>
789
+ Option.getOrElse(Option.liftPredicate(element.getRootNode(), isShadowRoot), () => element.ownerDocument)
790
+
791
+ // Module state (#460, Q7): a cache of the reads one synchronous run took, keyed by the root each read,
792
+ // dropped at the next microtask checkpoint.
793
+ let readsByRoot: Map<Root, RootRead> | undefined = undefined
794
+
795
+ /** The reads taken since the last microtask checkpoint, by root: the next checkpoint drops them. */
796
+ const readsNow = (): Map<Root, RootRead> => {
797
+ if (Predicate.isNotUndefined(readsByRoot)) return readsByRoot
798
+ const reads = new Map<Root, RootRead>()
799
+ readsByRoot = reads
800
+ queueMicrotask(() => {
801
+ readsByRoot = undefined
802
+ })
803
+ return reads
804
+ }
805
+
806
+ /**
807
+ * The Appear animations on `element`'s page, its document or its shadow root: one `getAnimations()`
808
+ * (`Appear.findAll`), kept until the next microtask checkpoint, for every Handoff until then (#706 Q3,
809
+ * #724). A hydration pass makes all its lookups before one, so it reads once: each element's at mount, and
810
+ * a Batch's at its change's first step.
811
+ */
812
+ export const pageAnimationsOf = (element: Element): RootRead => {
813
+ const root = rootOf(element)
814
+ const reads = readsNow()
815
+ const read = reads.get(root)
816
+ if (Predicate.isNotUndefined(read)) return read
817
+ const animations = Appear.findAll(root)
818
+ reads.set(root, animations)
819
+ return animations
820
+ }
821
+
822
+ /** The Handoff of `animation`: what the spine reads of it. */
823
+ // #672 (PR2-Q1): the spine reads its Handoff through these, so it reads no Animation, and the Handoff
824
+ // needs no port; the DOM's reads of the animation stay with whatever finds it. Development's match
825
+ // reads `animation` on the binding's side, so a production build ships none of it (#746, decision 6).
826
+ const toHandoff = (animation: Animation): DomHandoff => ({
827
+ elapsed: () => Appear.elapsedOf(animation),
828
+ delay: () => Appear.delayOf(animation),
829
+ animation,
830
+ })
831
+
832
+ /**
833
+ * The element's Appear animation, if a server started one (decision 6). Only an element whose inline style
834
+ * names its slot looks, in its page's read (#724): a page with none reads nothing.
835
+ */
836
+ export const handoffOf = (element: Element & ElementCSSInlineStyle): Option.Option<AppearHandoff.Handoff> =>
837
+ Option.map(Option.flatMap(Option.liftPredicate(element, Appear.pending), (el) => Appear.findIn(pageAnimationsOf(el), el)), toHandoff)