@wardic/dom 1.1.0 → 1.1.2

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 (253) hide show
  1. package/dist/DomProjectionSystem.js +3 -3
  2. package/dist/DomProjectionSystem.js.map +1 -1
  3. package/dist/FlushGate.d.ts +6 -6
  4. package/dist/FlushGate.d.ts.map +1 -1
  5. package/dist/FlushGate.js +7 -5
  6. package/dist/FlushGate.js.map +1 -1
  7. package/dist/ReorderController.js +3 -3
  8. package/dist/ReorderController.js.map +1 -1
  9. package/dist/Report.d.ts +1 -1
  10. package/dist/Report.d.ts.map +1 -1
  11. package/dist/Report.js +3 -2
  12. package/dist/Report.js.map +1 -1
  13. package/dist/Style.d.ts +2 -1
  14. package/dist/Style.d.ts.map +1 -1
  15. package/dist/Style.js +3 -1
  16. package/dist/Style.js.map +1 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/internal/batch-handoff.d.ts +25 -0
  20. package/dist/internal/batch-handoff.d.ts.map +1 -0
  21. package/dist/internal/batch-handoff.js +64 -0
  22. package/dist/internal/batch-handoff.js.map +1 -0
  23. package/dist/internal/gate-environment.d.ts +4 -0
  24. package/dist/internal/gate-environment.d.ts.map +1 -0
  25. package/dist/internal/gate-environment.js +21 -0
  26. package/dist/internal/gate-environment.js.map +1 -0
  27. package/dist/internal/projection.js +14 -14
  28. package/dist/internal/projection.js.map +1 -1
  29. package/dist/internal/reorder.d.ts +2 -2
  30. package/dist/internal/reorder.d.ts.map +1 -1
  31. package/dist/internal/reorder.js +2 -2
  32. package/dist/internal/reorder.js.map +1 -1
  33. package/dist/internal/starting-style.d.ts +0 -83
  34. package/dist/internal/starting-style.d.ts.map +1 -1
  35. package/dist/internal/starting-style.js +16 -143
  36. package/dist/internal/starting-style.js.map +1 -1
  37. package/dist/unstable/AppearAnimations.d.ts +191 -0
  38. package/dist/unstable/AppearAnimations.d.ts.map +1 -0
  39. package/dist/unstable/AppearAnimations.js +561 -0
  40. package/dist/unstable/AppearAnimations.js.map +1 -0
  41. package/dist/unstable/BatchMembers.d.ts +513 -0
  42. package/dist/unstable/BatchMembers.d.ts.map +1 -0
  43. package/dist/unstable/BatchMembers.js +2490 -0
  44. package/dist/unstable/BatchMembers.js.map +1 -0
  45. package/dist/unstable/DomValues.d.ts +25 -0
  46. package/dist/unstable/DomValues.d.ts.map +1 -0
  47. package/dist/unstable/DomValues.js +45 -0
  48. package/dist/unstable/DomValues.js.map +1 -0
  49. package/dist/unstable/DragConstraints.d.ts +48 -0
  50. package/dist/unstable/DragConstraints.d.ts.map +1 -0
  51. package/dist/unstable/DragConstraints.js +49 -0
  52. package/dist/unstable/DragConstraints.js.map +1 -0
  53. package/dist/unstable/DragControls.d.ts +50 -0
  54. package/dist/unstable/DragControls.d.ts.map +1 -0
  55. package/dist/unstable/DragControls.js +55 -0
  56. package/dist/unstable/DragControls.js.map +1 -0
  57. package/dist/unstable/DragDefaults.d.ts +34 -0
  58. package/dist/unstable/DragDefaults.d.ts.map +1 -0
  59. package/dist/unstable/DragDefaults.js +47 -0
  60. package/dist/unstable/DragDefaults.js.map +1 -0
  61. package/dist/unstable/DragTrack.d.ts +236 -0
  62. package/dist/unstable/DragTrack.d.ts.map +1 -0
  63. package/dist/unstable/DragTrack.js +646 -0
  64. package/dist/unstable/DragTrack.js.map +1 -0
  65. package/dist/unstable/DragTransition.d.ts +22 -0
  66. package/dist/unstable/DragTransition.d.ts.map +1 -0
  67. package/dist/unstable/DragTransition.js +31 -0
  68. package/dist/unstable/DragTransition.js.map +1 -0
  69. package/dist/unstable/ElementSetup.d.ts +144 -0
  70. package/dist/unstable/ElementSetup.d.ts.map +1 -0
  71. package/dist/unstable/ElementSetup.js +297 -0
  72. package/dist/unstable/ElementSetup.js.map +1 -0
  73. package/dist/unstable/Feature.d.ts +221 -0
  74. package/dist/unstable/Feature.d.ts.map +1 -0
  75. package/dist/unstable/Feature.js +281 -0
  76. package/dist/unstable/Feature.js.map +1 -0
  77. package/dist/unstable/GestureFeatures.d.ts +30 -0
  78. package/dist/unstable/GestureFeatures.d.ts.map +1 -0
  79. package/dist/unstable/GestureFeatures.js +32 -0
  80. package/dist/unstable/GestureFeatures.js.map +1 -0
  81. package/dist/unstable/GestureInfo.d.ts +61 -0
  82. package/dist/unstable/GestureInfo.d.ts.map +1 -0
  83. package/dist/unstable/GestureInfo.js +23 -0
  84. package/dist/unstable/GestureInfo.js.map +1 -0
  85. package/dist/unstable/Imperative.d.ts +214 -0
  86. package/dist/unstable/Imperative.d.ts.map +1 -0
  87. package/dist/unstable/Imperative.js +768 -0
  88. package/dist/unstable/Imperative.js.map +1 -0
  89. package/dist/unstable/Instant.d.ts +46 -0
  90. package/dist/unstable/Instant.d.ts.map +1 -0
  91. package/dist/unstable/Instant.js +49 -0
  92. package/dist/unstable/Instant.js.map +1 -0
  93. package/dist/unstable/LayoutGroup.d.ts +14 -0
  94. package/dist/unstable/LayoutGroup.d.ts.map +1 -0
  95. package/dist/unstable/LayoutGroup.js +31 -0
  96. package/dist/unstable/LayoutGroup.js.map +1 -0
  97. package/dist/unstable/LayoutMember.d.ts +127 -0
  98. package/dist/unstable/LayoutMember.d.ts.map +1 -0
  99. package/dist/unstable/LayoutMember.js +176 -0
  100. package/dist/unstable/LayoutMember.js.map +1 -0
  101. package/dist/unstable/LiveStyle.d.ts +171 -0
  102. package/dist/unstable/LiveStyle.d.ts.map +1 -0
  103. package/dist/unstable/LiveStyle.js +329 -0
  104. package/dist/unstable/LiveStyle.js.map +1 -0
  105. package/dist/unstable/MemberHold.d.ts +3 -0
  106. package/dist/unstable/MemberHold.d.ts.map +1 -0
  107. package/dist/unstable/MemberHold.js +223 -0
  108. package/dist/unstable/MemberHold.js.map +1 -0
  109. package/dist/unstable/OwnerScope.d.ts +16 -0
  110. package/dist/unstable/OwnerScope.d.ts.map +1 -0
  111. package/dist/unstable/OwnerScope.js +35 -0
  112. package/dist/unstable/OwnerScope.js.map +1 -0
  113. package/dist/unstable/PresenceController.d.ts +128 -0
  114. package/dist/unstable/PresenceController.d.ts.map +1 -0
  115. package/dist/unstable/PresenceController.js +1427 -0
  116. package/dist/unstable/PresenceController.js.map +1 -0
  117. package/dist/unstable/Press.d.ts +26 -0
  118. package/dist/unstable/Press.d.ts.map +1 -0
  119. package/dist/unstable/Press.js +19 -0
  120. package/dist/unstable/Press.js.map +1 -0
  121. package/dist/unstable/ServerInterpolators.d.ts +17 -0
  122. package/dist/unstable/ServerInterpolators.d.ts.map +1 -0
  123. package/dist/unstable/ServerInterpolators.js +20 -0
  124. package/dist/unstable/ServerInterpolators.js.map +1 -0
  125. package/dist/unstable/WardConfig.d.ts +567 -0
  126. package/dist/unstable/WardConfig.d.ts.map +1 -0
  127. package/dist/unstable/WardConfig.js +2 -0
  128. package/dist/unstable/WardConfig.js.map +1 -0
  129. package/dist/unstable/features/All.d.ts +24 -0
  130. package/dist/unstable/features/All.d.ts.map +1 -0
  131. package/dist/unstable/features/All.js +20 -0
  132. package/dist/unstable/features/All.js.map +1 -0
  133. package/dist/unstable/features/Colors.d.ts +12 -0
  134. package/dist/unstable/features/Colors.d.ts.map +1 -0
  135. package/dist/unstable/features/Colors.js +38 -0
  136. package/dist/unstable/features/Colors.js.map +1 -0
  137. package/dist/unstable/features/DomAnimation.d.ts +16 -0
  138. package/dist/unstable/features/DomAnimation.d.ts.map +1 -0
  139. package/dist/unstable/features/DomAnimation.js +19 -0
  140. package/dist/unstable/features/DomAnimation.js.map +1 -0
  141. package/dist/unstable/features/DomMax.d.ts +12 -0
  142. package/dist/unstable/features/DomMax.d.ts.map +1 -0
  143. package/dist/unstable/features/DomMax.js +14 -0
  144. package/dist/unstable/features/DomMax.js.map +1 -0
  145. package/dist/unstable/features/Drag.d.ts +5 -0
  146. package/dist/unstable/features/Drag.d.ts.map +1 -0
  147. package/dist/unstable/features/Drag.js +32 -0
  148. package/dist/unstable/features/Drag.js.map +1 -0
  149. package/dist/unstable/features/Focus.d.ts +5 -0
  150. package/dist/unstable/features/Focus.d.ts.map +1 -0
  151. package/dist/unstable/features/Focus.js +20 -0
  152. package/dist/unstable/features/Focus.js.map +1 -0
  153. package/dist/unstable/features/Hover.d.ts +5 -0
  154. package/dist/unstable/features/Hover.d.ts.map +1 -0
  155. package/dist/unstable/features/Hover.js +20 -0
  156. package/dist/unstable/features/Hover.js.map +1 -0
  157. package/dist/unstable/features/InView.d.ts +5 -0
  158. package/dist/unstable/features/InView.d.ts.map +1 -0
  159. package/dist/unstable/features/InView.js +20 -0
  160. package/dist/unstable/features/InView.js.map +1 -0
  161. package/dist/unstable/features/Input.d.ts +28 -0
  162. package/dist/unstable/features/Input.d.ts.map +1 -0
  163. package/dist/unstable/features/Input.js +31 -0
  164. package/dist/unstable/features/Input.js.map +1 -0
  165. package/dist/unstable/features/Keys.d.ts +95 -0
  166. package/dist/unstable/features/Keys.d.ts.map +1 -0
  167. package/dist/unstable/features/Keys.js +44 -0
  168. package/dist/unstable/features/Keys.js.map +1 -0
  169. package/dist/unstable/features/Layout.d.ts +43 -0
  170. package/dist/unstable/features/Layout.d.ts.map +1 -0
  171. package/dist/unstable/features/Layout.js +44 -0
  172. package/dist/unstable/features/Layout.js.map +1 -0
  173. package/dist/unstable/features/Pan.d.ts +5 -0
  174. package/dist/unstable/features/Pan.d.ts.map +1 -0
  175. package/dist/unstable/features/Pan.js +20 -0
  176. package/dist/unstable/features/Pan.js.map +1 -0
  177. package/dist/unstable/features/Press.d.ts +13 -0
  178. package/dist/unstable/features/Press.d.ts.map +1 -0
  179. package/dist/unstable/features/Press.js +10 -0
  180. package/dist/unstable/features/Press.js.map +1 -0
  181. package/dist/unstable/features/Scroll.d.ts +20 -0
  182. package/dist/unstable/features/Scroll.d.ts.map +1 -0
  183. package/dist/unstable/features/Scroll.js +34 -0
  184. package/dist/unstable/features/Scroll.js.map +1 -0
  185. package/dist/unstable/features/TimelineKeys.d.ts +7 -0
  186. package/dist/unstable/features/TimelineKeys.d.ts.map +1 -0
  187. package/dist/unstable/features/TimelineKeys.js +103 -0
  188. package/dist/unstable/features/TimelineKeys.js.map +1 -0
  189. package/package.json +4 -3
  190. package/src/DomProjectionSystem.ts +3 -3
  191. package/src/FlushGate.ts +11 -9
  192. package/src/ReorderController.ts +3 -3
  193. package/src/Report.ts +3 -7
  194. package/src/Style.ts +4 -1
  195. package/src/index.ts +1 -1
  196. package/src/internal/batch-handoff.ts +75 -0
  197. package/src/internal/gate-environment.ts +21 -0
  198. package/src/internal/projection.ts +14 -14
  199. package/src/internal/reorder.ts +4 -4
  200. package/src/internal/starting-style.ts +5 -204
  201. package/src/unstable/AppearAnimations.ts +837 -0
  202. package/src/unstable/BatchMembers.ts +3085 -0
  203. package/src/unstable/DomValues.ts +53 -0
  204. package/src/unstable/DragConstraints.ts +107 -0
  205. package/src/unstable/DragControls.ts +98 -0
  206. package/src/unstable/DragDefaults.ts +57 -0
  207. package/src/unstable/DragTrack.ts +959 -0
  208. package/src/unstable/DragTransition.ts +46 -0
  209. package/src/unstable/ElementSetup.ts +411 -0
  210. package/src/unstable/Feature.ts +494 -0
  211. package/src/unstable/GestureFeatures.ts +38 -0
  212. package/src/unstable/GestureInfo.ts +85 -0
  213. package/src/unstable/Imperative.ts +1037 -0
  214. package/src/unstable/Instant.ts +93 -0
  215. package/src/unstable/LayoutGroup.ts +36 -0
  216. package/src/unstable/LayoutMember.ts +319 -0
  217. package/src/unstable/LiveStyle.ts +497 -0
  218. package/src/unstable/MemberHold.ts +211 -0
  219. package/src/unstable/OwnerScope.ts +35 -0
  220. package/src/unstable/PresenceController.ts +1747 -0
  221. package/src/unstable/Press.ts +43 -0
  222. package/src/unstable/ServerInterpolators.ts +39 -0
  223. package/src/unstable/WardConfig.ts +704 -0
  224. package/src/unstable/features/All.ts +39 -0
  225. package/src/unstable/features/Colors.ts +40 -0
  226. package/src/unstable/features/DomAnimation.ts +19 -0
  227. package/src/unstable/features/DomMax.ts +14 -0
  228. package/src/unstable/features/Drag.ts +34 -0
  229. package/src/unstable/features/Focus.ts +21 -0
  230. package/src/unstable/features/Hover.ts +21 -0
  231. package/src/unstable/features/InView.ts +21 -0
  232. package/src/unstable/features/Input.ts +37 -0
  233. package/src/unstable/features/Keys.ts +124 -0
  234. package/src/unstable/features/Layout.ts +75 -0
  235. package/src/unstable/features/Pan.ts +21 -0
  236. package/src/unstable/features/Press.ts +21 -0
  237. package/src/unstable/features/Scroll.ts +35 -0
  238. package/src/unstable/features/TimelineKeys.ts +115 -0
  239. package/dist/internal/gate.d.ts +0 -199
  240. package/dist/internal/gate.d.ts.map +0 -1
  241. package/dist/internal/gate.js +0 -570
  242. package/dist/internal/gate.js.map +0 -1
  243. package/dist/internal/report.d.ts +0 -30
  244. package/dist/internal/report.d.ts.map +0 -1
  245. package/dist/internal/report.js +0 -60
  246. package/dist/internal/report.js.map +0 -1
  247. package/dist/internal/runner.d.ts +0 -22
  248. package/dist/internal/runner.d.ts.map +0 -1
  249. package/dist/internal/runner.js +0 -62
  250. package/dist/internal/runner.js.map +0 -1
  251. package/src/internal/gate.ts +0 -706
  252. package/src/internal/report.ts +0 -69
  253. package/src/internal/runner.ts +0 -78
@@ -0,0 +1,3085 @@
1
+ /**
2
+ * `createBatch`'s work (#665), for every DOM binding: one core Batch for a collection of elements, its
3
+ * members entered as their elements arrive, and each change of their targets one Retarget of them all.
4
+ * Each binding's `createBatch` builds on it, tracking its config's `animate` with its own framework.
5
+ *
6
+ * - **Its keys** are the ones its members' first targets and starts give: fixed when it's made, as a
7
+ * Batch's are (ADR-0069, decision 10). A key a later `animate` gives is an error naming it.
8
+ * - **A member** is an element given to its handle's `ref`. It starts from `initial`, else at each
9
+ * key's identity, as an element does with no style of its own; with `initial: false`, at its target.
10
+ * An element its framework makes again for the same member carries on where the last one was.
11
+ * - **A change** turns every member toward its targets in one Retarget: a member whose targets are
12
+ * unchanged gets nothing, and `delay: stagger()` counts the members it moves (ADR-0069, *Amendment
13
+ * (#665)*).
14
+ * - **Its transitions** are a Wardic element's, read as each change starts: the config's, else the
15
+ * nearest `WardicConfig`'s; each key's own entry and its `delay`; the Environment's Default
16
+ * transition for a key without one; reduced motion's Snap for a positional key; `skipAnimations`.
17
+ *
18
+ * Unstable, for Wardic's own packages: public, with no semver promise.
19
+ *
20
+ * @module
21
+ */
22
+ // Unstable: ADR-0071, decision 5. #672: solid's `batch.ts`, moved to dom for every DOM binding's
23
+ // `createBatch` and `animate`; `BatchMembers`, as core has `Batch`.
24
+ // ADR-0070 decisions 10–15 and *Amendment (#665)*. The DOM's writer, imported here so an app that never
25
+ // makes a Batch ships none of it (ADR-0070, *Amendment (#665)*).
26
+ import * as Batch from "@wardic/core/Batch"
27
+ import * as BaseValue from "@wardic/core/BaseValue"
28
+ import type * as DefaultTransition from "@wardic/core/DefaultTransition"
29
+ import type * as Machine from "@wardic/core/Machine"
30
+ import * as Playback from "@wardic/core/Playback"
31
+ import * as ReducedMotion from "@wardic/core/ReducedMotion"
32
+ import type * as Sequence from "@wardic/core/Sequence"
33
+ import type * as Subject from "@wardic/core/unstable/Subject"
34
+ import * as Appear from "../Appear.ts"
35
+ import * as DomBatch from "../DomBatch.ts"
36
+ import * as DomDefaultTransition from "../DomDefaultTransition.ts"
37
+ import * as DomPositionalKeys from "../DomPositionalKeys.ts"
38
+ import * as KeyboardPress from "../KeyboardPress.ts"
39
+ import * as Report from "../Report.ts"
40
+ import * as Svg from "../Svg.ts"
41
+ import * as Arr from "effect/Array"
42
+ import * as Bool from "effect/Boolean"
43
+ import * as Cause from "effect/Cause"
44
+ import type * as Fiber from "effect/Fiber"
45
+ import { identity } from "effect/Function"
46
+ import * as Iter from "effect/Iterable"
47
+ import * as Option from "effect/Option"
48
+ import * as Predicate from "effect/Predicate"
49
+ import * as Rec from "effect/Record"
50
+ import * as Result from "effect/Result"
51
+ import * as UndefinedOr from "effect/UndefinedOr"
52
+ import * as AppearAnimations from "./AppearAnimations.ts"
53
+ import type * as WardConfig from "./WardConfig.ts"
54
+ import type * as GestureInfo from "./GestureInfo.ts"
55
+ import type * as PresenceController from "./PresenceController.ts"
56
+ import * as PresenceRecord from "@wardic/core/unstable/PresenceRecord"
57
+ import * as RetargetLegs from "@wardic/core/unstable/RetargetLegs"
58
+ import type * as WardicServices from "@wardic/core/unstable/WardicServices"
59
+ import * as WardicConfigValue from "@wardic/core/unstable/WardicConfigValue"
60
+
61
+ /** The keys a Batch's members animate on the DOM: the transforms and `opacity`, as numbers. */
62
+ export type WardicBatchKey =
63
+ | "x" | "y" | "z" | "translateX" | "translateY" | "translateZ"
64
+ | "scale" | "scaleX" | "scaleY"
65
+ | "rotate" | "rotateX" | "rotateY" | "rotateZ"
66
+ | "skewX" | "skewY"
67
+ | "opacity"
68
+
69
+ /** A member's values: numbers on its keys, in `px` for a move, degrees for a turn, unitless for a scale and `opacity`. */
70
+ export type WardicBatchValues = { readonly [K in WardicBatchKey]?: number }
71
+
72
+ /**
73
+ * A Batch's transition: a Wardic element's, its `delay` seconds, or a `stagger()`, which holds each
74
+ * member by its place among the members a change moves.
75
+ */
76
+ export type WardicBatchTransition = WardConfig.WardicTransition extends infer T
77
+ ? T extends unknown ? Omit<T, "delay"> & { readonly delay?: number | ((index: number, total: number) => number) } : never
78
+ : never
79
+
80
+ /** A stop of a Batch's `animate` call: a number for every member, or a function of its index and the Batch's count. */
81
+ export type WardicBatchStop = number | ((i: number, n: number) => number)
82
+
83
+ /**
84
+ * A Batch's targets for an `animate` call, key by key: a stop, or two, the member's first and its
85
+ * target; or a function of the member's index and the count that gives one or two.
86
+ */
87
+ // ADR-0069 decision 14: Motion's two-stop form, for every member or per member, `(i) => [-2, rowY(i)]`.
88
+ export type WardicBatchTarget = {
89
+ readonly [K in WardicBatchKey]?: WardicBatchStop | readonly [WardicBatchStop, WardicBatchStop] | ((i: number, n: number) => number | readonly [number, number])
90
+ }
91
+
92
+ /**
93
+ * A Batch's key in a sequence's Segment of it: a number for every member, `null` for where it is, stops
94
+ * of them, or a function of a member's index and the Batch's count that gives one of them.
95
+ */
96
+ // #665, Q38: as `animate(grid, …)`'s, its stops placed over the sequence.
97
+ export type WardicBatchSegmentValue = number | null | ReadonlyArray<number | null> | ((i: number, n: number) => number | null | ReadonlyArray<number | null>)
98
+
99
+ /** A sequence's Segment of a Batch's values, key by key: each one of its keys. */
100
+ export type WardicBatchSegmentTarget = { readonly [K in WardicBatchKey]?: WardicBatchSegmentValue }
101
+
102
+ /** What `createAnimate`'s `animate` takes for a Batch: one, by index or keyed, or a member's handle, `grid.at(i)` or `grid.member(key)`. */
103
+ export type WardicBatchSubject = { readonly at: (i: number, props?: never) => unknown } | { readonly member: (key: never, props?: never) => unknown } | { readonly ref: (el: never) => void }
104
+
105
+ /** A Batch's landing: how many members set off in the flight that landed. */
106
+ export interface WardicBatchLanding {
107
+ readonly moved: number
108
+ }
109
+
110
+ /** A keyed member's exit: its values, and the transition it leaves on, else the Batch's (Q48). */
111
+ export type WardicBatchExit = WardicBatchValues & { readonly transition?: WardicBatchTransition }
112
+
113
+ /**
114
+ * A member's gesture, `whileHover`'s or `whileTap`'s (#665's PR 5, Q58): its values, and the transition it
115
+ * moves into them on, else the Batch's. It moves back on the Batch's, or a press ending while the member's
116
+ * hovered back to `whileHover`'s values on the hover's.
117
+ */
118
+ export type WardicBatchGesture = WardicBatchValues & { readonly transition?: WardicBatchTransition }
119
+
120
+ /** A member's gesture events (ADR-0070 decision 12, Q60): its hover's start and end, its press's start, and how it ended. */
121
+ export type WardicBatchGestureName = "hoverStart" | "hoverEnd" | "pressStart" | "tap" | "tapCancel"
122
+
123
+ /** What both bindings' `createBatch` take by index: `count` members, each by its index. */
124
+ export interface BatchConfig {
125
+ /** How many members it has: read once. */
126
+ readonly count: number
127
+ /** Where each member starts: values, a function of its index, or `false` to start at its targets. */
128
+ readonly initial?: false | WardicBatchValues | ((i: number) => WardicBatchValues)
129
+ /** Each member's targets, by its index: tracked, so a change turns every member once. */
130
+ readonly animate: (i: number) => WardicBatchValues
131
+ /**
132
+ * Where a member goes while the pointer is over it (touch never hovers), over `animate`'s: values with
133
+ * an optional `transition`, or a function of its index, read as its hover starts (Q58). Back to
134
+ * `animate`'s as it ends.
135
+ */
136
+ readonly whileHover?: WardicBatchGesture | ((i: number) => WardicBatchValues)
137
+ /**
138
+ * Where a member goes while it's pressed, over `whileHover`'s and `animate`'s: by a pointer, or by Enter
139
+ * or Space while it has focus (with it, or a tap event, a member's element takes `tabindex="0"` unless
140
+ * it's focusable): values with an optional `transition`, or a function of its index, read as its press
141
+ * starts (Q57, Q58).
142
+ */
143
+ readonly whileTap?: WardicBatchGesture | ((i: number) => WardicBatchValues)
144
+ /** How they move: else the nearest `WardicConfig`'s, else each key's Default transition. */
145
+ readonly transition?: WardicBatchTransition
146
+ /**
147
+ * Whether a server render plays its members' entrances in CSS from first paint, and hydration takes them
148
+ * over where they've got to (an **Appear animation**, #706): off unless `true`, under a provider whose
149
+ * `appear` isn't `false`. Without it, a server render draws each member's start, as before.
150
+ */
151
+ readonly appear?: boolean | undefined
152
+ }
153
+
154
+ /**
155
+ * What both bindings' `createBatch` take in the keyed form (#665, Q42–Q45): a list's items, each a member
156
+ * by its key, entering as its element arrives and leaving as it leaves the list.
157
+ */
158
+ export interface KeyedBatchConfig<T> {
159
+ /** The items, in order: tracked, so a change of the list, or of its order, turns every member once. */
160
+ readonly each: () => ReadonlyArray<T>
161
+ /** Each item's key: the name of its property, or a function of it (Q43). */
162
+ readonly key: keyof T | ((item: T) => unknown)
163
+ /** Its keys, fixed up front: else the first members' targets and starts give them (Q51). */
164
+ readonly keys?: ReadonlyArray<WardicBatchKey>
165
+ /** Where each member starts: values, a function of its item and index, or `false` to start at its targets. */
166
+ readonly initial?: false | WardicBatchValues | ((item: T, i: number) => WardicBatchValues)
167
+ /** Each member's targets, by its item and its index in `each`: tracked, so a change turns every member once. */
168
+ readonly animate: (item: T, i: number) => WardicBatchValues
169
+ /**
170
+ * Where a member leaves to under `<AnimatePresence>`, its element kept until it lands: values with an
171
+ * optional `transition`, or a function of its item, its last index and the presence's `custom` (Q48).
172
+ */
173
+ readonly exit?: WardicBatchExit | ((item: T, i: number, custom: unknown) => WardicBatchValues)
174
+ /**
175
+ * Where a member goes while the pointer is over it (touch never hovers), over `animate`'s: values with
176
+ * an optional `transition`, or a function of its item and index, read as its hover starts (Q58).
177
+ */
178
+ readonly whileHover?: WardicBatchGesture | ((item: T, i: number) => WardicBatchValues)
179
+ /**
180
+ * Where a member goes while it's pressed, over `whileHover`'s and `animate`'s, by a pointer or by Enter or
181
+ * Space while it has focus: values with an optional `transition`, or a function of its item and index,
182
+ * read as its press starts (Q57, Q58).
183
+ */
184
+ readonly whileTap?: WardicBatchGesture | ((item: T, i: number) => WardicBatchValues)
185
+ /** How they move: else the nearest `WardicConfig`'s, else each key's Default transition. */
186
+ readonly transition?: WardicBatchTransition
187
+ /** Whether a server render plays its members' entrances from first paint (#706): off unless `true`. */
188
+ readonly appear?: boolean | undefined
189
+ }
190
+
191
+ /**
192
+ * A Batch Reorder group's Batch (#712, ADR-0072 decision 8): a keyed Batch's config, and where an item
193
+ * goes while it's in hand, dragged or lifted from the keyboard, over its gestures': values with an
194
+ * optional `transition`, or a function of its item and index, read as it's taken.
195
+ */
196
+ export interface ReorderBatchConfig<T> extends KeyedBatchConfig<T> {
197
+ readonly whileDrag?: WardicBatchGesture | ((item: T, i: number) => WardicBatchValues) | undefined
198
+ /** A function `whileHover`, `whileTap` or `whileDrag` gives keys the Batch takes from its first item (Q27, Q34). */
199
+ readonly gestureKeysFromFirst: true
200
+ }
201
+
202
+ /** Whether a Batch's config is the keyed form's. */
203
+ export const isKeyed = (config: BatchConfig | KeyedBatchConfig<unknown>): config is KeyedBatchConfig<unknown> => Predicate.hasProperty(config, "each")
204
+
205
+ /** What a Batch needs from its provider. */
206
+ export interface BatchEnv {
207
+ readonly runtime: WardicServices.Runner<WardicServices.WardicServices>
208
+ readonly reducedMotion: () => boolean
209
+ readonly skipAnimations: () => boolean
210
+ readonly positionalKeys: ReducedMotion.PositionalKeys["Service"]
211
+ readonly defaultTransition: DefaultTransition.DefaultTransition["Service"]
212
+ /** The nearest `WardicConfig`'s transition, read as each change starts. */
213
+ readonly configTransition: () => WardConfig.WardicTransition | undefined
214
+ /** Its binding's `untrack`: a keyed Batch reads its list again at a task's end, outside its tracking. */
215
+ readonly untrack: <A>(read: () => A) => A
216
+ /**
217
+ * Whether it's made while hydrating a server render (#706): its members' elements may run their Appear
218
+ * animation, which its first change takes over. Left out, it never looks.
219
+ */
220
+ readonly hydrating?: boolean | undefined
221
+ /**
222
+ * In development alone (each binding's development flag), what checks a taken-over Appear animation against the
223
+ * member's own transitions (#706, Q9): left out of a production build, with the canonical text it writes.
224
+ */
225
+ readonly appearKeyOf?: typeof AppearAnimations.batchKeyOf | undefined
226
+ /** Its members' gestures (#665's PR 5, Q56): what watches them, from one source each. None, none listen. */
227
+ readonly gestures?: BatchGestureWatches | undefined
228
+ /**
229
+ * Whether a focused member's Enter and Space press it now (#712, Q32): a Batch Reorder group's, not while
230
+ * its keyboard reorder takes them. Left out, they always do.
231
+ */
232
+ readonly pressKeys?: (() => boolean) | undefined
233
+ }
234
+
235
+ /**
236
+ * How a Batch watches its members' gestures (#665's PR 5, Q56, Q60, Q62): its hover and its presses over
237
+ * them, each started once, at its first need, over its host, and stopped with the Batch.
238
+ */
239
+ export interface BatchGestureWatches {
240
+ /** Its members' hover, or presses (a pointer's, and a focused member's keys), watched from now on. */
241
+ readonly listen: (gesture: "hover" | "press", host: BatchGestureHost) => void
242
+ }
243
+
244
+ /**
245
+ * A member's gesture layer over its `animate` targets (ADR-0070 decision 12): its hover's, its press's over
246
+ * that, and a Batch Reorder group's item in hand's over both (#712, ADR-0072 decision 8).
247
+ */
248
+ export type BatchGestureLayer = "hover" | "press" | "drag"
249
+
250
+ /** What a Batch's gestures work its members through (Q58, Q59): their layers, its keys, and how each member is named. */
251
+ export interface BatchGestureHost {
252
+ /** The element a node is, while it's this Batch's member's, else `Option.none()`: what its watches are over. */
253
+ readonly memberElementOf: (node: unknown) => Option.Option<unknown>
254
+ /** The member such an element is: its number. */
255
+ readonly memberAt: (element: unknown) => number | undefined
256
+ /** Whether member `i`'s `layer` is on. */
257
+ readonly layered: (layer: BatchGestureLayer, i: number) => boolean
258
+ /**
259
+ * Member `i`'s `layer` at `values`, by key index (`NaN` for a key they don't give), or off: then the
260
+ * member turned toward its Override stack's targets on `transition`, never staggered, a key only a
261
+ * layer gave back to where it was as the first came on; a leaver not turned, its exit holding its keys.
262
+ */
263
+ readonly layer: (layer: BatchGestureLayer, i: number, values: Float64Array | undefined, transition: WardConfig.WardicTransition | undefined) => void
264
+ /** Its keys, in their order. */
265
+ readonly keys: () => ReadonlyArray<string>
266
+ /** Member `i` as an error names it, its index (a keyed member's in its list now), and its item. */
267
+ readonly nameOf: (i: number) => string
268
+ readonly indexOf: (i: number) => number
269
+ readonly itemOf: (i: number) => unknown
270
+ readonly keyed: boolean
271
+ readonly untrack: <A>(read: () => A) => A
272
+ /** The Batch's transition now. */
273
+ readonly configured: () => WardConfig.WardicTransition | undefined
274
+ /** Its config's `whileHover` and `whileTap`, as given, read as a gesture starts. */
275
+ readonly hoverGiven: unknown
276
+ readonly tapGiven: unknown
277
+ /** Whether a focused member's keys press it now: {@link BatchEnv.pressKeys}. */
278
+ readonly pressKeys: (() => boolean) | undefined
279
+ /** A Batch Reorder group's `whileDrag` now, as given (#712). */
280
+ readonly dragGiven: () => unknown
281
+ /** A member's gesture event, told its binding. */
282
+ readonly tell: (told: BatchGestureTold) => void
283
+ /**
284
+ * Member `i` in hand, a Batch Reorder group's dragged item (#712, ADR-0072 decision 7): its `x` and `y`
285
+ * there now, with no spring, over its Override stack's, until {@link handOff}.
286
+ */
287
+ readonly handAt: (i: number, x: number, y: number) => void
288
+ /** Member `i` let go: its `x` and `y` turned toward its Override stack's on the Batch's transition, from where they are at `vx` and `vy` a second. */
289
+ readonly handOff: (i: number, vx: number, vy: number) => void
290
+ }
291
+
292
+ /**
293
+ * A member's gesture event, as its Batch tells its binding (Q60): its name, the platform's event behind
294
+ * it, its point and a press's input, the member's element, its index (a keyed member's in its list now)
295
+ * and a keyed member's item.
296
+ */
297
+ export interface BatchGestureTold {
298
+ readonly name: WardicBatchGestureName
299
+ readonly raw: unknown
300
+ readonly point: GestureInfo.WardicPoint
301
+ /** A press's input; `undefined` for a hover. */
302
+ readonly input: GestureInfo.WardicPressInput | undefined
303
+ readonly element: Element
304
+ readonly i: number
305
+ readonly item: unknown
306
+ }
307
+
308
+ /** What a Batch tells its binding: a flight's start, and its landing; and its members' gestures. */
309
+ export interface BatchHooks {
310
+ readonly started: () => void
311
+ readonly landed: (landing: WardicBatchLanding) => void
312
+ /** A member's gesture event (Q60), after the member has turned toward its gesture's targets. */
313
+ readonly gesture?: ((told: BatchGestureTold) => void) | undefined
314
+ }
315
+
316
+ /** A Batch bound to its config: its targets, read by the binding's tracking, and what it does with them. */
317
+ export interface BatchBinding {
318
+ /** Every member's targets now, read in the binding's tracking: a compute, which writes nothing shared. */
319
+ readonly targetsOf: () => BatchTargets
320
+ /** A change: every member turned toward `targets`; in the keyed form, members entering and leaving. */
321
+ readonly apply: (targets: BatchTargets) => void
322
+ /**
323
+ * A change that moves the targets under its members (#712: a Batch Reorder group's first read of its
324
+ * element): each key whose target moves carries its motion over by the shift, so a member at rest is at its
325
+ * new targets at once and one mid-flight goes on as far off them as it was off its old; drawn now, before
326
+ * the page paints.
327
+ */
328
+ readonly applyShifted: (targets: BatchTargets) => void
329
+ /** Member `i`'s `ref`: one function a member. */
330
+ readonly refOf: (i: number) => (el: Element) => void
331
+ /** The keyed form's member for `key`, made at its first handle, under the `<AnimatePresence>` it's in: its number. */
332
+ readonly memberFor: (key: unknown, presence: PresenceController.PresenceContextValue | undefined) => number
333
+ /** The members a Batch or a member's handle names: `undefined` for every member, none once a handle's member has left. */
334
+ readonly namedOf: (entry: BatchSubjectEntry) => ReadonlyArray<number> | undefined
335
+ /** An element's own `style`, without the properties the Batch draws on it. */
336
+ readonly styleOf: <Style>(style: Style) => Style
337
+ /** An `animate` call's track over its members, or the members `members` names, driven by `head`. */
338
+ readonly track: (call: BatchCall) => BatchTrack
339
+ /** Member `i`'s entry, for `animate`: its handle's and its element's. */
340
+ readonly entryOf: (i: number) => BatchMemberEntry
341
+ /** Where an element call's `key` goes for a member's element. */
342
+ readonly routeOf: (key: string) => KeyRoute
343
+ /** A sequence's Segment of the Batch, or of the members `named` names: its members' entries, in member order, and its values for core. */
344
+ readonly segmentOf: (named: ReadonlyArray<number> | undefined, target: Readonly<Record<string, unknown>>) => BatchSegment
345
+ /** A sequence's Segment of members' elements: each Batch key a number, `null` or stops, and no transform the Batch draws without it. */
346
+ readonly checkElementSegment: (target: Readonly<Record<string, unknown>>) => void
347
+ /** A sequence's track over its members, each through its own Batch keys' stops, driven by `head`. */
348
+ readonly sequenceTrack: (call: BatchSequenceCall) => BatchTrack
349
+ /** Member `i`'s element, once it has arrived. */
350
+ readonly elementOf: (i: number) => Element | undefined
351
+ /**
352
+ * A Wardic element on member `i`'s element takes its `group` (#665's PR 4, ADR-0069 decision 17):
353
+ * the Batch's keys in it at the member's values and speeds, the Batch drawing them no more until it
354
+ * takes them back. `undefined` when the Batch has none of its keys, or the member isn't drawn yet.
355
+ */
356
+ readonly yieldGroup: (i: number, group: BatchGroup, holder: BatchHolder) => BatchYield | undefined
357
+ /** The Wardic element gives member `i`'s `group` back: from its values and speeds, toward the member's targets. */
358
+ readonly reclaim: (i: number, group: BatchGroup, back: BatchHandover) => void
359
+ /**
360
+ * What member `i`'s `key` is drawn at now, by its Batch: its value, or for a transform key it hasn't,
361
+ * its identity while it draws `transform`; `undefined` when it draws none of `key`'s group.
362
+ */
363
+ readonly drawnValueOf: (i: number, key: string) => number | undefined
364
+ /**
365
+ * Its members' hover, or presses, watched from now on (#665's PR 5, Q60): once each. A binding calls it
366
+ * when the Batch has `whileHover` or `whileTap`, a gesture callback, or a first ask for a gesture event.
367
+ */
368
+ readonly listen: (gesture: "hover" | "press") => void
369
+ /** What its members' gestures, and a Batch Reorder group's item in hand (#712), work them through. */
370
+ readonly host: BatchGestureHost
371
+ /** The Batch's run ended, and no member drawn again. */
372
+ readonly dispose: () => void
373
+ }
374
+
375
+ /**
376
+ * Every member's targets at a change: by index, member by member in key order, `NaN` for a key a member's
377
+ * targets leave out; keyed, each item, its key and its targets as `animate` gave them.
378
+ */
379
+ export type BatchTargets = Float64Array | KeyedTargets
380
+
381
+ /** A keyed Batch's targets at a change: its items in order, their keys, and each one's targets. */
382
+ interface KeyedTargets {
383
+ readonly items: ReadonlyArray<unknown>
384
+ readonly keys: ReadonlyArray<unknown>
385
+ readonly values: ReadonlyArray<Readonly<Record<string, unknown>>>
386
+ }
387
+
388
+ /** An `animate` call of a Batch: its targets, its transition, its scope's settings, its Playhead and landing. */
389
+ export interface BatchCall {
390
+ readonly target: WardicBatchTarget
391
+ readonly transition: WardConfig.WardicTransition | undefined
392
+ readonly reducedMotion: boolean
393
+ readonly skipAnimations: boolean
394
+ readonly head: Playback.Playhead
395
+ readonly settled: () => void
396
+ /** The members it moves, in order: every member when left out. */
397
+ readonly members: ReadonlyArray<number> | undefined
398
+ }
399
+
400
+ /** A sequence's Segment of a Batch for core (#665, Q38, Q39): its subjects, the members whose elements have arrived, and its values. */
401
+ export interface BatchSegment {
402
+ readonly subjects: ReadonlyArray<BatchMemberEntry>
403
+ readonly values: Readonly<Record<string, Sequence.Value>>
404
+ }
405
+
406
+ /** A sequence's part for a Batch: its members, in order, each one's compiled animation, its scope's settings, its Playhead and landing. */
407
+ export interface BatchSequenceCall {
408
+ readonly members: ReadonlyArray<number>
409
+ readonly animations: ReadonlyArray<Sequence.Animation>
410
+ readonly reducedMotion: boolean
411
+ readonly skipAnimations: boolean
412
+ readonly head: Playback.Playhead
413
+ readonly settled: () => void
414
+ }
415
+
416
+ /**
417
+ * Where an element call's key goes for a member's element (#665, Q14, Q33): the Batch's own key to
418
+ * the Batch; a transform the Batch draws without it, nowhere (its write would be the Batch's to
419
+ * overwrite); any other to a plain animation of the element.
420
+ */
421
+ export type KeyRoute = "batch" | "drawn" | "free"
422
+
423
+ /** What an `animate` call's Playback controls act on: an Imperative track's shape (`spine.ts`). */
424
+ export interface BatchTrack {
425
+ readonly run: () => void
426
+ readonly stop: () => void
427
+ readonly cancel: () => void
428
+ readonly duration: () => number
429
+ }
430
+
431
+ /** What `animate` knows of a Batch or a member's handle: its binding, and a handle's member by its index. */
432
+ export interface BatchSubjectEntry {
433
+ readonly binding: BatchBinding
434
+ readonly member: number | undefined
435
+ }
436
+
437
+ /** A member's entry: its handle's and its element's. */
438
+ export interface BatchMemberEntry extends BatchSubjectEntry {
439
+ readonly member: number
440
+ }
441
+
442
+ /** A Batch member's keys a driver on its element takes together (#665's PR 4, Q53): its `transform`, or its `opacity`. */
443
+ export type BatchGroup = "transform" | "opacity"
444
+
445
+ /** The group `key` is drawn in on the DOM: a transform key's `transform`, `opacity`'s own, or none. */
446
+ export const batchGroupOf = (key: string): BatchGroup | undefined => {
447
+ if (key === "opacity") return "opacity"
448
+ if (Predicate.isNotUndefined(BaseValue.TRANSFORM_IDENTITY[key])) return "transform"
449
+ return undefined
450
+ }
451
+
452
+ /** A group's keys handed over: each one's value and speed. */
453
+ export interface BatchHandover {
454
+ /** Each key's value, where it's drawn as it's handed over. */
455
+ readonly values: Readonly<Record<string, number>>
456
+ /** Each key's speed then, per second. */
457
+ readonly velocities: Readonly<Record<string, number>>
458
+ }
459
+
460
+ /** What a Wardic element holding a member's group tells its Batch (Q54). */
461
+ export interface BatchHolder {
462
+ /** Gives `group` back now, its keys' values and speeds, or `undefined` when it holds it no more. */
463
+ readonly surrender: (group: BatchGroup) => BatchHandover | undefined
464
+ /**
465
+ * Whether it keeps `group` through a Batch change of the member: a drag in progress keeps the
466
+ * transform, as does a transform key the Batch doesn't draw that it animates or has off its identity.
467
+ */
468
+ readonly keepsThrough: (group: BatchGroup) => boolean
469
+ }
470
+
471
+ /** A group a Batch gave a Wardic element: the Batch's keys in it, at the member's values and speeds. */
472
+ export interface BatchYield extends BatchHandover {
473
+ /** The Batch's keys in the group, which the Wardic element draws until it gives them back. */
474
+ readonly keys: ReadonlyArray<string>
475
+ }
476
+
477
+ /** Each Batch and member handle's entry, so `animate` knows them. */
478
+ // Module state (#460, Q7): a cache held weakly by the object it's for, so it goes with it.
479
+ const SUBJECTS = new WeakMap<object, BatchSubjectEntry>()
480
+
481
+ /** Each member's element's entry, while it's the member's, so `animate` of the element moves the member (Q14). */
482
+ // Module state (#460, Q7): held weakly by the element. Keyed by Subject (#672): the spine's hold, core's,
483
+ // looks its element up as the Subject it holds.
484
+ const MEMBER_ELEMENTS = new WeakMap<Subject.Subject, BatchMemberEntry>()
485
+
486
+ /** `handle` is `binding`'s Batch, for `animate`. */
487
+ export const registerBatch = (handle: object, binding: BatchBinding): void => {
488
+ SUBJECTS.set(handle, { binding, member: undefined })
489
+ }
490
+
491
+ /** The binding `subject` is a Batch or member handle of, for `animate`; `undefined` for anything else. */
492
+ export const batchSubjectOf = (subject: unknown): BatchSubjectEntry | undefined => {
493
+ if (!Predicate.isObject(subject)) return undefined
494
+ return SUBJECTS.get(subject)
495
+ }
496
+
497
+ // --- An element call on members' elements (#665, Q14, Q33–Q35) ----------------------------------
498
+
499
+ /** An element call's part for one Batch's member elements: the members, in list order, and the Batch's keys' stops. */
500
+ export interface MembersPart {
501
+ readonly binding: BatchBinding
502
+ readonly members: ReadonlyArray<number>
503
+ readonly target: WardicBatchTarget
504
+ }
505
+
506
+ /** An element call's part for one element: its index in the list, and what a plain animation of it takes. */
507
+ export interface ElementPart<T> {
508
+ readonly element: Element
509
+ readonly index: number
510
+ readonly target: T
511
+ }
512
+
513
+ /** Whether `value` is a Batch's key's first stop through an element: a number, or `null` for where it is. */
514
+ const isFirstStop: Predicate.Predicate<unknown> = /*#__PURE__*/ Predicate.or(Predicate.isNumber, Predicate.isNull)
515
+
516
+ /** Whether `value` is a Batch's key's two stops through an element: a first stop, and a number. */
517
+ const isElementStops = (value: unknown): value is readonly [number | null, number] => {
518
+ if (!isPair(value)) return false
519
+ if (!Predicate.isNumber(value[1])) return false
520
+ return isFirstStop(value[0])
521
+ }
522
+
523
+ /** A Batch's key's stops given through an element (Q34): a number, or two stops, a first `null` where it is. */
524
+ const elementStopsOf = (key: string, value: unknown): number | readonly [number, number] => {
525
+ if (Predicate.isNumber(value)) return value
526
+ if (!isElementStops(value)) {
527
+ return fail(`an animate call gives a member's element "${key}" as ${JSON.stringify(value)}: the Batch draws "${key}", which takes a number, or two stops, its first and its target`)
528
+ }
529
+ if (Predicate.isNull(value[0])) return value[1]
530
+ return value as readonly [number, number]
531
+ }
532
+
533
+ /** What a transform the Batch draws without it says (Q33): its whole `transform` is the Batch's. */
534
+ const drawnKey = (key: string): never => {
535
+ if (key === "transform") {
536
+ return fail(`an animate call gives a member's element "transform": the Batch draws its whole transform from its keys, so give them as keys (x, scale, rotate…) of the Batch`)
537
+ }
538
+ return fail(`an animate call gives a member's element "${key}", a transform the Batch draws without it: make the Batch with "${key}" among its keys, in its \`animate\` or \`initial\``)
539
+ }
540
+
541
+ /** A target split for one Batch's members' elements: the Batch's keys' stops, and the rest, `undefined` when nothing is left. */
542
+ interface MembersSplit<T> {
543
+ readonly batch: WardicBatchTarget
544
+ readonly rest: T | undefined
545
+ }
546
+
547
+ /** `target` split by `routeOf` for a Batch's members' elements; the rest is what a plain element's call would take. */
548
+ const splitFor = <T extends object>(routeOf: (key: string) => KeyRoute, target: T): MembersSplit<T> => {
549
+ const fields = target as Readonly<Record<string, unknown>>
550
+ const batch: Record<string, number | readonly [number, number]> = {}
551
+ const rest: Record<string, unknown> = {}
552
+ let hasRest = false
553
+ Arr.forEach(Rec.keys(fields), (key) => {
554
+ const route = routeOf(key)
555
+ if (route === "drawn") return drawnKey(key)
556
+ if (route === "batch") {
557
+ batch[key] = elementStopsOf(key, fields[key])
558
+ return
559
+ }
560
+ rest[key] = fields[key]
561
+ hasRest = true
562
+ })
563
+ return { batch: batch as WardicBatchTarget, rest: Bool.match(hasRest, { onTrue: () => rest as T, onFalse: () => undefined }) }
564
+ }
565
+
566
+ /** Whether `element` is a Batch member's element: one WeakMap read, so a call without one keeps the plain path. */
567
+ export const isMemberElement = (element: Subject.Subject): boolean => MEMBER_ELEMENTS.has(element)
568
+
569
+ /** `element`'s member's entry, while it's a Batch member's element: its subject in a sequence (Q40). */
570
+ export const memberEntryOf = (element: Subject.Subject): BatchMemberEntry | undefined => MEMBER_ELEMENTS.get(element)
571
+
572
+ /** Whether a sequence's subject is a Batch member's entry. */
573
+ export const isMemberEntry: Predicate.Refinement<unknown, BatchMemberEntry> = /*#__PURE__*/ Predicate.and(/*#__PURE__*/ Predicate.hasProperty("binding"), /*#__PURE__*/ Predicate.hasProperty("member")) as Predicate.Refinement<unknown, BatchMemberEntry>
574
+
575
+ // --- A sequence's Segments of Batches (#665, Q36–Q40) ---------------------------------------------
576
+
577
+ /** A sequence's part for one Batch: its members, in the order they first appear, and each one's compiled animation. */
578
+ export interface SequencePart {
579
+ readonly binding: BatchBinding
580
+ readonly members: ReadonlyArray<number>
581
+ readonly animations: ReadonlyArray<Sequence.Animation>
582
+ }
583
+
584
+ /** `animation` with only the keys `keep` keeps; `undefined` when it keeps none. */
585
+ const keysKept = (animation: Sequence.Animation, keep: (key: string) => boolean): Sequence.Animation | undefined => {
586
+ const keyframes = Rec.filter(animation.keyframes, (_, key) => keep(key))
587
+ if (Rec.isEmptyRecord(keyframes)) return undefined
588
+ return { keyframes, transition: Rec.filter(animation.transition, (_, key) => keep(key)) }
589
+ }
590
+
591
+ /**
592
+ * A compiled sequence's parts (Q40): each Batch's members as one part, in the order they first appear,
593
+ * their Batch keys its; each member's other keys as its element's; every other subject as it is.
594
+ */
595
+ export const sequencePartsOf = <S>(compiled: ReadonlyArray<readonly [S | BatchMemberEntry, Sequence.Animation]>): {
596
+ readonly batches: ReadonlyArray<SequencePart>
597
+ readonly others: ReadonlyArray<readonly [S | Element, Sequence.Animation]>
598
+ } => {
599
+ const byBinding = new Map<BatchBinding, { readonly members: Array<number>; readonly animations: Array<Sequence.Animation> }>()
600
+ const others: Array<readonly [S | Element, Sequence.Animation]> = []
601
+ Arr.forEach(compiled, ([subject, animation]) => {
602
+ if (!isMemberEntry(subject)) {
603
+ others.push([subject as S, animation])
604
+ return
605
+ }
606
+ const { binding, member } = subject
607
+ let part = byBinding.get(binding)
608
+ if (Predicate.isUndefined(part)) {
609
+ part = { members: [], animations: [] }
610
+ byBinding.set(binding, part)
611
+ }
612
+ part.members.push(member)
613
+ part.animations.push(animation)
614
+ // Its keys the Batch doesn't have, its element's: a member element's Segment gave them.
615
+ const rest = keysKept(animation, (key) => binding.routeOf(key) !== "batch")
616
+ const element = binding.elementOf(member)
617
+ if (Bool.and(Predicate.isNotUndefined(rest), Predicate.isNotUndefined(element))) others.push([element as Element, rest as Sequence.Animation])
618
+ })
619
+ return { batches: Arr.map(Arr.fromIterable(byBinding), ([binding, part]): SequencePart => ({ binding, ...part })), others }
620
+ }
621
+
622
+ /**
623
+ * An element call's parts (#665, Q14, Q35): each Batch's member elements as one part, in list order,
624
+ * with the Batch's keys; each element, a member's with the keys left, as one of its own.
625
+ */
626
+ export const callPartsOf = <T extends object>(elements: ReadonlyArray<Element>, target: T): { readonly members: ReadonlyArray<MembersPart>; readonly elements: ReadonlyArray<ElementPart<T>> } => {
627
+ const byBinding = new Map<BatchBinding, { readonly members: Array<number>; readonly split: MembersSplit<T> }>()
628
+ const parts: Array<ElementPart<T>> = []
629
+ Arr.forEach(elements, (element, index) => {
630
+ const entry = MEMBER_ELEMENTS.get(element)
631
+ if (Predicate.isUndefined(entry)) {
632
+ parts.push({ element, index, target })
633
+ return
634
+ }
635
+ let part = byBinding.get(entry.binding)
636
+ if (Predicate.isUndefined(part)) {
637
+ part = { members: [], split: splitFor(entry.binding.routeOf, target) }
638
+ byBinding.set(entry.binding, part)
639
+ }
640
+ part.members.push(entry.member)
641
+ // Its other keys by its place in the list, as a plain element's (Motion's `delay(i, n)`).
642
+ const rest = part.split.rest
643
+ if (Predicate.isNotUndefined(rest)) parts.push({ element, index, target: rest })
644
+ })
645
+ const members = Arr.filter(
646
+ Arr.map(Arr.fromIterable(byBinding), ([binding, part]): MembersPart => ({ binding, members: part.members, target: part.split.batch })),
647
+ (part) => !Rec.isEmptyRecord(part.target as Readonly<Record<string, unknown>>),
648
+ )
649
+ return { members, elements: parts }
650
+ }
651
+
652
+ /** The props an element gives a member's handle: its own `ref`, and its own `style`, as an object. */
653
+ export interface MemberProps<E extends Element, Style> {
654
+ readonly ref?: (el: E) => void
655
+ readonly style?: Style
656
+ }
657
+
658
+ /** A member's handle: spread onto its element. */
659
+ export interface Member<E extends Element, Style> {
660
+ readonly ref: (el: E) => void
661
+ readonly style?: Style | undefined
662
+ }
663
+
664
+ /** What an error about a Batch says. */
665
+ export const fail = (message: string): never => {
666
+ throw new Error(`createBatch: ${message}`)
667
+ }
668
+
669
+ /** Whether `i` is one of `count` members' indices. */
670
+ const isMember = (i: number, count: number): boolean => Number.isInteger(i) && i >= 0 && i < count
671
+
672
+ const noMember = (i: number, count: number): never => fail(`it has no member ${i}: its count is ${count}`)
673
+
674
+ /** Each key's identity: a transform's, and `opacity`'s 1, an element's own with no style of its own. */
675
+ // Per member per key at mount (#540): statements.
676
+ export const identityOf = (key: string): number => {
677
+ const identity = BaseValue.TRANSFORM_IDENTITY[key]
678
+ if (Predicate.isUndefined(identity)) return 1
679
+ return identity
680
+ }
681
+
682
+ /** An `initial` as values, a function's called by `call`, or `undefined` for none (`false` included). */
683
+ const startGiven = <F>(initial: false | WardicBatchValues | F | undefined, call: (made: F) => WardicBatchValues): Readonly<Record<string, unknown>> | undefined => {
684
+ if (Predicate.isUndefined(initial) || initial === false) return undefined
685
+ if (Predicate.isFunction(initial)) return call(initial as F)
686
+ return initial as Readonly<Record<string, unknown>>
687
+ }
688
+
689
+ /** `initial` for member `i`, as values, or `undefined` for none. */
690
+ const initialOf = (config: BatchConfig, i: number): Readonly<Record<string, unknown>> | undefined =>
691
+ startGiven(config.initial, (made: (i: number) => WardicBatchValues) => made(i))
692
+
693
+ /** The keys `count` members give, in the order they first appear: what their first targets and starts name. */
694
+ const keysFrom = (count: number, targetsAt: (i: number) => Readonly<Record<string, unknown>>, startAt: (i: number) => Readonly<Record<string, unknown>> | undefined): ReadonlyArray<string> => {
695
+ const seen = new Set<string>()
696
+ // Per member at the Batch's making, once (#665): a loop over its targets' keys and its start's.
697
+ for (let i = 0; i < count; i++) {
698
+ for (const key in targetsAt(i)) seen.add(key)
699
+ const start = startAt(i)
700
+ if (Predicate.isNotUndefined(start)) for (const key in start) seen.add(key)
701
+ }
702
+ return Arr.fromIterable(seen)
703
+ }
704
+
705
+ /** The keys a Batch's members give by index. */
706
+ const keysOf = (config: BatchConfig): ReadonlyArray<string> =>
707
+ keysFrom(config.count, (i) => config.animate(i) as Readonly<Record<string, unknown>>, (i) => initialOf(config, i))
708
+
709
+ /** One change that lands every key at once: `skipAnimations`'. */
710
+ const INSTANT: Batch.Transition = { type: "tween", duration: 0 }
711
+
712
+ /** A key's index, -1 for a key the Batch hasn't. Built once. */
713
+ const keyIndexOr: (k: number | undefined) => number = /*#__PURE__*/ UndefinedOr.match({ onUndefined: (): number => -1, onDefined: (k: number): number => k })
714
+
715
+ /** A Batch Reorder group's item in hand's change (#712): its `x` and `y` where it's held, at once. */
716
+ const IN_HAND: Batch.RetargetOptions = { transition: { x: INSTANT, y: INSTANT } }
717
+
718
+ /** A sequence's run that lands a key at once after `delay`: `skipAnimations`', and reduced motion's Snap of a positional key. */
719
+ // Module state (#460, Q7): a cache built once, keyed by what it caches.
720
+ const LANDINGS = new Map<number, Machine.KeyframesOptions>()
721
+
722
+ const landingAfter = (delay: number): Machine.KeyframesOptions => {
723
+ const known = LANDINGS.get(delay)
724
+ if (Predicate.isNotUndefined(known)) return known
725
+ const made: Machine.KeyframesOptions = { duration: 0, delay }
726
+ LANDINGS.set(delay, made)
727
+ return made
728
+ }
729
+
730
+ /** A Batch key's stop in a sequence, as core's Batch takes it: a number, `NaN` for `null`. */
731
+ const stopNumber = (stop: Sequence.Stop): number => {
732
+ if (Predicate.isNumber(stop)) return stop
733
+ return Number.NaN
734
+ }
735
+
736
+ /** A key's last stop that's a number, `NaN` (where it is) for none: what its `null`s after it hold. */
737
+ const lastNumber = (stops: ReadonlyArray<number>): number =>
738
+ Option.getOrElse(Arr.findLast(stops, (stop) => !Number.isNaN(stop)), () => Number.NaN)
739
+
740
+ /** Whether `value` is a Batch key's value in a sequence: a number, `null`, or stops of them. */
741
+ const isSegmentStops = (value: unknown): boolean => {
742
+ if (isFirstStop(value)) return true
743
+ if (!Arr.isArray(value)) return false
744
+ return Arr.every(value, isFirstStop)
745
+ }
746
+
747
+ /** A Batch key's value in a sequence (Q38): a number, `null` or stops of them; else an error naming the key, and the member a function gave it. */
748
+ const segmentValueOf = (key: string, value: unknown, memberName: string | undefined): Sequence.Stop | ReadonlyArray<Sequence.Stop> => {
749
+ if (isSegmentStops(value)) return value as Sequence.Stop | ReadonlyArray<Sequence.Stop>
750
+ const whose = UndefinedOr.match(memberName, { onUndefined: () => "", onDefined: (name) => `${name}'s ` })
751
+ return fail(`a sequence gives ${whose}"${key}" as ${JSON.stringify(value)}: a Batch's key takes a number, \`null\`, or stops of them`)
752
+ }
753
+
754
+ /**
755
+ * An `exit`, `whileHover` or `whileTap` given as an object, values with an optional `transition` (Q48,
756
+ * Q58), else `undefined`: a function's values are read as each is needed.
757
+ */
758
+ export const objectFormOf = (given: unknown): WardicBatchGesture | undefined => {
759
+ if (Predicate.isFunction(given)) return undefined
760
+ return given as WardicBatchGesture | undefined
761
+ }
762
+
763
+ /** Such an object's values, less its `transition`; none for a function, or for none given. */
764
+ export const objectFormValues = (given: unknown): Readonly<Record<string, unknown>> =>
765
+ UndefinedOr.match(objectFormOf(given), {
766
+ onUndefined: () => NO_VALUES,
767
+ onDefined: ({ transition: _transition, ...values }) => values,
768
+ })
769
+
770
+ /** Member `i` as an error names it: `nameOf`'s, made only for the error. */
771
+ type NameOf = (i: number) => string
772
+
773
+ /** A member by index as an error names it. */
774
+ const indexName: NameOf = (i) => `member ${i}`
775
+
776
+ /** A keyed member as an error names it, by its key. */
777
+ const keyName = (key: unknown): string => `member ${JSON.stringify(key)}`
778
+
779
+ /**
780
+ * Member `i`'s `values` written as its targets on `keys` into `into` at `base`, `NaN` for a key they
781
+ * leave out: each one of `keys`, and a number, else an error naming it (`nameOf`). The client's at each
782
+ * change, and the server's for a member's start (#665's PR 6).
783
+ */
784
+ // Per member per key at a change (#665): statements, its name made only for an error.
785
+ const targetsOn = (into: Float64Array, base: number, keys: ReadonlyArray<string>, keyIndex: ReadonlyMap<string, number>, values: Readonly<Record<string, unknown>>, nameOf: NameOf, i: number): void => {
786
+ for (let k = 0; k < keys.length; k++) into[base + k] = Number.NaN
787
+ for (const key in values) {
788
+ const k = keyIndex.get(key)
789
+ if (Predicate.isUndefined(k)) return fail(`${nameOf(i)}'s targets give "${key}", which isn't one of its keys (${keys.join(", ")}): a Batch's keys are fixed when it's made`)
790
+ const value = values[key]
791
+ if (Predicate.isNumber(value)) {
792
+ into[base + k] = value
793
+ continue
794
+ }
795
+ if (Predicate.isNotUndefined(value)) fail(`${nameOf(i)}'s "${key}" is ${JSON.stringify(value)}: a Batch's targets are numbers, one each`)
796
+ }
797
+ }
798
+
799
+ /**
800
+ * Member `i`'s start on `keys` (Q63): `given`'s value for each key it gives, else its target in `targets`
801
+ * at `base` when it starts at its targets, else the key's identity; a key it gives that isn't one of
802
+ * `keys`, or a value that isn't a number, is an error naming it (`nameOf`). The client's as a member
803
+ * enters, and the server's.
804
+ */
805
+ // Per member at mount (#540): statements, its name made only for an error.
806
+ const startOn = (
807
+ keys: ReadonlyArray<string>,
808
+ keyIndex: ReadonlyMap<string, number>,
809
+ given: Readonly<Record<string, unknown>> | undefined,
810
+ targets: Float64Array,
811
+ base: number,
812
+ atTargets: boolean,
813
+ nameOf: NameOf,
814
+ i: number,
815
+ ): Record<string, number> => {
816
+ const start: Record<string, number> = {}
817
+ if (Predicate.isNotUndefined(given)) {
818
+ for (const key in given) {
819
+ if (!keyIndex.has(key)) fail(`${nameOf(i)} starts at "${key}", which isn't one of its keys (${keys.join(", ")}): a Batch's keys are fixed when it's made`)
820
+ }
821
+ }
822
+ Arr.forEach(keys, (key, k) => {
823
+ const target = targets[base + k]
824
+ let value = identityOf(key)
825
+ if (atTargets && !Number.isNaN(target)) value = target
826
+ if (Predicate.isNotUndefined(given)) {
827
+ const own = given[key]
828
+ if (Predicate.isNumber(own)) value = own
829
+ if (Predicate.isNotUndefined(own) && !Predicate.isNumber(own)) fail(`${nameOf(i)}'s "${key}" starts at ${JSON.stringify(own)}: a Batch's values are numbers`)
830
+ }
831
+ start[key] = value
832
+ })
833
+ return start
834
+ }
835
+
836
+ /**
837
+ * A Batch's keys: `given`, with those its `exit`, `whileHover` and `whileTap` objects give as values after
838
+ * them (Q48, Q58), and a Batch Reorder group's `whileDrag` (#712), and its function gestures' by
839
+ * `firstGestures`, their values for the list's first item (Q27, Q34); with `keys` given (`fixed`), one
840
+ * outside them is an error naming it.
841
+ */
842
+ const withConfigKeys = (
843
+ given: ReadonlyArray<string>,
844
+ fixed: boolean,
845
+ config: BatchConfig | KeyedBatchConfig<unknown>,
846
+ firstGestures: Readonly<Record<string, unknown>> = NO_VALUES,
847
+ ): ReadonlyArray<string> => {
848
+ let all = given
849
+ const more: ReadonlyArray<readonly [string, Readonly<Record<string, unknown>>]> = [
850
+ ["exit", objectFormValues((config as { readonly exit?: unknown }).exit)],
851
+ ["whileHover", objectFormValues((config as { readonly whileHover?: unknown }).whileHover)],
852
+ ["whileTap", objectFormValues((config as { readonly whileTap?: unknown }).whileTap)],
853
+ ["whileDrag", objectFormValues((config as { readonly whileDrag?: unknown }).whileDrag)],
854
+ ["function whileHover, whileTap or whileDrag", firstGestures],
855
+ ]
856
+ Arr.forEach(more, ([name, values]) => {
857
+ const added = Arr.filter(Rec.keys(values), (key) => !Arr.contains(all, key))
858
+ if (added.length === 0) return
859
+ if (fixed) fail(`its \`${name}\` gives "${added[0]}", which isn't one of its \`keys\` (${given.join(", ")})`)
860
+ all = [...all, ...added]
861
+ })
862
+ return all
863
+ }
864
+
865
+ /** The properties a Batch on `keys` draws on its members' elements: `transform`, with a transform key, and `opacity`, with it. */
866
+ const drawnBy = (keys: ReadonlyArray<string>): ReadonlySet<string> =>
867
+ new Set([...Arr.filter(["transform"], () => Arr.some(keys, (key) => key !== "opacity")), ...Arr.filter(["opacity"], () => Arr.contains(keys, "opacity"))])
868
+
869
+ /** A member's own `style`, without the properties the Batch draws (`drawn`): a string's an error, its binding writing it over them. */
870
+ const ownStyleOf = <Style>(style: Style, drawn: ReadonlySet<string>): Style => {
871
+ if (Predicate.isString(style)) {
872
+ return fail(`give a member's own \`style\` as an object: a string is written over what the Batch draws`)
873
+ }
874
+ if (!Predicate.isObject(style)) return style
875
+ return Rec.filter(style as Readonly<Record<string, unknown>>, (_, name) => !drawn.has(name)) as Style
876
+ }
877
+
878
+ /** Two items with one key: an error naming both. */
879
+ const twoWithKey = (first: number, second: number, key: unknown): never => fail(`items ${first} and ${second} both have the key ${JSON.stringify(key)}: each item's key is its own`)
880
+
881
+ /** A member's slot before its element arrives. */
882
+ const NO_SLOT = -1
883
+
884
+ /** A key a writer draws nothing for: a group a Wardic element holds (#665's PR 4). */
885
+ const UNDRAWN = "~undrawn"
886
+
887
+ /** Each group's bit in a held element's mask: the groups a Wardic element on it holds, which its Batch doesn't draw. */
888
+ const GROUP_BITS: Readonly<Record<BatchGroup, number>> = { transform: 1, opacity: 2 }
889
+
890
+ /** A member's groups a Wardic element on its element holds (#665's PR 4): that element, and each group's holder. */
891
+ interface HeldMember {
892
+ readonly el: Element
893
+ readonly groups: Map<BatchGroup, BatchHolder>
894
+ }
895
+
896
+ /** Where a change starts a member's handed keys from, and at what speeds (Q54). */
897
+ type HandedStarts = Pick<Batch.RetargetOptions, "from" | "velocity">
898
+
899
+ /** An element as an error names it: its tag, then its `id` and first class, as `div#card.tile`. */
900
+ export const elementName = (el: Element): string => {
901
+ let name = el.tagName.toLowerCase()
902
+ if (el.id !== "") name = `${name}#${el.id}`
903
+ const first = el.classList.item(0)
904
+ if (Predicate.isNotNull(first)) name = `${name}.${first}`
905
+ return name
906
+ }
907
+
908
+ /** The elements a Wardic element has a layout node on: a Batch member's can have none (Q52). */
909
+ // Module state (#460, Q7): held weakly by the element, so it goes with it.
910
+ const LAYOUT_ELEMENTS = new WeakSet<Element>()
911
+
912
+ /**
913
+ * `element` given a layout node (#665's PR 4, Q52): an error when it's a Batch member's, whose
914
+ * transform its Batch draws, under which the projection would measure it.
915
+ */
916
+ export const markLayoutElement = (element: Element): void => {
917
+ if (MEMBER_ELEMENTS.has(element)) return fail(layoutOnMember(element))
918
+ LAYOUT_ELEMENTS.add(element)
919
+ }
920
+
921
+ /** The error for a layout node on a Batch member's element. */
922
+ const layoutOnMember = (element: Element): string =>
923
+ `a member's element (${elementName(element)}) has \`layout\` or \`layoutId\`: the Batch draws its transform, under which the projection measures it. Give its Wardic element no layout, or leave it out of the Batch`
924
+
925
+ /** No values: an exit with none, which moves nothing and lets its element go at once. */
926
+ const NO_VALUES: Readonly<Record<string, unknown>> = {}
927
+
928
+ /** Whether `value` is two stops. */
929
+ const isPair = (value: unknown): value is readonly [unknown, unknown] => {
930
+ if (!Arr.isArray(value)) return false
931
+ return value.length === 2
932
+ }
933
+
934
+ /** Reduced motion's Snap after `delay`: a 0 s tween, kept by its delay so its keys share one. */
935
+ // Module state (#460, Q7): a cache built once, keyed by what it caches.
936
+ const SNAPS = new Map<number, Batch.Transition>()
937
+
938
+ const snapAfter = (delay: number): Batch.Transition => {
939
+ const known = SNAPS.get(delay)
940
+ if (Predicate.isNotUndefined(known)) return known
941
+ const made: Batch.Transition = { type: "tween", duration: 0, delay }
942
+ SNAPS.set(delay, made)
943
+ return made
944
+ }
945
+
946
+ /**
947
+ * A Default transition held by a key's own `delay`, as a Wardic element's is when its transition gives
948
+ * only a delay (ADR-0051): one object for each transition and delay, so the members on it share it.
949
+ */
950
+ // Module state (#460, Q7): a cache held weakly by the object it's for, so it goes with it.
951
+ const DELAYED = new WeakMap<object, Map<number, Batch.Transition>>()
952
+
953
+ const delayedBy = (transition: Batch.Transition, delay: number): Batch.Transition => {
954
+ if (delay === 0) return transition
955
+ let byDelay = DELAYED.get(transition)
956
+ if (Predicate.isUndefined(byDelay)) {
957
+ byDelay = new Map()
958
+ DELAYED.set(transition, byDelay)
959
+ }
960
+ const known = byDelay.get(delay)
961
+ if (Predicate.isNotUndefined(known)) return known
962
+ const made = { ...transition, delay } as Batch.Transition
963
+ byDelay.set(delay, made)
964
+ return made
965
+ }
966
+
967
+ /**
968
+ * A transition without a `stagger()` delay, which a change gives each member by its place: one object
969
+ * each. A `delay` in seconds stays, held by the keys the transition's own fields reach, as a Wardic
970
+ * element's top-level delay is.
971
+ */
972
+ // Module state (#460, Q7): a cache held weakly by the object it's for, so it goes with it.
973
+ const UNSTAGGERED = new WeakMap<object, WardConfig.WardicTransition>()
974
+
975
+ const unstaggered = (given: WardicBatchTransition | WardConfig.WardicTransition): WardConfig.WardicTransition => {
976
+ if (!Predicate.isFunction(given.delay)) return given as WardConfig.WardicTransition
977
+ const known = UNSTAGGERED.get(given)
978
+ if (Predicate.isNotUndefined(known)) return known
979
+ const made = { ...given, delay: undefined } as unknown as WardConfig.WardicTransition
980
+ UNSTAGGERED.set(given, made)
981
+ return made
982
+ }
983
+
984
+ /** A change's `stagger()` delay, for the members it moves; `undefined` for none. */
985
+ const staggerOf = (given: WardConfig.WardicTransition | undefined): ((rank: number, n: number) => number) | undefined => {
986
+ if (Predicate.isUndefined(given)) return undefined
987
+ const delay: unknown = given.delay
988
+ if (Predicate.isFunction(delay)) return delay as (rank: number, n: number) => number
989
+ return undefined
990
+ }
991
+
992
+ /** A key's transition as a Batch runs it: its run, which can't be an inertia or repeat. */
993
+ const batchRunOf = (run: RetargetLegs.Run, key: string): Batch.Transition => {
994
+ if (run.type === "inertia") fail(`"${key}" has an inertia transition, which a Batch can't run: give it a spring or a tween`)
995
+ if (Predicate.hasProperty(run, "repeat")) fail(`"${key}"'s transition repeats, which a Batch can't run`)
996
+ return run as Batch.Transition
997
+ }
998
+
999
+ /** A change's plan for one key: its own transition, or `undefined` for its Default transition held by `delay`. */
1000
+ interface KeyPlan {
1001
+ readonly own: Batch.Transition | undefined
1002
+ readonly delay: number
1003
+ }
1004
+
1005
+ /**
1006
+ * Each key's plan for a change, by its index, as a Wardic element's keys run (#301): its entry, else
1007
+ * `default`, else the transition's own fields; reduced motion's Snap for a positional key that doesn't
1008
+ * opt out; its Default transition, held by its own `delay`, for a key whose transition isn't defined.
1009
+ */
1010
+ // Once a change, per key.
1011
+ const plannedOf = (positional: ReducedMotion.PositionalKeys["Service"], keys: ReadonlyArray<string>, given: WardConfig.WardicTransition | undefined, reduced: boolean): ReadonlyArray<KeyPlan> =>
1012
+ Arr.map(keys, (key): KeyPlan => {
1013
+ const transition = RetargetLegs.transitionForKey(given, key)
1014
+ let delay = 0
1015
+ let respects = true
1016
+ if (Predicate.isNotUndefined(transition)) {
1017
+ if (Predicate.isNumber(transition.delay)) delay = transition.delay
1018
+ respects = transition.respectReducedMotion !== false
1019
+ }
1020
+ if (reduced && respects && positional.isPositional(key)) return { own: snapAfter(delay), delay }
1021
+ const run = RetargetLegs.runOf(transition)
1022
+ if (Predicate.isUndefined(run)) return { own: undefined, delay }
1023
+ return { own: batchRunOf(run, key), delay }
1024
+ })
1025
+
1026
+ /**
1027
+ * A member's transitions on `keys` for a change planned as `planned`: each key's own, else its Default
1028
+ * transition (`defaultFor`) toward its target there, `targetAt(k)`; every key at once when it's skipped.
1029
+ * A server's Appear plan's (#706) and a client's check of it.
1030
+ */
1031
+ // Per member per key, at a server's render and at a hydrating client's first change (#706): statements.
1032
+ const memberTransitionsOf = (
1033
+ keys: ReadonlyArray<string>,
1034
+ planned: ReadonlyArray<KeyPlan>,
1035
+ defaultFor: (key: string, target: number) => Batch.Transition,
1036
+ targetAt: (k: number) => number,
1037
+ skipped: boolean,
1038
+ ): ReadonlyArray<Batch.Transition> =>
1039
+ Arr.map(keys, (key, k) => {
1040
+ if (skipped) return INSTANT
1041
+ const plan = planned[k] as KeyPlan
1042
+ if (Predicate.isNotUndefined(plan.own)) return plan.own
1043
+ return delayedBy(defaultFor(key, targetAt(k)), plan.delay)
1044
+ })
1045
+
1046
+ /** The Handoff's module, once it has loaded (#706, Q11): every Batch after the first takes its members over at once. */
1047
+ // Module state (#460, Q7): one module, loaded once for the page.
1048
+ let handoffModule: typeof import("../internal/batch-handoff.ts") | undefined = undefined
1049
+ // Module state (#460, Q7): its load, settled once, never rejected: a failed load reported, and nothing taken over.
1050
+ let loadingHandoff: Promise<typeof import("../internal/batch-handoff.ts") | undefined> | undefined = undefined
1051
+
1052
+ /** The Handoff's module's load, started at its first need; a failure reported on `runtime`. */
1053
+ const loadHandoff = (runtime: WardicServices.Runner<WardicServices.WardicServices>): Promise<typeof import("../internal/batch-handoff.ts") | undefined> => {
1054
+ if (Predicate.isUndefined(loadingHandoff)) {
1055
+ loadingHandoff = import("../internal/batch-handoff.ts").then(
1056
+ (module) => {
1057
+ handoffModule = module
1058
+ return module
1059
+ },
1060
+ (error: unknown) => {
1061
+ // Let a later Batch try again.
1062
+ loadingHandoff = undefined
1063
+ runtime.runFork(Report.failure("wardic: a Batch's Handoff code failed to load; its members' Appear animations are let go", Cause.die(error)))
1064
+ return undefined
1065
+ },
1066
+ )
1067
+ }
1068
+ return loadingHandoff
1069
+ }
1070
+
1071
+ // --- A server render's start (#665's PR 6, ADR-0070 decision 14, Q63–Q67) ----------------------------
1072
+
1073
+ /** A keyed member's `initial` for its item and index: values, a function's, or `undefined` for none or `false`. */
1074
+ const keyedInitialOf = (config: KeyedBatchConfig<unknown>, item: unknown, i: number): Readonly<Record<string, unknown>> | undefined =>
1075
+ startGiven(config.initial, (given: (item: unknown, i: number) => WardicBatchValues) => given(item, i))
1076
+
1077
+ /**
1078
+ * A spread member's handle on a server: no `ref` to run, and its `start` drawn as the DOM writer draws it,
1079
+ * over its own `style` less the properties the Batch draws (`drawn`). The client draws the same values as
1080
+ * the member arrives, so its element doesn't move at hydration. Its element's own `style` is the handle's:
1081
+ * a `style` beside the spread is replaced by the one it carries, as Solid's spread lets the later win.
1082
+ */
1083
+ const serverMemberOf = <E extends Element, Style>(
1084
+ start: Readonly<Record<string, number>> | undefined,
1085
+ drawn: ReadonlySet<string>,
1086
+ props: MemberProps<E, Style> | undefined,
1087
+ appear: ServerMemberAppear = NO_MEMBER_APPEAR,
1088
+ ): Member<E, Style> => {
1089
+ const own = ownStyleOf(UndefinedOr.map(props, (given) => given.style), drawn)
1090
+ const started = UndefinedOr.match(start, { onUndefined: () => NO_STYLE, onDefined: DomBatch.styleOf })
1091
+ /** The member's handle, its own style under what the Batch writes. */
1092
+ const writing = (written: Readonly<Record<string, string>>): Member<E, Style> => {
1093
+ if (Bool.and(Predicate.isUndefined(own), Rec.isEmptyRecord(written))) return { ref: noop }
1094
+ return { ref: noop, style: { ...(own as object | undefined), ...written } as Style }
1095
+ }
1096
+ // Its Appear animation (#706) over its start, unless its own style sets an `animation`, which it keeps
1097
+ // (Q4): then its group's rule isn't asked for on its account.
1098
+ if (AppearAnimations.setsAnimation(own as object | string | undefined)) {
1099
+ appear.vetoed()
1100
+ return writing(started)
1101
+ }
1102
+ return writing(UndefinedOr.match(appear.style(), { onUndefined: () => started, onDefined: (style) => ({ ...started, ...style }) }))
1103
+ }
1104
+
1105
+ /** A member's Appear animation on a server (#706): its style, and what says it waits when its own style vetoes it. */
1106
+ interface ServerMemberAppear {
1107
+ /** Its style, its group's rule sampled at the first ask: asked only when its own style doesn't veto it. */
1108
+ readonly style: () => Readonly<Record<string, string>> | undefined
1109
+ /** Its own style sets an `animation`: said, once, where it would have played one. */
1110
+ readonly vetoed: () => void
1111
+ }
1112
+
1113
+ /** No Appear animation. */
1114
+ const NO_MEMBER_APPEAR: ServerMemberAppear = { style: () => undefined, vetoed: () => {} }
1115
+
1116
+ /** No style of the Batch's to write. */
1117
+ const NO_STYLE: Readonly<Record<string, string>> = {}
1118
+
1119
+ /** Its keys checked as the client's `Batch.make` checks them: a key the DOM's writer doesn't draw is its error. */
1120
+ const checkedOnServer = (keys: ReadonlyArray<string>): void => {
1121
+ Batch.make({ keys, writer: DomBatch.writer, transition: { type: "spring" }, capacity: 1 })
1122
+ }
1123
+
1124
+ /** A server Batch's keys, by index, their drawn properties, and room for one member's targets. */
1125
+ interface ServerKeys {
1126
+ readonly keys: ReadonlyArray<string>
1127
+ readonly keyIndex: ReadonlyMap<string, number>
1128
+ readonly drawn: ReadonlySet<string>
1129
+ readonly targets: Float64Array
1130
+ }
1131
+
1132
+ /** `keys` as a server Batch reads them, checked as the client's are. */
1133
+ const serverKeysOf = (keys: ReadonlyArray<string>): ServerKeys => {
1134
+ checkedOnServer(keys)
1135
+ return { keys, keyIndex: new Map(Arr.map(keys, (key, k) => [key, k] as const)), drawn: drawnBy(keys), targets: new Float64Array(keys.length) }
1136
+ }
1137
+
1138
+ // --- A server render's Appear animations (#706, ADR-0044 *Amendment (#706)*) -------------------------
1139
+
1140
+ /** What a server render's Batch reads of its provider and its nearest `WardicConfig` for its members' Appear animations (#706). */
1141
+ export interface BatchServerAppear {
1142
+ /** The render's Appear animations: none with the provider's `appear={false}`, or no provider. */
1143
+ readonly state: AppearAnimations.ServerAppear | undefined
1144
+ /** Its nearest `WardicConfig`'s reduced motion, else `undefined` for the provider's (#434). */
1145
+ readonly setting: ReducedMotion.Config | undefined
1146
+ /** Whether its nearest `WardicConfig` skips its animations (#468). */
1147
+ readonly skipped: boolean
1148
+ /** Its nearest `WardicConfig`'s transition, for a Batch with none of its own. */
1149
+ readonly configTransition: WardConfig.WardicTransition | undefined
1150
+ }
1151
+
1152
+ /** A server Batch's read of its provider's Appear animations and its nearest `WardicConfig` (#706): each binding's hooks give them. */
1153
+ export const batchServerAppearOf = (state: AppearAnimations.ServerAppear | undefined, config: WardicConfigValue.WardicConfigValue | undefined, skipped: boolean): BatchServerAppear => ({
1154
+ state,
1155
+ setting: WardicConfigValue.settingOf(config),
1156
+ skipped,
1157
+ configTransition: configTransitionOf(config)(),
1158
+ })
1159
+
1160
+ /** No Appear animations: a server render's Batch that's given none. */
1161
+ export const NO_SERVER_APPEAR: BatchServerAppear = { state: undefined, setting: undefined, skipped: false, configTransition: undefined }
1162
+
1163
+ /** The DOM's Positional keys, which a server's reduced rule snaps, as an element's (ADR-0029). */
1164
+ const SERVER_POSITIONAL: ReducedMotion.PositionalKeys["Service"] = { isPositional: DomPositionalKeys.isPositional }
1165
+
1166
+ /** The DOM's Default transition, which a server samples a key with no transition defined on, as the client runs it (ADR-0051). */
1167
+ const serverDefaultFor = (key: string, target: number): Batch.Transition => DomDefaultTransition.transitionFor(key, target) as Batch.Transition
1168
+
1169
+ /** `startAt`, as a change's options take it: none without one. */
1170
+ const startAtOption = (startAt: ((slot: number) => number) | undefined): Pick<Batch.RetargetOptions, "startAt"> =>
1171
+ UndefinedOr.match(startAt, { onUndefined: () => ({}), onDefined: (given) => ({ startAt: given }) })
1172
+
1173
+ /** A member on a server: its start, and its start and targets a number a key, a key its targets leave out at its start. */
1174
+ interface ServerMember {
1175
+ readonly start: Record<string, number>
1176
+ readonly from: ReadonlyArray<number>
1177
+ readonly to: ReadonlyArray<number>
1178
+ }
1179
+
1180
+ /** A target, or `start` for a key the targets leave out (`NaN`): a key a change keeps where it is. */
1181
+ // Per member per key at a server's render: statements.
1182
+ const targetOr = (target: number, start: number): number => {
1183
+ if (Number.isNaN(target)) return start
1184
+ return target
1185
+ }
1186
+
1187
+ /** A member's values on a server, from its start and its targets as `targetsOn` wrote them into `targets`. */
1188
+ const serverMemberValuesOf = (keys: ReadonlyArray<string>, start: Record<string, number>, targets: Float64Array): ServerMember => {
1189
+ const from = Arr.map(keys, (key) => start[key] as number)
1190
+ return { start, from, to: Arr.map(from, (value, k) => targetOr(targets[k] as number, value)) }
1191
+ }
1192
+
1193
+ /** Whether a member moves: some key's start isn't its target. */
1194
+ const movesFrom = (member: ServerMember): boolean => Arr.some(member.from, (value, k) => value !== member.to[k])
1195
+
1196
+ /** A Batch's members on one set of transitions, on a server: one rule for them, and its reduced one, registered as its first member asks. */
1197
+ interface RuleGroup {
1198
+ readonly key: string
1199
+ readonly transitions: Batch.Transitions
1200
+ readonly reduced: { readonly key: string; readonly transitions: Batch.Transitions } | undefined
1201
+ readonly members: Array<number>
1202
+ slot: Option.Option<Appear.BatchSlot> | undefined
1203
+ }
1204
+
1205
+ /** Each key's transition, by its name. */
1206
+ const byKey = (keys: ReadonlyArray<string>, transitions: ReadonlyArray<Batch.Transition>): Batch.Transitions =>
1207
+ Rec.fromEntries(Arr.map(keys, (key, k) => [key, transitions[k] as Batch.Transition] as const))
1208
+
1209
+ /**
1210
+ * `batchKeyOf` remembered by its transitions' identities, for one Batch's members at a server's render: a
1211
+ * set of transitions' canonical text written once.
1212
+ */
1213
+ const ruleKeyMemo = (keys: ReadonlyArray<string>) => {
1214
+ const ids = new WeakMap<object, number>()
1215
+ let next = 0
1216
+ const known = new Map<string, Option.Option<string>>()
1217
+ /** A transition's number among those seen. */
1218
+ const idOf = (transition: object): number => {
1219
+ const seen = ids.get(transition)
1220
+ if (Predicate.isNotUndefined(seen)) return seen
1221
+ const made = next
1222
+ next++
1223
+ ids.set(transition, made)
1224
+ return made
1225
+ }
1226
+ // Per member at a server's render: its transitions' numbers, its key written the first time they come.
1227
+ return (transitions: ReadonlyArray<Batch.Transition>, reduced: boolean, skipped: boolean): Option.Option<string> => {
1228
+ const signature = `${Arr.map(transitions, idOf).join(",")}|${reduced}|${skipped}`
1229
+ const seen = known.get(signature)
1230
+ if (Predicate.isNotUndefined(seen)) return seen
1231
+ const made = AppearAnimations.batchKeyOf(keys, transitions, reduced, skipped)
1232
+ known.set(signature, made)
1233
+ return made
1234
+ }
1235
+ }
1236
+
1237
+ /** A server Batch's members' Appear styles, by member, and whether each plays one. */
1238
+ interface MemberStyles {
1239
+ readonly styleAt: (i: number) => Readonly<Record<string, string>> | undefined
1240
+ readonly plays: (i: number) => boolean
1241
+ }
1242
+
1243
+ /** No Appear animation for any member. */
1244
+ const NO_STYLES: MemberStyles = { styleAt: () => undefined, plays: () => false }
1245
+
1246
+ /**
1247
+ * A server Batch's members' Appear styles (#706, Q1–Q6, Q21: with its `appear: true`), by member: its own values, its group's slot and
1248
+ * its delay, or `undefined` for one that plays none. Its members on one set of transitions share a rule,
1249
+ * planned as the client plans its first change, by its setting: `"never"` the normal one, `"always"` the
1250
+ * reduced one, `"user"` both, the reduced under the media query; skipped, every key at once (#468). A
1251
+ * group's rules go to the render's sheet as its first member asks, so a Batch none of whose members renders
1252
+ * one writes none. Each member's delay is its stagger by its rank among the members that move, as the
1253
+ * client counts them. Why it plays none is said when the provider explains (#585).
1254
+ */
1255
+ // Once a Batch at a server's render, a loop over its members (#665's per-member site): with it, 1,000
1256
+ // members rendered in 5.5 ms, against 1.15 ms without (4.3 µs a member; #706, measured in Node).
1257
+ const serverAppearStylesOf = (
1258
+ server: BatchServerAppear,
1259
+ state: AppearAnimations.ServerAppear,
1260
+ config: BatchConfig | KeyedBatchConfig<unknown>,
1261
+ keys: ReadonlyArray<string>,
1262
+ members: ReadonlyArray<ServerMember>,
1263
+ ): MemberStyles => {
1264
+ const name = `a Batch (${keys.join(", ")})`
1265
+ const moving = Arr.map(members, movesFrom)
1266
+ const movers = Arr.reduce(moving, 0, (count, moves) => count + Number(moves))
1267
+ if (movers === 0) {
1268
+ state.waits(name, "no member moves from its start")
1269
+ return NO_STYLES
1270
+ }
1271
+ let configured = config.transition as WardConfig.WardicTransition | undefined
1272
+ if (Predicate.isUndefined(configured)) configured = server.configTransition
1273
+ const skipped = Bool.or(server.skipped, UndefinedOr.map(configured, (given) => given.skipAnimations) === true)
1274
+ let setting = server.setting
1275
+ if (Predicate.isUndefined(setting)) setting = state.reducedMotion
1276
+ const plain = UndefinedOr.map(configured, unstaggered)
1277
+ const normal = plannedOf(SERVER_POSITIONAL, keys, plain, false)
1278
+ const reduced = plannedOf(SERVER_POSITIONAL, keys, plain, true)
1279
+ // The play each member's rule draws, and under `"user"` the reduced one beside it.
1280
+ const reducedAlways = Bool.and(setting === "always", Bool.not(skipped))
1281
+ let play = normal
1282
+ if (reducedAlways) play = reduced
1283
+ const reducedBeside = Bool.and(setting === "user", Bool.not(skipped))
1284
+ let stagger = staggerOf(configured)
1285
+ if (skipped) stagger = undefined
1286
+ // Each member's key by its transitions' identities: members on the same transitions share the objects
1287
+ // (`delayedBy`'s, the Default transitions'), so their canonical text is written once, not once a member.
1288
+ const ruleKeyOf = ruleKeyMemo(keys)
1289
+ const groups = new Map<string, RuleGroup>()
1290
+ const groupOf: Array<RuleGroup | undefined> = []
1291
+ const indexInGroup: Array<number> = []
1292
+ const delays: Array<number> = []
1293
+ let rank = 0
1294
+ for (let i = 0; i < members.length; i++) {
1295
+ if (!moving[i]) continue
1296
+ const member = members[i] as ServerMember
1297
+ const transitions = memberTransitionsOf(keys, play, serverDefaultFor, (k) => member.to[k] as number, skipped)
1298
+ const key = ruleKeyOf(transitions, reducedAlways, skipped)
1299
+ if (Option.isNone(key)) {
1300
+ state.waits(name, "its transition holds a function with no easing name")
1301
+ return NO_STYLES
1302
+ }
1303
+ let group = groups.get(key.value)
1304
+ if (Predicate.isUndefined(group)) {
1305
+ let reducedRule: RuleGroup["reduced"] = undefined
1306
+ if (reducedBeside) {
1307
+ const reducedTransitions = memberTransitionsOf(keys, reduced, serverDefaultFor, (k) => member.to[k] as number, false)
1308
+ reducedRule = { key: Option.getOrThrow(AppearAnimations.batchKeyOf(keys, reducedTransitions, true, false)), transitions: byKey(keys, reducedTransitions) }
1309
+ }
1310
+ group = { key: key.value, transitions: byKey(keys, transitions), reduced: reducedRule, members: [], slot: undefined }
1311
+ groups.set(key.value, group)
1312
+ }
1313
+ groupOf[i] = group
1314
+ indexInGroup[i] = group.members.length
1315
+ group.members.push(i)
1316
+ let delay = 0
1317
+ if (Predicate.isNotUndefined(stagger)) delay = stagger(rank, movers)
1318
+ delays[i] = delay
1319
+ rank++
1320
+ }
1321
+ /** A group's slot: its rules sampled and registered at its first member's ask, or `None` when one can't be. */
1322
+ const slotOf = (group: RuleGroup): Option.Option<Appear.BatchSlot> => {
1323
+ if (Predicate.isNotUndefined(group.slot)) return group.slot
1324
+ const specOf = (key: string, transitions: Batch.Transitions): Appear.BatchSpec => ({
1325
+ key,
1326
+ keys,
1327
+ transition: transitions,
1328
+ starts: Arr.map(group.members, (i) => (members[i] as ServerMember).from),
1329
+ targets: Arr.map(group.members, (i) => (members[i] as ServerMember).to),
1330
+ })
1331
+ const rule = Appear.batchKeyframes(specOf(group.key, group.transitions))
1332
+ const reducedRule = UndefinedOr.map(group.reduced, (r) => Appear.batchKeyframes(specOf(r.key, r.transitions)))
1333
+ const failure = Option.orElse(Result.getFailure(rule), () => Option.flatMap(Option.fromUndefinedOr(reducedRule), Result.getFailure))
1334
+ if (Option.isSome(failure)) {
1335
+ state.waits(name, failure.value)
1336
+ group.slot = Option.none()
1337
+ return group.slot
1338
+ }
1339
+ group.slot = Option.some(state.batch(Result.getOrThrow(rule), UndefinedOr.map(reducedRule, Result.getOrThrow)))
1340
+ return group.slot
1341
+ }
1342
+ return {
1343
+ styleAt: (i) => {
1344
+ const group = groupOf[i]
1345
+ if (Predicate.isUndefined(group)) return undefined
1346
+ return Option.getOrUndefined(Option.flatMap(slotOf(group), (slot) => Option.fromUndefinedOr(slot.styleOf(indexInGroup[i] as number, delays[i] as number))))
1347
+ },
1348
+ plays: (i) => Predicate.isNotUndefined(groupOf[i]),
1349
+ }
1350
+ }
1351
+
1352
+ /**
1353
+ * Each member's Appear animation on a server, by its index: its style, made once, and, when its own style
1354
+ * vetoes it, the provider's explanation, once a member (Solid's spread calls a handle once for each prop it
1355
+ * reads).
1356
+ */
1357
+ const memberAppearsOf = (state: AppearAnimations.ServerAppear, styles: MemberStyles, nameOf: NameOf) => {
1358
+ const said = new Set<number>()
1359
+ // Each member's style, made once: Solid's spread calls its handle once for each prop it reads.
1360
+ const made = new Map<number, Readonly<Record<string, string>> | undefined>()
1361
+ const styleOnce = (i: number): Readonly<Record<string, string>> | undefined => {
1362
+ if (made.has(i)) return made.get(i)
1363
+ const style = styles.styleAt(i)
1364
+ made.set(i, style)
1365
+ return style
1366
+ }
1367
+ return (i: number): ServerMemberAppear => ({
1368
+ style: () => styleOnce(i),
1369
+ vetoed: () => {
1370
+ if (Bool.or(Bool.not(styles.plays(i)), said.has(i))) return
1371
+ said.add(i)
1372
+ state.waits(`a Batch's ${nameOf(i)}`, "its own style sets an animation")
1373
+ },
1374
+ })
1375
+ }
1376
+
1377
+ /** A server render's members and their Appear animations: each member's values, and its Appear. */
1378
+ interface ServerMembers {
1379
+ readonly memberAt: (i: number) => ServerMember
1380
+ readonly appearOf: (i: number) => ServerMemberAppear
1381
+ }
1382
+
1383
+ /**
1384
+ * A server Batch's members (#706): with its `appear: true` (Q21) and a render that writes Appear
1385
+ * animations, every member read up front, as a rule is its group's and a delay its rank's; else each as
1386
+ * its handle asks, and none plays one.
1387
+ */
1388
+ const serverMembersOf = (
1389
+ server: BatchServerAppear,
1390
+ config: BatchConfig | KeyedBatchConfig<unknown>,
1391
+ keys: ReadonlyArray<string>,
1392
+ count: number,
1393
+ memberAt: (i: number) => ServerMember,
1394
+ nameOf: NameOf,
1395
+ ): ServerMembers => {
1396
+ const plain: ServerMembers = { memberAt, appearOf: () => NO_MEMBER_APPEAR }
1397
+ const state = server.state
1398
+ if (Predicate.isUndefined(state)) return plain
1399
+ if (config.appear !== true) return plain
1400
+ const members = Arr.makeBy(count, memberAt)
1401
+ return { memberAt: (i) => members[i] as ServerMember, appearOf: memberAppearsOf(state, serverAppearStylesOf(server, state, config, keys, members), nameOf) }
1402
+ }
1403
+
1404
+ /**
1405
+ * A server render's handles by index (Q63): each member's start, its `initial`'s values, its targets
1406
+ * with `initial: false`, else nothing, on the keys the client makes it with, its checks the client's.
1407
+ */
1408
+ export const serverHandlesOf = <Style>(config: BatchConfig, server: BatchServerAppear = NO_SERVER_APPEAR) => {
1409
+ const { keys, keyIndex, drawn, targets } = serverKeysOf(withConfigKeys(keysOf(config), false, config))
1410
+ const memberAt = (i: number): ServerMember => {
1411
+ targetsOn(targets, 0, keys, keyIndex, config.animate(i) as Readonly<Record<string, unknown>>, indexName, i)
1412
+ return serverMemberValuesOf(keys, startOn(keys, keyIndex, initialOf(config, i), targets, 0, config.initial === false, indexName, i), targets)
1413
+ }
1414
+ const members = serverMembersOf(server, config, keys, config.count, memberAt, indexName)
1415
+ return <E extends Element>(i: number, props?: MemberProps<E, Style>): Member<E, Style> => {
1416
+ if (!isMember(i, config.count)) return noMember(i, config.count)
1417
+ return serverMemberOf(members.memberAt(i).start, drawn, props, members.appearOf(i))
1418
+ }
1419
+ }
1420
+
1421
+ /**
1422
+ * A server render's keyed handles (Q63, Q65): the list read once, each key's member started by its item
1423
+ * and its index there, its targets under `<AnimatePresence initial={false}>`; a key the list doesn't have,
1424
+ * nothing. Its keys and checks the client's: with `keys` given and no items, its keys as given.
1425
+ */
1426
+ export const serverKeyedHandlesOf = <Style>(config: KeyedBatchConfig<unknown>, presenceOf: () => PresenceController.PresenceContextValue | undefined, server: BatchServerAppear = NO_SERVER_APPEAR) => {
1427
+ const items = config.each()
1428
+ const reader = keyReaderOf(config)
1429
+ const keyAt: Array<unknown> = []
1430
+ const indexOfKey = new Map<unknown, number>()
1431
+ Arr.forEach(items, (item, i) => {
1432
+ const key = reader(item, i)
1433
+ const known = indexOfKey.get(key)
1434
+ if (Predicate.isNotUndefined(known)) twoWithKey(known, i, key)
1435
+ indexOfKey.set(key, i)
1436
+ keyAt.push(key)
1437
+ })
1438
+ const nameOf: NameOf = (i) => keyName(keyAt[i])
1439
+ const values = Arr.map(items, (item, i) => config.animate(item, i) as Readonly<Record<string, unknown>>)
1440
+ const fixed = config.keys as ReadonlyArray<string> | undefined
1441
+ const listed = UndefinedOr.match(fixed, { onUndefined: () => keysFrom(items.length, (i) => values[i], (i) => keyedInitialOf(config, items[i], i)), onDefined: identity })
1442
+ // As the client's: `keys` given and no items yet makes them as they are.
1443
+ let given = listed
1444
+ if (Bool.or(Predicate.isUndefined(fixed), items.length > 0)) given = withConfigKeys(listed, Predicate.isNotUndefined(fixed), config)
1445
+ const { keys, keyIndex, drawn, targets } = serverKeysOf(given)
1446
+ /** Item `i`'s values, at its targets when `quiet` or with `initial: false`. */
1447
+ const memberAt = (i: number, quiet: boolean): ServerMember => {
1448
+ targetsOn(targets, 0, keys, keyIndex, values[i] as Readonly<Record<string, unknown>>, nameOf, i)
1449
+ let initial = keyedInitialOf(config, items[i], i)
1450
+ if (quiet) initial = undefined
1451
+ let atTargets = quiet
1452
+ if (config.initial === false) atTargets = true
1453
+ return serverMemberValuesOf(keys, startOn(keys, keyIndex, initial, targets, 0, atTargets, nameOf, i), targets)
1454
+ }
1455
+ // Each from its `initial`: one under `<AnimatePresence initial={false}>`, which its own render tells, plays none.
1456
+ const members = serverMembersOf(server, config, keys, items.length, (i) => memberAt(i, false), nameOf)
1457
+ return <E extends Element>(key: unknown, props?: MemberProps<E, Style>): Member<E, Style> => {
1458
+ const i = indexOfKey.get(key)
1459
+ if (Predicate.isUndefined(i)) return serverMemberOf(undefined, drawn, props)
1460
+ // `<AnimatePresence initial={false}>`'s first render (Q46): at its targets, whatever `initial` says.
1461
+ if (PresenceRecord.presenceBlocksInitial(presenceOf())) return serverMemberOf(memberAt(i, true).start, drawn, props)
1462
+ return serverMemberOf(members.memberAt(i).start, drawn, props, members.appearOf(i))
1463
+ }
1464
+ }
1465
+
1466
+ const noop = (): void => {}
1467
+
1468
+ /** Member handles for `binding`: its `ref`, the element's own `ref` called beside it, and its own `style` kept. */
1469
+ export const handlesOf = <Style>(binding: BatchBinding) =>
1470
+ <E extends Element>(i: number, props?: MemberProps<E, Style>): Member<E, Style> => {
1471
+ const handle = memberHandleOf<E, Style>(binding, i, props)
1472
+ // Known to `animate`, as member `i`'s: its entry made once, so a handle made at each render costs its
1473
+ // WeakMap write alone (0.09 ms a 1,000 handles in Node, against 0.16 with an entry made each time; #665).
1474
+ SUBJECTS.set(handle, binding.entryOf(i))
1475
+ return handle
1476
+ }
1477
+
1478
+ const memberHandleOf = <E extends Element, Style>(binding: BatchBinding, i: number, props: MemberProps<E, Style> | undefined): Member<E, Style> => {
1479
+ const ref = binding.refOf(i)
1480
+ if (Predicate.isUndefined(props)) return { ref }
1481
+ const own = props.ref
1482
+ const both = (el: E): void => {
1483
+ ref(el)
1484
+ if (Predicate.isNotUndefined(own)) own(el)
1485
+ }
1486
+ // No `style` of its own: none on the handle, so a spread keeps a `style` the element gives before it (Solid 2's merge takes an `undefined` one).
1487
+ if (Predicate.isUndefined(props.style)) return { ref: both }
1488
+ return { ref: both, style: binding.styleOf(props.style) }
1489
+ }
1490
+
1491
+ /** The nearest `WardicConfig`'s transition, read as each change starts, from either binding's config value. */
1492
+ export const configTransitionOf = (config: { readonly transition: () => WardConfig.WardicTransition | undefined } | undefined) => (): WardConfig.WardicTransition | undefined => {
1493
+ if (Predicate.isUndefined(config)) return undefined
1494
+ return config.transition()
1495
+ }
1496
+
1497
+ /** Keyed member handles for `binding`: as {@link handlesOf}'s, each key's member made at its first handle. */
1498
+ export const keyedHandlesOf = <Style>(binding: BatchBinding, presenceNow: () => PresenceController.PresenceContextValue | undefined) =>
1499
+ <E extends Element>(key: unknown, props?: MemberProps<E, Style>): Member<E, Style> => {
1500
+ // The presence it's made under, read as it's made, in its item's render (Q46).
1501
+ const member = binding.memberFor(key, presenceNow())
1502
+ const handle = memberHandleOf<E, Style>(binding, member, props)
1503
+ SUBJECTS.set(handle, binding.entryOf(member))
1504
+ return handle
1505
+ }
1506
+
1507
+ /** A keyed member's index before its item is in `each`, or once it has left. */
1508
+ const NO_INDEX = -1
1509
+
1510
+ /** A keyed Batch's members' keys: its config's, by property or function, each checked to give one. */
1511
+ const keyReaderOf = (config: KeyedBatchConfig<unknown>): ((item: unknown, i: number) => unknown) => {
1512
+ const given = config.key
1513
+ const read: (item: unknown) => unknown = Bool.match(Predicate.isFunction(given), {
1514
+ onTrue: () => given as (item: unknown) => unknown,
1515
+ onFalse: () => (item: unknown) => (item as Readonly<Record<PropertyKey, unknown>>)[given as unknown as PropertyKey],
1516
+ })
1517
+ // Per item at a change (#665): statements.
1518
+ return (item, i) => {
1519
+ const key = read(item)
1520
+ if (Predicate.isNullish(key)) return fail(`item ${i}'s key is ${String(key)}: give each item a key, by \`key\``)
1521
+ return key
1522
+ }
1523
+ }
1524
+
1525
+ /**
1526
+ * What a Batch's members are, chosen once as it's made: by index, `count` of them fixed; or keyed, a list's
1527
+ * items by their keys, entering and leaving with it.
1528
+ */
1529
+ interface MembersForm {
1530
+ /** How many members the list has now: the `n` a function of a member's index hears. */
1531
+ readonly size: () => number
1532
+ /** How an error names member `i`: by its index, or by its key. */
1533
+ readonly nameOf: (i: number) => string
1534
+ /** Every member's targets now: a compute, which writes nothing shared. */
1535
+ readonly targetsOf: () => BatchTargets
1536
+ /** A change's targets taken in: by index, the targets; keyed, the list, members entering and leaving. */
1537
+ readonly take: (targets: BatchTargets) => void
1538
+ /** The slots of the members that have arrived: by index, in the order they did (its own list, not a copy); keyed, in the list's. */
1539
+ readonly arrivedSlots: () => ReadonlyArray<number>
1540
+ /** Every member, in order: by index, by index; keyed, in the list's. */
1541
+ readonly inOrder: () => ReadonlyArray<number>
1542
+ /** Member `i`'s `initial`, as values, or `undefined` for none. */
1543
+ readonly initialOf: (i: number) => Readonly<Record<string, unknown>> | undefined
1544
+ /** Whether member `i`'s element enters as it arrives: keyed, once the list has its key and the Batch is made. */
1545
+ readonly entersNow: (i: number) => boolean
1546
+ /** A slot entered: by index, kept in arrival order. */
1547
+ readonly entered: (slot: number) => void
1548
+ /** Member `i`'s `ref`, or the error for one it doesn't have. */
1549
+ readonly refOf: (i: number) => (el: Element) => void
1550
+ /** The keyed form's member for `key`, under `presence`. */
1551
+ readonly memberFor: (key: unknown, presence: PresenceController.PresenceContextValue | undefined) => number
1552
+ }
1553
+
1554
+ /** A keyed member's exit while it plays: its presence's `release`, and its `custom`. */
1555
+ interface MemberExit {
1556
+ readonly release: (completed?: boolean) => void
1557
+ readonly custom: unknown
1558
+ }
1559
+
1560
+ /**
1561
+ * A Batch for `config`'s members, under `env`'s provider: its writer the DOM's. The binding tracks
1562
+ * {@link BatchBinding.targetsOf} and hands each new value to {@link BatchBinding.apply}.
1563
+ *
1564
+ * - **By index,** its `count` members are fixed, member `i` its `i`th, and its core Batch is made at once.
1565
+ * - **Keyed** (Q42–Q45), each key's member is a number, given at its key's first sight and given back when
1566
+ * it leaves, so a long list's churn reuses them. Its core Batch is made at the first change with
1567
+ * members, at a handle's first sight of one, or at once when its `keys` are given (Q51).
1568
+ */
1569
+ export const bindBatch = (env: BatchEnv, config: BatchConfig | KeyedBatchConfig<unknown>, hooks: BatchHooks): BatchBinding => {
1570
+ const keyed = isKeyed(config)
1571
+ // The keys, and the core Batch: made at once by index, at the first change with members when keyed.
1572
+ let keys: ReadonlyArray<string> = []
1573
+ let stride = 0
1574
+ let keyIndex: ReadonlyMap<string, number> = new Map()
1575
+ let batch: Batch.Batch<Element> | undefined = undefined
1576
+ let write: (subject: Element, positions: Float64Array, base: number) => void = noop
1577
+ // The CSS properties the Batch draws, which an element's own `style` leaves to it.
1578
+ let drawn: ReadonlySet<string> = new Set()
1579
+ /** The core Batch, once it's made: every caller runs after. */
1580
+ const made = (): Batch.Batch<Element> => UndefinedOr.getOrThrow(batch)
1581
+
1582
+ // Each member's slot (`NO_SLOT` before its element arrives), its index in the list (`NO_INDEX` when it
1583
+ // has none), and its element, entry and `ref`; each slot's member; and every member's targets, `stride` a member.
1584
+ let capacity = 1
1585
+ let slotOf = new Int32Array(capacity).fill(NO_SLOT)
1586
+ let indexOf = new Int32Array(capacity).fill(NO_INDEX)
1587
+ const elementOf: Array<Element | undefined> = []
1588
+ const entries: Array<BatchMemberEntry | undefined> = []
1589
+ const refs: Array<(el: Element) => void> = []
1590
+ const memberOf: Array<number> = []
1591
+ let current: Float64Array = new Float64Array(0)
1592
+ // Each member's gestures on (#665's PR 5), a layer each over `animate`'s targets: its values while it's
1593
+ // on, `NaN` for a key it doesn't give; and how many layers are on, so a change with none reads `animate`'s
1594
+ // alone. Declared before `targetOf`, which reads them per member per key at a change.
1595
+ const hovering: Array<Float64Array | undefined> = []
1596
+ const pressing: Array<Float64Array | undefined> = []
1597
+ // A Batch Reorder group's item in hand (#712): its `whileDrag` layer over its press's, and where its
1598
+ // `x` and `y` are held, over every layer's, while it's dragged.
1599
+ const dragging: Array<Float64Array | undefined> = []
1600
+ const layers: Readonly<Record<BatchGestureLayer, Array<Float64Array | undefined>>> = { hover: hovering, press: pressing, drag: dragging }
1601
+ const hands: Array<Float64Array | undefined> = []
1602
+ // `x`'s and `y`'s key index, once a hand's held: -1 for a Batch without them.
1603
+ let handX = -1
1604
+ let handY = -1
1605
+ let gesturing = 0
1606
+ // Where each key only a gesture gives (none of `animate`'s) was as the member's first layer came on:
1607
+ // what it returns to as its last goes (decision 12), `NaN` for the rest; kept while a layer is on.
1608
+ const bases: Array<Float64Array | undefined> = []
1609
+ let binding: BatchBinding | undefined = undefined
1610
+
1611
+ /** Room for `wanted` members: every member's typed arrays grown to the next power of two times their size that holds it. */
1612
+ // Once a growth (#665): typed arrays copied.
1613
+ const growMembersTo = (wanted: number): void => {
1614
+ if (wanted <= capacity) return
1615
+ const grown = capacity * 2 ** Math.ceil(Math.log2(wanted / capacity))
1616
+ const slots = new Int32Array(grown).fill(NO_SLOT)
1617
+ slots.set(slotOf)
1618
+ slotOf = slots
1619
+ const indices = new Int32Array(grown).fill(NO_INDEX)
1620
+ indices.set(indexOf)
1621
+ indexOf = indices
1622
+ const listings = new Int32Array(grown)
1623
+ listings.set(listedIn)
1624
+ listedIn = listings
1625
+ const targets = new Float64Array(grown * stride).fill(Number.NaN)
1626
+ targets.set(current)
1627
+ current = targets
1628
+ capacity = grown
1629
+ }
1630
+
1631
+ /** Member `i`'s `values` written as its targets into `into`, `NaN` for a key they leave out; each one a number. */
1632
+ // Per member per key at a change (#665): statements.
1633
+ const targetsInto = (into: Float64Array, i: number, values: Readonly<Record<string, unknown>>): void =>
1634
+ targetsOn(into, i * stride, keys, keyIndex, values, form.nameOf, i)
1635
+
1636
+ const configuredOf = (): WardConfig.WardicTransition | undefined => {
1637
+ const given = config.transition as WardConfig.WardicTransition | undefined
1638
+ if (Predicate.isNotUndefined(given)) return given
1639
+ return env.configTransition()
1640
+ }
1641
+
1642
+ // Its gestures as given (#665's PR 5): `whileHover` and `whileTap`, an object or a function.
1643
+ /** A key's Default transition toward `target`. */
1644
+ const defaultFor = (k: number, target: number): Batch.Transition => env.defaultTransition.transitionFor(keys[k], target) as Batch.Transition
1645
+
1646
+ /** The Batch's keys, fixed from now on, and room for every member's targets on them. */
1647
+ const keysAre = (given: ReadonlyArray<string>): void => {
1648
+ keys = given
1649
+ stride = given.length
1650
+ keyIndex = new Map(Arr.map(given, (key, k) => [key, k] as const))
1651
+ current = new Float64Array(capacity * stride).fill(Number.NaN)
1652
+ }
1653
+
1654
+ /**
1655
+ * The core Batch: its own transitions each key's as it is now, so the members a change gives them step by
1656
+ * one matrix while they share one (ADR-0069, *Amendment (#665)*), the Default transition toward
1657
+ * `firstTarget(k)`, its first member's, for a key without one.
1658
+ */
1659
+ const makeBatch = (firstTarget: (k: number) => number): void => {
1660
+ const ownPlan = plannedOf(env.positionalKeys, keys, UndefinedOr.map(configuredOf(), unstaggered), false)
1661
+ const own: Record<string, Batch.Transition> = {}
1662
+ Arr.forEach(keys, (key, k) => {
1663
+ const plan = ownPlan[k]
1664
+ if (Predicate.isNotUndefined(plan.own)) {
1665
+ own[key] = plan.own
1666
+ return
1667
+ }
1668
+ let target = firstTarget(k)
1669
+ if (Number.isNaN(target)) target = identityOf(key)
1670
+ own[key] = delayedBy(defaultFor(k, target), plan.delay)
1671
+ })
1672
+ // The writer's write for these keys, built once: an arriving element is drawn with it at once. A member
1673
+ // a Wardic element holds a group of is drawn without it (#665's PR 4): one check a member while none is.
1674
+ write = DomBatch.writer.forKeys(keys)
1675
+ const without = (group: BatchGroup): ((el: Element, positions: Float64Array, base: number) => void) =>
1676
+ DomBatch.writer.forKeys(Arr.map(keys, (key) => Bool.match(batchGroupOf(key) === group, { onTrue: () => UNDRAWN, onFalse: () => key })))
1677
+ const withoutTransform = without("transform")
1678
+ const withoutOpacity = without("opacity")
1679
+ const full = write
1680
+ // Per frame, per moving member: a size check, and with a member held, a Map read. A member both of
1681
+ // whose groups are held is drawn by its Wardic element alone: the Batch draws nothing else.
1682
+ const masking = (el: Element, positions: Float64Array, base: number): void => {
1683
+ if (masks.size === 0) return full(el, positions, base)
1684
+ const mask = masks.get(el)
1685
+ if (Predicate.isUndefined(mask)) return full(el, positions, base)
1686
+ if (mask === GROUP_BITS.transform) return withoutTransform(el, positions, base)
1687
+ if (mask === GROUP_BITS.opacity) return withoutOpacity(el, positions, base)
1688
+ }
1689
+ groupKs.transform = Arr.filter(Arr.map(keys, (_, k) => k), (k) => batchGroupOf(keys[k]) === "transform")
1690
+ groupKs.opacity = Arr.filter(Arr.map(keys, (_, k) => k), (k) => keys[k] === "opacity")
1691
+ batch = Batch.make({ keys, writer: { writes: DomBatch.writer.writes, forKeys: () => masking }, transition: own, capacity })
1692
+ drawn = drawnBy(keys)
1693
+ }
1694
+
1695
+ // --- Keyed: a list's items by key (#665, Q42–Q45, Q51) ------------------------------------
1696
+
1697
+ const byKey = config as KeyedBatchConfig<unknown>
1698
+ const keyReader = Bool.match(keyed, { onTrue: () => keyReaderOf(byKey), onFalse: () => (): unknown => undefined })
1699
+ // Each member's key and item, each key's member, the members given back, how many members there have
1700
+ // been, and the list's members in order.
1701
+ const keyOf: Array<unknown> = []
1702
+ const itemOf: Array<unknown> = []
1703
+ const memberOfKey = new Map<unknown, number>()
1704
+ const freeMembers: Array<number> = []
1705
+ let memberCount = 0
1706
+ let order: ReadonlyArray<number> = []
1707
+ // Which listing (a change of the list taken in) last listed each member, to tell a key given twice and the members that left.
1708
+ let listedIn = new Int32Array(capacity)
1709
+ let listings = 0
1710
+
1711
+ /** Keyed: member `item`'s `initial` at `i`, as values, or `undefined` for none. */
1712
+
1713
+ // Keyed: its `exit` as values (an object's, less its `transition`; none for a function's), and that `transition`.
1714
+ const exitObject = objectFormOf(byKey.exit)
1715
+ const exitValues = objectFormValues(byKey.exit)
1716
+ const exitTransition = UndefinedOr.map(exitObject, (given) => given.transition as WardConfig.WardicTransition | undefined)
1717
+
1718
+ /** Keyed: the items now, their keys and their targets, as `animate` gives them. A compute: it writes nothing shared. */
1719
+ const keyedTargetsOf = (): KeyedTargets => {
1720
+ const items = byKey.each()
1721
+ return {
1722
+ items,
1723
+ keys: Arr.map(items, keyReader),
1724
+ values: Arr.map(items, (item, i) => byKey.animate(item, i) as Readonly<Record<string, unknown>>),
1725
+ }
1726
+ }
1727
+
1728
+ /**
1729
+ * Keyed: the core Batch, made on `targets`' keys and its `exit`'s, as values (else the config's `keys`,
1730
+ * which must hold the `exit`'s), when it has members.
1731
+ */
1732
+ const makeFromList = (targets: KeyedTargets): void => {
1733
+ if (targets.items.length === 0) return
1734
+ keysAre(withMoreKeys(UndefinedOr.match(byKey.keys, {
1735
+ onUndefined: () => keysFrom(targets.items.length, (i) => targets.values[i], (i) => keyedInitialOf(byKey, targets.items[i], i)),
1736
+ onDefined: identity,
1737
+ }), firstGesturesOf(targets)))
1738
+ makeBatch((k) => {
1739
+ const value = targets.values[0][keys[k]]
1740
+ if (Predicate.isNumber(value)) return value
1741
+ return Number.NaN
1742
+ })
1743
+ }
1744
+
1745
+ /**
1746
+ * `given` keys with those its `exit`, `whileHover` and `whileTap` give as values after them (Q48, Q58);
1747
+ * with `keys` given, one outside them is an error naming it.
1748
+ */
1749
+ const withMoreKeys = (given: ReadonlyArray<string>, firstGestures: Readonly<Record<string, unknown>> = NO_VALUES): ReadonlyArray<string> =>
1750
+ withConfigKeys(given, Predicate.isNotUndefined(byKey.keys), config, firstGestures)
1751
+
1752
+ /**
1753
+ * Keyed: a Batch Reorder group's function gestures' values for the list's first item (#712, Q27, Q34):
1754
+ * `whileHover`'s, `whileTap`'s and `whileDrag`'s keys join the Batch's, as `animate`'s first targets' do.
1755
+ * None for an object's, or for any other Batch, whose function gestures give keys it has.
1756
+ */
1757
+ const firstGesturesOf = (targets: KeyedTargets): Readonly<Record<string, unknown>> => {
1758
+ if (Bool.not(Predicate.hasProperty(config, "gestureKeysFromFirst"))) return NO_VALUES
1759
+ const given = config as unknown as Readonly<Record<"whileHover" | "whileTap" | "whileDrag", unknown>>
1760
+ const first = (gesture: unknown): Readonly<Record<string, unknown>> =>
1761
+ Bool.match(Predicate.isFunction(gesture), {
1762
+ onTrue: () => env.untrack(() => (gesture as (item: unknown, i: number) => Readonly<Record<string, unknown>>)(targets.items[0], 0)),
1763
+ onFalse: () => NO_VALUES,
1764
+ })
1765
+ return { ...first(given.whileHover), ...first(given.whileTap), ...first(given.whileDrag) }
1766
+ }
1767
+
1768
+ /** Keyed: the member for `key`: its member, else a new one. */
1769
+ const memberForKey = (key: unknown): number => {
1770
+ const known = memberOfKey.get(key)
1771
+ if (Predicate.isNotUndefined(known)) return known
1772
+ return newMember(key)
1773
+ }
1774
+
1775
+ /** A keyed member for `key`, at its first sight: a member given back, else the next. */
1776
+ const newMember = (key: unknown): number => {
1777
+ let member = freeMembers.pop()
1778
+ if (Predicate.isUndefined(member)) {
1779
+ member = memberCount
1780
+ memberCount = memberCount + 1
1781
+ growMembersTo(memberCount)
1782
+ }
1783
+ const i = member
1784
+ const entry: BatchMemberEntry = { binding: UndefinedOr.getOrThrow(binding), member: i }
1785
+ entries[i] = entry
1786
+ keyOf[i] = key
1787
+ indexOf[i] = NO_INDEX
1788
+ listedIn[i] = 0
1789
+ memberOfKey.set(key, i)
1790
+ // Its `ref` reaches it only while it's this key's: a handle kept past its leave reaches nothing.
1791
+ refs[i] = (el: Element) => {
1792
+ if (entries[i] === entry) arrive(i, el)
1793
+ }
1794
+ return i
1795
+ }
1796
+
1797
+ /**
1798
+ * Keyed: the list now, `targets`, taken in: the core Batch made at its first members, each item's member
1799
+ * (made at its key's first sight) given its index, item and targets, and each member that left the list
1800
+ * leaving the Batch at once (3a: an exit comes with `<AnimatePresence>`, in 3b).
1801
+ */
1802
+ const takeList = (targets: KeyedTargets): void => {
1803
+ if (Predicate.isUndefined(batch)) makeFromList(targets)
1804
+ if (Predicate.isUndefined(batch)) return
1805
+ listings = listings + 1
1806
+ const next: Array<number> = []
1807
+ // Per item at a change (#665): statements.
1808
+ Arr.forEach(targets.items, (item, i) => {
1809
+ const key = targets.keys[i]
1810
+ const member = memberForKey(key)
1811
+ if (listedIn[member] === listings) return twoWithKey(indexOf[member], i, key)
1812
+ listedIn[member] = listings
1813
+ indexOf[member] = i
1814
+ itemOf[member] = item
1815
+ targetsInto(current, member, targets.values[i])
1816
+ next.push(member)
1817
+ // Back in the list mid-exit (Q26): its exit cut short, its element gone at once, uncompleted; its
1818
+ // next element takes its slot over, its values and speed, and this change turns it toward `animate`.
1819
+ if (unlisted.delete(member)) cutExit(member)
1820
+ })
1821
+ Arr.forEach(order, (member) => {
1822
+ if (listedIn[member] !== listings) leavesList(member)
1823
+ })
1824
+ order = next
1825
+ }
1826
+
1827
+ /**
1828
+ * Keyed: member `i` left the list. Under `<AnimatePresence>` (its element watched), it stays in the
1829
+ * Batch until its exit lands; else it leaves at once.
1830
+ */
1831
+ const leavesList = (i: number): void => {
1832
+ if (Bool.or(Predicate.isNotUndefined(exits[i]), isWatched(i))) {
1833
+ unlisted.add(i)
1834
+ flushSoon()
1835
+ return
1836
+ }
1837
+ leaveBatch(i)
1838
+ }
1839
+
1840
+ /** Keyed: whether member `i`'s element is the one its presence watches. */
1841
+ const isWatched = (i: number): boolean => {
1842
+ const watched = watchedOn[i]
1843
+ if (Predicate.isUndefined(watched)) return false
1844
+ return watched === elementOf[i]
1845
+ }
1846
+
1847
+ /** Keyed: member `i`'s exit cut short, its element let go at once, uncompleted (#286's rule). */
1848
+ const cutExit = (i: number): void => {
1849
+ const exit = exits[i]
1850
+ exits[i] = undefined
1851
+ if (Predicate.isNotUndefined(exit)) exit.release(false)
1852
+ }
1853
+
1854
+ /** Keyed: member `i` leaves the Batch, at once; its number is given back. */
1855
+ const leaveBatch = (i: number): void => {
1856
+ unlisted.delete(i)
1857
+ exits[i] = undefined
1858
+ presenceOf[i] = undefined
1859
+ watchedOn[i] = undefined
1860
+ quietStart.delete(i)
1861
+ unhold(i)
1862
+ const slot = slotOf[i]
1863
+ if (slot !== NO_SLOT) Batch.leave(made(), slot)
1864
+ const el = elementOf[i]
1865
+ if (Predicate.isNotUndefined(el)) forget(el, i)
1866
+ memberOfKey.delete(keyOf[i])
1867
+ keyOf[i] = undefined
1868
+ itemOf[i] = undefined
1869
+ entries[i] = undefined
1870
+ elementOf[i] = undefined
1871
+ slotOf[i] = NO_SLOT
1872
+ indexOf[i] = NO_INDEX
1873
+ reported.delete(i)
1874
+ freeMembers.push(i)
1875
+ }
1876
+
1877
+ // --- Keyed under `<AnimatePresence>` (#665, PR 3b, Q46–Q48) ------------------------------------
1878
+
1879
+ // Each member's presence (the one its latest handle was made under) and the element it watches there;
1880
+ // the members that start at their targets (`initial={false}`, its first render); the members out of
1881
+ // the list it holds while they exit; each one's exit while it plays; and the exits starting this task.
1882
+ const presenceOf: Array<PresenceController.PresenceContextValue | undefined> = []
1883
+ const watchedOn: Array<Element | undefined> = []
1884
+ const quietStart = new Set<number>()
1885
+ const unlisted = new Set<number>()
1886
+ const exits: Array<MemberExit | undefined> = []
1887
+ let starting: Array<number> = []
1888
+ let exitsSoon = false
1889
+
1890
+ // Each member's element held off the page by `mode="wait"`, and the call that lets the hold go.
1891
+ const holds = new Map<number, () => void>()
1892
+
1893
+ /** Keyed: whether member `entry` is still member `i`: a member given back and taken by another key isn't. */
1894
+ const isCurrent = (i: number, entry: BatchMemberEntry | undefined): boolean => entries[i] === entry
1895
+
1896
+ /** Keyed: member `i`'s element `el` watched by its presence, so its leave plays its exit, holding it on the page. */
1897
+ const watchOn = (i: number, el: Element): void => {
1898
+ const presence = presenceOf[i]
1899
+ if (Predicate.isUndefined(presence) || watchedOn[i] === el) return
1900
+ const watch = presence.watch
1901
+ if (Predicate.isUndefined(watch)) return
1902
+ watchedOn[i] = el
1903
+ const entry = entries[i]
1904
+ watch({
1905
+ element: () => el,
1906
+ holds: true,
1907
+ leave: (custom, release) => memberLeft(i, entry, el, custom, release),
1908
+ gone: () => watchGone(i, entry, el),
1909
+ interrupted: () => exitCut(i, entry),
1910
+ })
1911
+ }
1912
+
1913
+ /**
1914
+ * Keyed: whether the member entering at `slot` is held off the page by its presence's `mode="wait"`,
1915
+ * read at its task's end, once the presence has decided: its move starts as the presence lets it on,
1916
+ * as a Wardic element's does then.
1917
+ */
1918
+ const heldBack = (slot: number): boolean => {
1919
+ const i = memberOf[slot]
1920
+ const presence = presenceOf[i]
1921
+ const el = elementOf[i]
1922
+ if (Predicate.isUndefined(presence) || Predicate.isUndefined(el)) return false
1923
+ unhold(i)
1924
+ const entry = entries[i]
1925
+ const cancel = PresenceRecord.presenceHold(presence, el, () => {
1926
+ holds.delete(i)
1927
+ if (Bool.and(isCurrent(i, entry), slotOf[i] === slot)) change([slot])
1928
+ })
1929
+ if (Predicate.isUndefined(cancel)) return false
1930
+ holds.set(i, cancel)
1931
+ return true
1932
+ }
1933
+
1934
+ /** Keyed: member `i`'s hold let go, if it had one. */
1935
+ const unhold = (i: number): void => {
1936
+ const cancel = holds.get(i)
1937
+ holds.delete(i)
1938
+ if (Predicate.isNotUndefined(cancel)) cancel()
1939
+ }
1940
+
1941
+ /** Keyed: member `i`'s element left its presence: its exit plays with this task's others', so `stagger()` counts them (Q25). */
1942
+ const memberLeft = (i: number, entry: BatchMemberEntry | undefined, el: Element, custom: unknown, release: (completed?: boolean) => void): void => {
1943
+ // Not the member's element now (made again), or never drawn: nothing to exit on it.
1944
+ if (!isCurrent(i, entry)) return release()
1945
+ if (elementOf[i] !== el) return release()
1946
+ if (slotOf[i] === NO_SLOT) return release()
1947
+ exits[i] = { release, custom }
1948
+ starting.push(i)
1949
+ if (exitsSoon) return
1950
+ exitsSoon = true
1951
+ queueMicrotask(playExits)
1952
+ }
1953
+
1954
+ /** Keyed: a leaver's exit values: its `exit` read once, a function's called with its item, last index and `custom`. */
1955
+ const exitValuesOf = (i: number, custom: unknown): Readonly<Record<string, unknown>> => {
1956
+ if (Predicate.isFunction(byKey.exit)) return byKey.exit(itemOf[i], indexOf[i], custom)
1957
+ return exitValues
1958
+ }
1959
+
1960
+ /** Keyed: this task's exits, one driven change of them all, each member let go as its own lands (Q47). */
1961
+ const playExits = (): void => {
1962
+ exitsSoon = false
1963
+ const going = Arr.filter(starting, (i) => Bool.and(Predicate.isNotUndefined(exits[i]), slotOf[i] !== NO_SLOT))
1964
+ starting = []
1965
+ if (going.length === 0) return
1966
+ // A Batch disposed since lets its leavers go at once.
1967
+ if (disposed) return Arr.forEach(going, cutExit)
1968
+ const exitTargets = new Float64Array(capacity * stride).fill(Number.NaN)
1969
+ const moving: Array<number> = []
1970
+ // Per leaver at its exit (#665): statements. An exit that fails is reported, and lets its element go.
1971
+ Arr.forEach(going, (i) => {
1972
+ try {
1973
+ targetsInto(exitTargets, i, exitValuesOf(i, UndefinedOr.getOrThrow(exits[i]).custom))
1974
+ moving.push(i)
1975
+ } catch (defect) {
1976
+ env.runtime.runFork(Report.failure("createBatch: a member's exit failed", Cause.die(defect)))
1977
+ cutExit(i)
1978
+ if (unlisted.has(i)) leaveBatch(i)
1979
+ }
1980
+ })
1981
+ if (moving.length === 0) return
1982
+ const slots = Arr.map(moving, (i) => slotOf[i])
1983
+ const exitOf = (slot: number, k: number): number => exitTargets[memberOf[slot] * stride + k]
1984
+ // The groups Wardic elements hold of the leavers that their exits move come back first (Q54).
1985
+ retakeFor(slots, givesGroup((slot, k) => !Number.isNaN(exitOf(slot, k))))
1986
+ const configured = configuredOf()
1987
+ changeOn(slots, exitOf, undefined, {
1988
+ transition: UndefinedOr.match(exitTransition, { onUndefined: () => configured, onDefined: identity }),
1989
+ reducedMotion: env.reducedMotion(),
1990
+ skipAnimations: skipsNow(configured),
1991
+ head: Playback.make(),
1992
+ settled: noop,
1993
+ onMemberLanded: (slot) => exitLanded(memberOf[slot]),
1994
+ }).run()
1995
+ }
1996
+
1997
+ /**
1998
+ * Keyed: member `i`'s exit landed: its element let go. Out of the list, the member leaves the Batch; in
1999
+ * it (its element gone with a presence child that left), its slot goes, so its next element enters anew.
2000
+ */
2001
+ const exitLanded = (i: number): void => {
2002
+ const exit = exits[i]
2003
+ if (Predicate.isUndefined(exit)) return
2004
+ exits[i] = undefined
2005
+ exit.release()
2006
+ if (unlisted.has(i)) return leaveBatch(i)
2007
+ dropSlot(i)
2008
+ }
2009
+
2010
+ /** Keyed: member `i`, still in the list, out of the Batch's run: its next element enters from `initial`. */
2011
+ const dropSlot = (i: number): void => {
2012
+ const slot = slotOf[i]
2013
+ if (slot === NO_SLOT) return
2014
+ Batch.leave(made(), slot)
2015
+ slotOf[i] = NO_SLOT
2016
+ const el = elementOf[i]
2017
+ if (Predicate.isNotUndefined(el)) forget(el, i)
2018
+ elementOf[i] = undefined
2019
+ watchedOn[i] = undefined
2020
+ }
2021
+
2022
+ /**
2023
+ * Keyed: member `i`'s exit cut short by its presence (a take-over of the child it's in, the presence
2024
+ * going): out of the list, it leaves the Batch; in it, it turns back toward its targets.
2025
+ */
2026
+ const exitCut = (i: number, entry: BatchMemberEntry | undefined): void => {
2027
+ if (!isCurrent(i, entry)) return
2028
+ exits[i] = undefined
2029
+ if (unlisted.has(i)) return leaveBatch(i)
2030
+ const slot = slotOf[i]
2031
+ if (slot !== NO_SLOT) change([slot])
2032
+ }
2033
+
2034
+ /** Keyed: member `i`'s watch dropped with no leave: its element left some other way. Out of the list, it leaves the Batch. */
2035
+ const watchGone = (i: number, entry: BatchMemberEntry | undefined, el: Element): void => {
2036
+ if (!isCurrent(i, entry)) return
2037
+ if (watchedOn[i] !== el) return
2038
+ watchedOn[i] = undefined
2039
+ if (Bool.and(unlisted.has(i), Predicate.isUndefined(exits[i]))) leaveBatch(i)
2040
+ }
2041
+
2042
+ /**
2043
+ * Keyed: the members out of the list whose presence didn't take their elements, at a task's end: one
2044
+ * not inside a child the presence keeps, whose element is off the page with no exit, leaves the Batch.
2045
+ */
2046
+ const settleUnlisted = (): void =>
2047
+ Iter.forEach(unlisted, (i) => {
2048
+ if (Predicate.isNotUndefined(exits[i])) return
2049
+ const el = elementOf[i]
2050
+ if (Predicate.isUndefined(el)) return leaveBatch(i)
2051
+ if (el.isConnected) return
2052
+ leaveBatch(i)
2053
+ })
2054
+
2055
+ // Elements whose keys the list didn't have as they arrived, and those reported for still not having them
2056
+ // at a task's end: each enters once a change lists its key (Q45).
2057
+ let waiting: Array<number> = []
2058
+ const reported = new Set<number>()
2059
+
2060
+ /** Keyed: the waiting elements whose keys the list has now, entered; the rest wait on. */
2061
+ const enterListed = (): void => {
2062
+ if (waiting.length === 0 || Predicate.isUndefined(batch)) return
2063
+ const early = waiting
2064
+ waiting = []
2065
+ Arr.forEach(early, (i) => {
2066
+ // Gone since, or entered already.
2067
+ if (Predicate.isUndefined(entries[i]) || slotOf[i] !== NO_SLOT) return
2068
+ if (indexOf[i] === NO_INDEX) {
2069
+ waiting.push(i)
2070
+ return
2071
+ }
2072
+ reported.delete(i)
2073
+ enter(i, UndefinedOr.getOrThrow(elementOf[i]))
2074
+ })
2075
+ }
2076
+
2077
+ /** Keyed: the waiting elements at a task's end, the list read again: those it has entered, each other one reported once. */
2078
+ // Found at a task's end, where a throw reaches nothing: reported, and the element waits on.
2079
+ const settleWaiting = (): void => {
2080
+ if (waiting.length === 0) return
2081
+ takeList(env.untrack(keyedTargetsOf))
2082
+ enterListed()
2083
+ Arr.forEach(waiting, (i) => {
2084
+ if (reported.has(i)) return
2085
+ reported.add(i)
2086
+ const unlisted = new Error(`createBatch: an element was given ${form.nameOf(i)}'s handle, but no item in \`each\` has that key`)
2087
+ env.runtime.runFork(Report.failure("createBatch: a member's element has no item", Cause.die(unlisted)))
2088
+ })
2089
+ }
2090
+
2091
+ const keyedForm: MembersForm = {
2092
+ size: () => order.length,
2093
+ nameOf: (i) => keyName(keyOf[i]),
2094
+ targetsOf: keyedTargetsOf,
2095
+ take: (targets) => {
2096
+ takeList(targets as KeyedTargets)
2097
+ enterListed()
2098
+ },
2099
+ arrivedSlots: () => Arr.filter(Arr.map(order, (i) => slotOf[i]), (slot) => slot !== NO_SLOT),
2100
+ inOrder: () => order,
2101
+ initialOf: (i) => keyedInitialOf(byKey, itemOf[i], indexOf[i]),
2102
+ entersNow: (i) => Bool.and(indexOf[i] !== NO_INDEX, Predicate.isNotUndefined(batch)),
2103
+ entered: noop,
2104
+ refOf: (i) => refs[i],
2105
+ // A member for a key no list has listed stays until a list does: its handle's element may arrive first.
2106
+ // On Solid 2 a spread's compute can make one Solid then throws away, so a key's member is made once.
2107
+ memberFor: (key, presence) => {
2108
+ if (Predicate.isUndefined(batch)) makeFromList(env.untrack(keyedTargetsOf))
2109
+ const member = memberForKey(key)
2110
+ if (Predicate.isNotUndefined(presence)) {
2111
+ presenceOf[member] = presence
2112
+ // Made in the presence's first render with `initial={false}`: it starts at its targets.
2113
+ if (Bool.and(slotOf[member] === NO_SLOT, PresenceRecord.presenceBlocksInitial(presence))) quietStart.add(member)
2114
+ }
2115
+ return member
2116
+ },
2117
+ }
2118
+
2119
+ // --- By index: `count` members, fixed --------------------------------------------------
2120
+
2121
+ const byIndex = config as BatchConfig
2122
+ const count = Bool.match(keyed, { onTrue: () => 0, onFalse: () => byIndex.count })
2123
+ // The slots, in the order their elements arrived.
2124
+ const entered: Array<number> = []
2125
+ // Every member, by index.
2126
+ const indices: ReadonlyArray<number> = Arr.makeBy(Math.max(1, count), identity).slice(0, count)
2127
+
2128
+ /** By index: every member's targets now, member by member in key order. */
2129
+ const indexTargetsOf = (): Float64Array => {
2130
+ const targets = new Float64Array(count * stride)
2131
+ // Per member at a change, the Batch's own loop (ADR-0025, *Amendment (#665)*).
2132
+ for (let i = 0; i < count; i++) targetsInto(targets, i, byIndex.animate(i) as Readonly<Record<string, unknown>>)
2133
+ return targets
2134
+ }
2135
+
2136
+ const indexForm: MembersForm = {
2137
+ size: () => count,
2138
+ nameOf: indexName,
2139
+ targetsOf: indexTargetsOf,
2140
+ take: (targets) => {
2141
+ current = targets as Float64Array
2142
+ },
2143
+ arrivedSlots: () => entered,
2144
+ inOrder: () => indices,
2145
+ initialOf: (i) => initialOf(byIndex, i),
2146
+ entersNow: () => true,
2147
+ entered: (slot) => {
2148
+ entered.push(slot)
2149
+ },
2150
+ refOf: (i) => {
2151
+ if (!isMember(i, count)) return noMember(i, count)
2152
+ return refs[i]
2153
+ },
2154
+ memberFor: () => fail(`a Batch by index has no \`member(key)\`: give its members \`at(i)\``),
2155
+ }
2156
+
2157
+ const form: MembersForm = Bool.match(keyed, { onTrue: () => keyedForm, onFalse: () => indexForm })
2158
+
2159
+ // --- Its members' moves ----------------------------------------------------------------
2160
+
2161
+ /** Member `i`'s start: its `initial` over each key's identity, or, with `initial: false`, its targets. */
2162
+ // Per member at mount (#540): statements.
2163
+ const startOf = (i: number): Record<string, number> => {
2164
+ // `<AnimatePresence initial={false}>`'s first render (Q46): at its targets, whatever `initial` says.
2165
+ const quiet = quietStart.delete(i)
2166
+ let given = form.initialOf(i)
2167
+ if (quiet) given = undefined
2168
+ let atTargets = quiet
2169
+ if (config.initial === false) atTargets = true
2170
+ return startOn(keys, keyIndex, given, current, i * stride, atTargets, form.nameOf, i)
2171
+ }
2172
+
2173
+ // The runs it forked, interrupted when it's disposed; whether a flight is on, and the members it set off.
2174
+ const fibers = new Set<Fiber.Fiber<void>>()
2175
+ let flying = false
2176
+ let moved = 0
2177
+ let disposed = false
2178
+
2179
+ /** A flight lands once a run ends with nothing moving: a run forked while one ran ends at once. */
2180
+ const ended = (): void => {
2181
+ if (disposed) return
2182
+ if (!flying || Batch.isMoving(made())) return
2183
+ flying = false
2184
+ hooks.landed({ moved })
2185
+ }
2186
+
2187
+ /** After a change: a flight's start, if it set one off, and a run, which does nothing while one runs. */
2188
+ const wake = (setOff: number): void => {
2189
+ if (!Batch.isMoving(made())) return
2190
+ if (!flying) {
2191
+ flying = true
2192
+ moved = 0
2193
+ hooks.started()
2194
+ }
2195
+ moved = moved + setOff
2196
+ // Heard by an observer, not an `Effect.ensuring`: one primitive fewer at each change (#665's profile).
2197
+ const fiber = env.runtime.runFork(Batch.run(made()))
2198
+ fibers.add(fiber)
2199
+ fiber.addObserver(() => {
2200
+ fibers.delete(fiber)
2201
+ ended()
2202
+ })
2203
+ }
2204
+
2205
+ /**
2206
+ * Member `slot`'s target for its `k`th key: its Override stack's (ADR-0070 decision 12, #665's PR 5),
2207
+ * its press's over its hover's over `animate`'s; a Batch Reorder group's item in hand's `x` and `y` where
2208
+ * it's held, over its `whileDrag`'s, over the rest (#712).
2209
+ */
2210
+ // Per member per key at a change: with no member's gesture on, `animate`'s read alone.
2211
+ const targetOf = (slot: number, k: number): number => {
2212
+ const i = memberOf[slot]
2213
+ if (gesturing === 0) return current[i * stride + k]
2214
+ const hand = hands[i]
2215
+ if (Predicate.isNotUndefined(hand)) {
2216
+ if (k === handX) return hand[0]
2217
+ if (k === handY) return hand[1]
2218
+ }
2219
+ const dragged = dragging[i]
2220
+ if (Predicate.isNotUndefined(dragged) && !Number.isNaN(dragged[k])) return dragged[k]
2221
+ const pressed = pressing[i]
2222
+ if (Predicate.isNotUndefined(pressed) && !Number.isNaN(pressed[k])) return pressed[k]
2223
+ const hovered = hovering[i]
2224
+ if (Predicate.isNotUndefined(hovered) && !Number.isNaN(hovered[k])) return hovered[k]
2225
+ const target = current[i * stride + k]
2226
+ if (!Number.isNaN(target)) return target
2227
+ const base = bases[i]
2228
+ if (Predicate.isUndefined(base)) return target
2229
+ return base[k]
2230
+ }
2231
+
2232
+ /**
2233
+ * A change's transitions: one per key, by its name, when every key has its own; else a function of
2234
+ * a member's slot, for the keys on their Default transition, which each member's target decides.
2235
+ */
2236
+ // A function called per member's key cost a change at 1,000 members a call each (#665's profile).
2237
+ const transitionOf = (planned: ReadonlyArray<KeyPlan>): Batch.Transitions | ((slot: number, k: number) => Batch.Transition) => {
2238
+ if (Arr.every(planned, (plan) => Predicate.isNotUndefined(plan.own))) {
2239
+ const byName: Record<string, Batch.Transition> = {}
2240
+ Arr.forEach(keys, (key, k) => {
2241
+ byName[key] = UndefinedOr.getOrThrow(planned[k].own)
2242
+ })
2243
+ return byName
2244
+ }
2245
+ return (slot, k) => {
2246
+ const plan = planned[k]
2247
+ if (Predicate.isNotUndefined(plan.own)) return plan.own
2248
+ return delayedBy(defaultFor(k, targetOf(slot, k)), plan.delay)
2249
+ }
2250
+ }
2251
+
2252
+ /**
2253
+ * `slots` a change moves now: all of them, but those entering this task that `mode="wait"` holds off
2254
+ * the page, which move as they go on (Q46). With none entering, `slots` as they are.
2255
+ */
2256
+ const movingNow = (slots: ReadonlyArray<number>): ReadonlyArray<number> => {
2257
+ if (arrived.length === 0) return slots
2258
+ const entering = new Set(arrived)
2259
+ return Arr.filter(slots, (slot) => Bool.not(Bool.and(entering.has(slot), heldBack(slot))))
2260
+ }
2261
+
2262
+ /** Whether a change now lands at once: its scope's `skipAnimations`, or its transition's (#468). */
2263
+ const skipsNow = (configured: WardConfig.WardicTransition | undefined): boolean => {
2264
+ if (env.skipAnimations()) return true
2265
+ return UndefinedOr.map(configured, (given) => given.skipAnimations) === true
2266
+ }
2267
+
2268
+ /** The change for `slots` now: their targets, with this moment's transitions. */
2269
+ const change = (slots: ReadonlyArray<number>, starts?: HandedStarts): void => {
2270
+ if (slots.length === 0) return
2271
+ // The groups Wardic elements hold of these members that it moves come back first (Q54), from where they've left them.
2272
+ const back = UndefinedOr.match(starts, { onUndefined: () => startsOf(takeBack(slots, changesGroup)), onDefined: identity })
2273
+ const configured = configuredOf()
2274
+ turnOn(slots, configured, staggerOf(configured), back)
2275
+ }
2276
+
2277
+ /**
2278
+ * `slots` turned toward their targets on `configured`, each held by `delay`'s for its rank when given, from
2279
+ * `back`'s starts. The first change after members arrive running their Appear animation, whichever it is
2280
+ * (the arrival's, or a Batch Reorder group's own first), starts each where that has got to (#706).
2281
+ */
2282
+ const turnOn = (slots: ReadonlyArray<number>, configured: WardConfig.WardicTransition | undefined, delay: ((rank: number, n: number) => number) | undefined, back: HandedStarts | undefined): void => {
2283
+ // Its Appear animations' Handoff (#706): at the page's first, after its code has loaded (Q11), its
2284
+ // members drawn by their CSS meanwhile.
2285
+ const startsHandoff = appearing.size > 0 && Predicate.isUndefined(handoffAt)
2286
+ if (startsHandoff && Predicate.isUndefined(handoffModule)) return afterHandoffLoads(() => turnOn(slots, configured, delay, back))
2287
+ const skipped = skipsNow(configured)
2288
+ const reduced = env.reducedMotion()
2289
+ const planned = plannedOf(env.positionalKeys, keys, UndefinedOr.map(configured, unstaggered), reduced)
2290
+ // The first change after members arrive running their Appear animation starts each where that has got
2291
+ // to; every change before its first step starts them the same way, a member arriving then among them.
2292
+ if (startsHandoff) handoffAt = handoffStartAt((slot) => memberRuleKeyOf(slot, planned, reduced, skipped))
2293
+ const startAt = handoffAt
2294
+ // Skipped, every key at once and no stagger; else this moment's transitions, each member held by its rank's delay.
2295
+ const options: Batch.RetargetOptions = Bool.match(skipped, {
2296
+ onTrue: () => ({ transition: INSTANT, ...back, ...startAtOption(startAt) }),
2297
+ onFalse: () => ({ transition: transitionOf(planned), ...UndefinedOr.match(delay, { onUndefined: () => ({}), onDefined: (given) => ({ delay: given }) }), ...back, ...startAtOption(startAt) }),
2298
+ })
2299
+ wake(Batch.retarget(made(), slots, targetOf, options))
2300
+ // A change that took none of them over: no step reads them, so each is let go now.
2301
+ if (Predicate.isNotUndefined(startAt) && !Batch.isMoving(made())) releaseAppearing()
2302
+ }
2303
+
2304
+ // --- The Handoff (#706, ADR-0044 *Amendment (#706)*, Q3, Q8, Q9) --------------------------------------
2305
+
2306
+ // A hydrating Batch's members whose elements run their Appear animation, by slot, as they arrive: what its
2307
+ // arrival change takes over. Read only while it hydrates, and asked for one (Q21; a string read a
2308
+ // member): a client-only Batch never looks, and a member's element running a Wardic element's own Appear
2309
+ // animation, where its Batch didn't ask, stays that element's.
2310
+ let looksForAppear = false
2311
+ if (env.hydrating === true) looksForAppear = config.appear === true
2312
+ const appearing = new Set<number>()
2313
+ // The Handoff's `startAt`, while its first change waits for its first step: every change till then takes it.
2314
+ let handoffAt: ((slot: number) => number) | undefined = undefined
2315
+
2316
+ /**
2317
+ * A member's rule's key, as the server's rule group named its transitions in this change: what its Appear
2318
+ * animation's name is checked against, in development (`env.appearKeyOf`); `None` otherwise.
2319
+ */
2320
+ const memberRuleKeyOf = (slot: number, planned: ReadonlyArray<KeyPlan>, reduced: boolean, skipped: boolean): Option.Option<string> =>
2321
+ UndefinedOr.match(env.appearKeyOf, {
2322
+ onUndefined: () => Option.none(),
2323
+ onDefined: (keyOf) =>
2324
+ keyOf(keys, memberTransitionsOf(keys, planned, (key, target) => env.defaultTransition.transitionFor(key, target) as Batch.Transition, (k) => targetOr(targetOf(slot, k), Batch.get(made(), slot, keys[k] as string)), skipped), reduced, skipped),
2325
+ })
2326
+
2327
+ /** What the Handoff's module reads of this Batch's members running their Appear animation. */
2328
+ const handoffMembers = (keyOf: (slot: number) => Option.Option<string>) => ({
2329
+ appearing,
2330
+ elementOf: (slot: number) => elementOf[memberOf[slot] as number],
2331
+ keyOf: UndefinedOr.map(env.appearKeyOf, () => keyOf),
2332
+ runtime: env.runtime,
2333
+ release: releaseAppearing,
2334
+ })
2335
+
2336
+ /** The first change's `startAt`, its members' times read at its first step (`batch-handoff.ts`, loaded by now). */
2337
+ const handoffStartAt = (keyOf: (slot: number) => Option.Option<string>): ((slot: number) => number) =>
2338
+ UndefinedOr.getOrThrow(handoffModule).startAtOf(handoffMembers(keyOf))
2339
+
2340
+ // Changes that wait for the Handoff's code, run in order once it has loaded; none once it's disposed.
2341
+ let waitingForHandoff: Array<() => void> | undefined = undefined
2342
+ /** `run` once the Handoff's code has loaded, after any change waiting before it; its members let go if it fails to. */
2343
+ const afterHandoffLoads = (run: () => void): void => {
2344
+ if (Predicate.isNotUndefined(waitingForHandoff)) {
2345
+ waitingForHandoff.push(run)
2346
+ return
2347
+ }
2348
+ waitingForHandoff = [run]
2349
+ void loadHandoff(env.runtime).then((module) => {
2350
+ const waiting = UndefinedOr.getOrThrow(waitingForHandoff)
2351
+ waitingForHandoff = undefined
2352
+ if (disposed) return
2353
+ // Not loaded: each member let go of its animation, and moved from its start.
2354
+ if (Predicate.isUndefined(module)) releaseAppearing()
2355
+ Arr.forEach(waiting, (next) => next())
2356
+ })
2357
+ }
2358
+
2359
+ /**
2360
+ * Every member still running its Appear animation let go of it: once the Handoff's first step has read
2361
+ * them, one a change didn't move among them, or each one the Handoff's code never came for.
2362
+ */
2363
+ const releaseAppearing = (): void => {
2364
+ Iter.forEach(appearing, (slot) => UndefinedOr.map(elementOf[memberOf[slot] as number] as (Element & ElementCSSInlineStyle) | undefined, Appear.release))
2365
+ appearing.clear()
2366
+ handoffAt = undefined
2367
+ }
2368
+
2369
+ // --- Hover and press per member (#665's PR 5, ADR-0070 decision 12, Q56–Q60) ----------------------
2370
+
2371
+ // Whether the Batch watches its members' hover and presses yet. What lays their layers on and lifts
2372
+ // them is `batch-gestures.ts`', loaded at its first need (Q62).
2373
+ const listening: Record<"hover" | "press", boolean> = { hover: false, press: false }
2374
+
2375
+ /** The member at `slot` turned toward its Override stack's targets on `transition`: one member, never staggered (Q58). */
2376
+ const turnMember = (slot: number, transition: WardConfig.WardicTransition | undefined): void =>
2377
+ turnOn([slot], transition, undefined, startsOf(takeBack([slot], changesGroup)))
2378
+
2379
+ /**
2380
+ * Member `i`'s gestures dropped with its element (Q59): with its slot kept (its element replaced), back
2381
+ * toward `animate`'s on the Batch's transition, as at a gesture's end; its next one starts afresh.
2382
+ */
2383
+ const ungesture = (i: number): void => {
2384
+ let on = 0
2385
+ if (Predicate.isNotUndefined(hovering[i])) on++
2386
+ if (Predicate.isNotUndefined(pressing[i])) on++
2387
+ if (Predicate.isNotUndefined(dragging[i])) on++
2388
+ if (Predicate.isNotUndefined(hands[i])) on++
2389
+ if (on === 0) return
2390
+ hovering[i] = undefined
2391
+ pressing[i] = undefined
2392
+ dragging[i] = undefined
2393
+ hands[i] = undefined
2394
+ const slot = slotOf[i]
2395
+ if (Bool.and(slot !== NO_SLOT, !disposed)) turnMember(slot, configuredOf())
2396
+ // Counted until it's turned, so `targetOf` reads its bases.
2397
+ gesturing -= on
2398
+ bases[i] = undefined
2399
+ }
2400
+
2401
+ /** Where member `i`'s keys only `values` give were as they came on, kept for its layers' end. */
2402
+ // Per gesture start, a loop over the Batch's keys (#665).
2403
+ const baseFor = (i: number, slot: number, values: Float64Array): void => {
2404
+ let base = bases[i]
2405
+ for (let k = 0; k < stride; k++) {
2406
+ if (Number.isNaN(values[k])) continue
2407
+ if (!Number.isNaN(current[i * stride + k])) continue
2408
+ if (Predicate.isUndefined(base)) {
2409
+ base = new Float64Array(stride).fill(Number.NaN)
2410
+ bases[i] = base
2411
+ }
2412
+ // Kept from the first layer that gave it.
2413
+ if (!Number.isNaN(base[k])) continue
2414
+ base[k] = Batch.get(made(), slot, keys[k])
2415
+ }
2416
+ }
2417
+
2418
+ /** Whether member `i` has no gesture layer on. */
2419
+ const noLayer = (i: number): boolean =>
2420
+ Bool.and(Bool.and(Predicate.isUndefined(hovering[i]), Predicate.isUndefined(pressing[i])), Predicate.isUndefined(dragging[i]))
2421
+
2422
+ // --- A Batch Reorder group's item in hand (#712, ADR-0072 decision 7) ---------------------------------
2423
+
2424
+ // The member a hand's change moves, by its place in the Batch's run, reused at each drag sample.
2425
+ const handMovers: Array<number> = [NO_SLOT]
2426
+ // A hand let go: where its `x` and `y` start from, and their speeds, `[x, y, vx, vy]`.
2427
+ const handLetGo = new Float64Array(4)
2428
+ // Per key at the hand's change, core's retarget calling them (the hot path): statements.
2429
+ const letGoFrom = (_: number, k: number): number => {
2430
+ if (k === handX) return handLetGo[0]
2431
+ if (k === handY) return handLetGo[1]
2432
+ return Number.NaN
2433
+ }
2434
+ const letGoSpeed = (_: number, k: number): number => {
2435
+ if (k === handX) return handLetGo[2]
2436
+ if (k === handY) return handLetGo[3]
2437
+ return 0
2438
+ }
2439
+ const LET_GO: HandedStarts = { from: letGoFrom, velocity: letGoSpeed }
2440
+
2441
+ /** Member `i`'s hand, made as it's first held: counted with its layers, and the Batch's `x` and `y` found. */
2442
+ // A change of one member, batch.ts's site (#665): statements.
2443
+ const handOf = (i: number): Float64Array => {
2444
+ const known = hands[i]
2445
+ if (Predicate.isNotUndefined(known)) return known
2446
+ const made = new Float64Array(2)
2447
+ hands[i] = made
2448
+ gesturing++
2449
+ handX = keyIndexOr(keyIndex.get("x"))
2450
+ handY = keyIndexOr(keyIndex.get("y"))
2451
+ return made
2452
+ }
2453
+
2454
+ /** Member `i` held at (`x`, `y`): its `x` and `y` there at the next frame, with no spring. */
2455
+ const handAt = (i: number, x: number, y: number): void => {
2456
+ const slot = slotOf[i]
2457
+ if (Bool.or(slot === NO_SLOT, disposed)) return
2458
+ const hand = handOf(i)
2459
+ hand[0] = x
2460
+ hand[1] = y
2461
+ handMovers[0] = slot
2462
+ wake(Batch.retarget(made(), handMovers, targetOf, IN_HAND))
2463
+ }
2464
+
2465
+ /** Member `i` let go: from where it was held, at (`vx`, `vy`) a second, toward its Override stack's targets. */
2466
+ const handOff = (i: number, vx: number, vy: number): void => {
2467
+ const hand = hands[i]
2468
+ if (Predicate.isUndefined(hand)) return
2469
+ hands[i] = undefined
2470
+ handLetGo[0] = hand[0]
2471
+ handLetGo[1] = hand[1]
2472
+ handLetGo[2] = vx
2473
+ handLetGo[3] = vy
2474
+ const slot = slotOf[i]
2475
+ if (Bool.and(slot !== NO_SLOT, !disposed)) turnOn([slot], configuredOf(), undefined, LET_GO)
2476
+ // Counted until it's turned, so `targetOf` read its hand's keys from its stack.
2477
+ gesturing--
2478
+ }
2479
+
2480
+ // --- A change that moves the targets under its members (#712) ----------------------------------------
2481
+
2482
+ // A key's speed as `shiftedFrom` found it, for `shiftedSpeed`, which core reads right after, the same key.
2483
+ let shiftedVelocity = 0
2484
+ /** Where `slot`'s `k`th key starts as its target moves under it: as far off its new target as off its old; `NaN`, unmoved. */
2485
+ // Per member per key at the change (batch.ts's site, #665): statements.
2486
+ const shiftedFrom = (slot: number, k: number): number => {
2487
+ const next = targetOf(slot, k)
2488
+ const was = Batch.target(made(), slot, keys[k])
2489
+ if (Number.isNaN(next) || Number.isNaN(was) || next === was) return Number.NaN
2490
+ shiftedVelocity = Batch.velocity(made(), slot, keys[k])
2491
+ return Batch.get(made(), slot, keys[k]) + next - was
2492
+ }
2493
+ const shiftedSpeed = (): number => shiftedVelocity
2494
+ const SHIFTED: HandedStarts = { from: shiftedFrom, velocity: shiftedSpeed }
2495
+
2496
+ /** What its gestures work its members through. */
2497
+ const gestureHost: BatchGestureHost = {
2498
+ memberElementOf: (node) => {
2499
+ if (!Predicate.isObject(node)) return Option.none()
2500
+ // Any node's object: a WeakMap read, which an element this Batch drew answers.
2501
+ const entry = MEMBER_ELEMENTS.get(node as unknown as Element)
2502
+ if (Predicate.isUndefined(entry)) return Option.none()
2503
+ if (entry.binding !== binding) return Option.none()
2504
+ return Option.some(node)
2505
+ },
2506
+ memberAt: (element) => UndefinedOr.map(MEMBER_ELEMENTS.get(element as Element), (entry) => entry.member),
2507
+ layered: (layer, i) => Predicate.isNotUndefined(layers[layer][i]),
2508
+ layer: (layer, i, values, transition) => {
2509
+ const slot = slotOf[i]
2510
+ if (slot === NO_SLOT) return
2511
+ const was = layers[layer][i]
2512
+ if (Predicate.isNotUndefined(values)) {
2513
+ if (Predicate.isUndefined(was)) gesturing++
2514
+ baseFor(i, slot, values)
2515
+ }
2516
+ layers[layer][i] = values
2517
+ // A leaver's exit holds its keys (Q47), and lands: its gestures move nothing.
2518
+ if (Predicate.isUndefined(exits[i])) turnMember(slot, transition)
2519
+ if (Predicate.isNotUndefined(values)) return
2520
+ if (Predicate.isUndefined(was)) return
2521
+ // Lifted: counted until it's turned, so `targetOf` read its bases.
2522
+ gesturing--
2523
+ if (noLayer(i)) bases[i] = undefined
2524
+ },
2525
+ keys: () => keys,
2526
+ nameOf: (i) => form.nameOf(i),
2527
+ indexOf: (i) => indexOf[i],
2528
+ itemOf: (i) => itemOf[i],
2529
+ keyed,
2530
+ untrack: env.untrack,
2531
+ configured: configuredOf,
2532
+ // Read as each gesture starts: a Batch Reorder group's are its props now (#712).
2533
+ get hoverGiven() {
2534
+ return (config as { readonly whileHover?: unknown }).whileHover
2535
+ },
2536
+ get tapGiven() {
2537
+ return (config as { readonly whileTap?: unknown }).whileTap
2538
+ },
2539
+ pressKeys: env.pressKeys,
2540
+ dragGiven: () => (config as { readonly whileDrag?: unknown }).whileDrag,
2541
+ tell: (told) => UndefinedOr.map(hooks.gesture, (tellIt) => tellIt(told)),
2542
+ handAt,
2543
+ handOff,
2544
+ }
2545
+
2546
+ /**
2547
+ * Its members' hover, or presses, watched from now on (Q60): once each. Presses start hover first, so a
2548
+ * release off a member tells its hover's end before its press's whatever was asked first, as a Wardic
2549
+ * element's do; and make each pressable member's element focusable (Q57).
2550
+ */
2551
+ const listen = (gesture: "hover" | "press"): void => {
2552
+ const watches = env.gestures
2553
+ if (Predicate.isUndefined(watches)) return
2554
+ if (disposed) return
2555
+ if (listening[gesture]) return
2556
+ if (gesture === "press") listen("hover")
2557
+ listening[gesture] = true
2558
+ if (gesture === "press") {
2559
+ Arr.forEach(elementOf, (el) => {
2560
+ if (Predicate.isNotUndefined(el)) KeyboardPress.makeFocusable(el)
2561
+ })
2562
+ }
2563
+ watches.listen(gesture, gestureHost)
2564
+ }
2565
+
2566
+ // --- The latest driver (#665's PR 4, ADR-0069 decision 17, Q52–Q54) ---------------------------------
2567
+
2568
+ // Each member's groups a Wardic element on its element holds; each held element's groups, as bits; and
2569
+ // each group's keys' indices, from `makeBatch`.
2570
+ const heldBy: Array<HeldMember | undefined> = []
2571
+ const masks = new Map<Element, number>()
2572
+ const groupKs: Record<BatchGroup, ReadonlyArray<number>> = { transform: [], opacity: [] }
2573
+
2574
+ /** Member `i`'s `group` drawn by the Batch again. */
2575
+ const unmask = (i: number, group: BatchGroup): void => {
2576
+ const held = heldBy[i]
2577
+ if (Predicate.isUndefined(held)) return
2578
+ held.groups.delete(group)
2579
+ const left = bitsOf(held.el) & ~GROUP_BITS[group]
2580
+ if (left !== 0) {
2581
+ masks.set(held.el, left)
2582
+ return
2583
+ }
2584
+ masks.delete(held.el)
2585
+ heldBy[i] = undefined
2586
+ }
2587
+
2588
+ /** Member `i`'s held groups let go with its element: the Batch draws it no more, or another element now. */
2589
+ const letGo = (i: number): void => {
2590
+ const held = heldBy[i]
2591
+ if (Predicate.isUndefined(held)) return
2592
+ masks.delete(held.el)
2593
+ heldBy[i] = undefined
2594
+ }
2595
+
2596
+ /** An element's held groups' bits: 0 for none. */
2597
+ const bitsOf = (el: Element): number => UndefinedOr.match(masks.get(el), { onUndefined: () => 0, onDefined: identity })
2598
+
2599
+ /** Whether a change toward the members' targets moves `slot`'s `group`: a key of it whose target it changes. */
2600
+ // Per held member's group at a change (#665): statements.
2601
+ const changesGroup = (slot: number, group: BatchGroup): boolean => {
2602
+ const ks = groupKs[group]
2603
+ for (let n = 0; n < ks.length; n++) {
2604
+ const k = ks[n]
2605
+ const goal = targetOf(slot, k)
2606
+ if (Number.isNaN(goal)) continue
2607
+ if (goal !== Batch.target(made(), slot, keys[k])) return true
2608
+ }
2609
+ return false
2610
+ }
2611
+
2612
+ /** Whether `given(slot, k)` gives a key of `group`: a driven change's or an exit's, which moves it. */
2613
+ // Per held member's group at a call (#665): statements.
2614
+ const givesGroup = (given: (slot: number, k: number) => boolean) => (slot: number, group: BatchGroup): boolean => {
2615
+ const ks = groupKs[group]
2616
+ for (let n = 0; n < ks.length; n++) {
2617
+ if (given(slot, ks[n])) return true
2618
+ }
2619
+ return false
2620
+ }
2621
+
2622
+ /** A handover's starts, for a change: each handed key's value and speed, `NaN` (and 0) for the rest. */
2623
+ const startsOf = (byMember: ReadonlyMap<number, BatchHandover> | undefined): HandedStarts | undefined => {
2624
+ if (Predicate.isUndefined(byMember)) return undefined
2625
+ // Per member per key at a change (#665): statements.
2626
+ const handed = (slot: number, k: number, of: (back: BatchHandover) => Readonly<Record<string, number>>, none: number): number => {
2627
+ const back = byMember.get(memberOf[slot])
2628
+ if (Predicate.isUndefined(back)) return none
2629
+ const value = of(back)[keys[k]]
2630
+ if (Predicate.isUndefined(value)) return none
2631
+ return value
2632
+ }
2633
+ return {
2634
+ from: (slot, k) => handed(slot, k, (back) => back.values, Number.NaN),
2635
+ velocity: (slot, k) => handed(slot, k, (back) => back.velocities, 0),
2636
+ }
2637
+ }
2638
+
2639
+ /**
2640
+ * The groups Wardic elements hold of `slots`' members that a change `moves`, taken back for it (Q54):
2641
+ * each from where its holder leaves it, but one its holder keeps through it. Each member's handover,
2642
+ * or `undefined` for none.
2643
+ */
2644
+ const takeBack = (slots: ReadonlyArray<number>, moves: (slot: number, group: BatchGroup) => boolean): ReadonlyMap<number, BatchHandover> | undefined => {
2645
+ if (masks.size === 0) return undefined
2646
+ let byMember: Map<number, BatchHandover> | undefined
2647
+ // Per held member at a change (#665): statements. Deleting the entry being visited is safe in a Map's iteration.
2648
+ Arr.forEach(slots, (slot) => {
2649
+ const i = memberOf[slot]
2650
+ const held = heldBy[i]
2651
+ if (Predicate.isUndefined(held)) return
2652
+ Iter.forEach(held.groups, ([group, holder]) => {
2653
+ if (!moves(slot, group)) return
2654
+ if (holder.keepsThrough(group)) return
2655
+ const back = holder.surrender(group)
2656
+ unmask(i, group)
2657
+ if (Predicate.isUndefined(back)) return
2658
+ if (Predicate.isUndefined(byMember)) byMember = new Map()
2659
+ const was = byMember.get(i)
2660
+ if (Predicate.isUndefined(was)) {
2661
+ byMember.set(i, back)
2662
+ return
2663
+ }
2664
+ byMember.set(i, { values: { ...was.values, ...back.values }, velocities: { ...was.velocities, ...back.velocities } })
2665
+ })
2666
+ })
2667
+ return byMember
2668
+ }
2669
+
2670
+ /**
2671
+ * Before a driven change of `slots` (an `animate` call's, a sequence's, a keyed Batch's exits): the
2672
+ * groups Wardic elements hold of them that it `moves`, taken back, each turned from there toward its
2673
+ * targets, which the change then takes as it plays.
2674
+ */
2675
+ const retakeFor = (slots: ReadonlyArray<number>, moves: (slot: number, group: BatchGroup) => boolean): void => {
2676
+ const back = takeBack(slots, moves)
2677
+ if (Predicate.isUndefined(back)) return
2678
+ change(Arr.filter(slots, (slot) => back.has(memberOf[slot])), startsOf(back))
2679
+ }
2680
+
2681
+ /** A Wardic element on member `i`'s element takes its `group` (Q53). */
2682
+ const yieldGroup = (i: number, group: BatchGroup, holder: BatchHolder): BatchYield | undefined => {
2683
+ const slot = slotOf[i]
2684
+ if (slot === NO_SLOT) return undefined
2685
+ const el = elementOf[i]
2686
+ if (Predicate.isUndefined(el)) return undefined
2687
+ const ks = groupKs[group]
2688
+ if (ks.length === 0) return undefined
2689
+ const inGroup: Array<string> = []
2690
+ const values: Record<string, number> = {}
2691
+ const velocities: Record<string, number> = {}
2692
+ // Per key of a group a Wardic element takes (#665): statements.
2693
+ Arr.forEach(ks, (k) => {
2694
+ const key = keys[k]
2695
+ inGroup.push(key)
2696
+ values[key] = Batch.get(made(), slot, key)
2697
+ velocities[key] = Batch.velocity(made(), slot, key)
2698
+ })
2699
+ let held = heldBy[i]
2700
+ if (Predicate.isUndefined(held)) {
2701
+ held = { el, groups: new Map() }
2702
+ heldBy[i] = held
2703
+ }
2704
+ held.groups.set(group, holder)
2705
+ masks.set(el, bitsOf(el) | GROUP_BITS[group])
2706
+ return { keys: inGroup, values, velocities }
2707
+ }
2708
+
2709
+ /** What member `i`'s `key` is drawn at now: its Batch value, a transform key it hasn't at its identity, or none. */
2710
+ const drawnValueOf = (i: number, key: string): number | undefined => {
2711
+ const group = batchGroupOf(key)
2712
+ if (Predicate.isUndefined(group)) return undefined
2713
+ const slot = slotOf[i]
2714
+ if (slot === NO_SLOT) return undefined
2715
+ if (keyIndex.has(key)) return Batch.get(made(), slot, key)
2716
+ if (groupKs[group].length === 0) return undefined
2717
+ return identityOf(key)
2718
+ }
2719
+
2720
+ /**
2721
+ * The Wardic element gives member `i`'s `group` back (Q54): the Batch draws it again, from there, toward
2722
+ * its targets. A leaver mid-exit is drawn where its exit has it, which its element goes as it lands.
2723
+ */
2724
+ const reclaim = (i: number, group: BatchGroup, back: BatchHandover): void => {
2725
+ unmask(i, group)
2726
+ if (disposed) return
2727
+ const slot = slotOf[i]
2728
+ if (slot === NO_SLOT) return
2729
+ if (Predicate.isNotUndefined(exits[i])) return
2730
+ change([slot], startsOf(new Map([[i, back]])))
2731
+ }
2732
+
2733
+ // Elements that arrived this task: entered at once, turned toward their targets together at its end.
2734
+ let arrived: Array<number> = []
2735
+ let flushing = false
2736
+ const flushArrivals = (): void => {
2737
+ flushing = false
2738
+ if (disposed) return
2739
+ settleWaiting()
2740
+ settleUnlisted()
2741
+ // An element `mode="wait"` holds off the page moves as it goes on (Q46).
2742
+ const slots = Arr.filter(arrived, (slot) => !heldBack(slot))
2743
+ arrived = []
2744
+ change(slots)
2745
+ }
2746
+ /** The task's arrivals flushed at its end, once. */
2747
+ const flushSoon = (): void => {
2748
+ if (flushing) return
2749
+ flushing = true
2750
+ queueMicrotask(flushArrivals)
2751
+ }
2752
+
2753
+ /** `el` drawn now at `values`, one per key, and turned about its own centre inside an `<svg>`, as the renderer's. */
2754
+ const drawNow = (el: Element, values: ReadonlyArray<number>): void => {
2755
+ if (Svg.isInner(el)) {
2756
+ const style = (el as SVGElement).style
2757
+ style.setProperty("transform-box", "fill-box")
2758
+ style.setProperty("transform-origin", "50% 50%")
2759
+ }
2760
+ write(el, Float64Array.from(values), 0)
2761
+ }
2762
+
2763
+ /** `el` no longer known to `animate` as member `i`'s element, unless another member has it now. */
2764
+ const forget = (el: Element, i: number): void => {
2765
+ letGo(i)
2766
+ ungesture(i)
2767
+ if (MEMBER_ELEMENTS.get(el) === entries[i]) MEMBER_ELEMENTS.delete(el)
2768
+ }
2769
+
2770
+ /** Member `i` entered on `el`, drawn at its start now, its move with every member that arrives this task, at its end. */
2771
+ const enter = (i: number, el: Element): void => {
2772
+ const start = startOf(i)
2773
+ const entering = Batch.enter(made(), el, start)
2774
+ slotOf[i] = entering
2775
+ // Hydrating, its element may run its Appear animation (#706): the arrival change takes it over. A
2776
+ // client-only Batch reads nothing of it. Per member at mount (#540): statements.
2777
+ if (looksForAppear) {
2778
+ if (Appear.pending(el as ElementCSSInlineStyle & Element)) appearing.add(entering)
2779
+ }
2780
+ memberOf[entering] = i
2781
+ form.entered(entering)
2782
+ drawNow(el, Arr.map(keys, (key) => start[key]))
2783
+ flushSoon()
2784
+ arrived.push(entering)
2785
+ }
2786
+
2787
+ /** Whether another Batch draws `el`: it's a member's element there. */
2788
+ const drawnByAnother = (el: Element): boolean => {
2789
+ const other = MEMBER_ELEMENTS.get(el)
2790
+ if (Predicate.isUndefined(other)) return false
2791
+ return other.binding !== binding
2792
+ }
2793
+
2794
+ const arrive = (i: number, el: Element): void => {
2795
+ if (disposed) return
2796
+ if (elementOf[i] === el) return
2797
+ // One Batch draws an element (Q52): a second's would write over the first's. One with a layout node
2798
+ // can't be a member: the projection measures it under the transform the Batch draws.
2799
+ if (drawnByAnother(el)) return fail(`an element (${elementName(el)}) is a member of two Batches: one Batch draws an element's \`transform\` and \`opacity\``)
2800
+ if (LAYOUT_ELEMENTS.has(el)) return fail(layoutOnMember(el))
2801
+ const was = elementOf[i]
2802
+ if (Predicate.isNotUndefined(was)) forget(was, i)
2803
+ elementOf[i] = el
2804
+ // Known to `animate`, as member `i`'s element (Q14).
2805
+ MEMBER_ELEMENTS.set(el, UndefinedOr.getOrThrow(entries[i]))
2806
+ // Pressable, it's focusable, so a key can press it (Q57): called here, not through the lazily loaded
2807
+ // gestures, whose route cost a mount more than the check (#709, Q2).
2808
+ if (listening.press) KeyboardPress.makeFocusable(el)
2809
+ // Keyed, under `<AnimatePresence>`: watched there, so its leave plays its exit (Q46).
2810
+ watchOn(i, el)
2811
+ const slot = slotOf[i]
2812
+ // A new element for a member: it takes the member over, its values, speed and delays as they are.
2813
+ if (slot !== NO_SLOT) {
2814
+ Batch.replace(made(), slot, el)
2815
+ drawNow(el, Arr.map(keys, (key) => Batch.get(made(), slot, key)))
2816
+ return
2817
+ }
2818
+ // Keyed, before the list has its key, or before the Batch is made: at the task's end, or a later change.
2819
+ if (!form.entersNow(i)) {
2820
+ waiting.push(i)
2821
+ flushSoon()
2822
+ return
2823
+ }
2824
+ enter(i, el)
2825
+ }
2826
+
2827
+ /** One stop's value for member `i`: a number, or a function's of its index and the count. */
2828
+ const stopAt = (key: string, stop: unknown, i: number): number => {
2829
+ let value = stop
2830
+ if (Predicate.isFunction(stop)) value = stop(indexOf[i], form.size())
2831
+ if (Predicate.isNumber(value)) return value
2832
+ return fail(`an animate call's "${key}" gives ${form.nameOf(i)} ${JSON.stringify(value)}: a Batch takes numbers`)
2833
+ }
2834
+
2835
+ /** The slots an `animate` call moves: every member's there is, or the members it names, in order, whose elements have arrived. */
2836
+ const callSlotsOf = (named: ReadonlyArray<number> | undefined): ReadonlyArray<number> =>
2837
+ UndefinedOr.match(named, {
2838
+ // A copy: the call keeps it, and members arrive after.
2839
+ onUndefined: () => [...form.arrivedSlots()],
2840
+ onDefined: (given) => Arr.filter(Arr.map(given, (i) => slotOf[i]), (slot) => slot !== NO_SLOT),
2841
+ })
2842
+
2843
+ /** Where an element call's `key` goes for a member's element (Q14, Q33). */
2844
+ const routeOf = (key: string): KeyRoute => {
2845
+ if (keyIndex.has(key)) return "batch"
2846
+ if (!drawn.has("transform")) return "free"
2847
+ if (key === "transform") return "drawn"
2848
+ if (key === "opacity") return "free"
2849
+ if (DomBatch.writer.writes(key)) return "drawn"
2850
+ return "free"
2851
+ }
2852
+
2853
+
2854
+ /** A track that moves nothing: a call before a keyed Batch has members, which finishes at its play (Q51). */
2855
+ const landedTrack = (settled: () => void): BatchTrack => ({ run: settled, stop: noop, cancel: noop, duration: () => 0 })
2856
+
2857
+ /** An `animate` call's track: its members' targets and first stops by key, its own transitions, its Playhead. */
2858
+ const track = (call: BatchCall): BatchTrack => {
2859
+ if (Predicate.isUndefined(batch)) return landedTrack(call.settled)
2860
+ const slots = callSlotsOf(call.members)
2861
+ // Each member's stops by key, its target and its first, `NaN` for none: worked out once, at the call.
2862
+ const tos = new Float64Array(capacity * stride).fill(Number.NaN)
2863
+ const froms = new Float64Array(capacity * stride).fill(Number.NaN)
2864
+ let firsts = false
2865
+ const given = call.target as Readonly<Record<string, unknown>>
2866
+ Arr.forEach(Rec.keys(given), (key) => {
2867
+ const k = keyIndex.get(key)
2868
+ if (Predicate.isUndefined(k)) return fail(`an animate call gives "${key}", which isn't one of the Batch's keys (${keys.join(", ")})`)
2869
+ const value = given[key]
2870
+ // Per member per key at a call (#665): statements.
2871
+ Arr.forEach(slots, (slot) => {
2872
+ const i = memberOf[slot]
2873
+ const at = i * stride + k
2874
+ let stops = value
2875
+ if (Predicate.isFunction(value)) stops = value(indexOf[i], form.size())
2876
+ if (isPair(stops)) {
2877
+ froms[at] = stopAt(key, stops[0], i)
2878
+ tos[at] = stopAt(key, stops[1], i)
2879
+ firsts = true
2880
+ return
2881
+ }
2882
+ if (Predicate.isNumber(stops)) {
2883
+ tos[at] = stops
2884
+ return
2885
+ }
2886
+ return fail(`an animate call's "${key}" is ${JSON.stringify(stops)}: a Batch takes a number or two, its first and its target, or a function of a member's index that gives them`)
2887
+ })
2888
+ })
2889
+ const fromOf = (slot: number, k: number): number => froms[memberOf[slot] * stride + k]
2890
+ const toOf = (slot: number, k: number): number => tos[memberOf[slot] * stride + k]
2891
+ // The groups Wardic elements hold of its members that it moves come back first, from where they've left them (Q54).
2892
+ retakeFor(slots, givesGroup((slot, k) => !Number.isNaN(toOf(slot, k))))
2893
+ return changeOn(slots, toOf, Bool.match(firsts, { onTrue: () => fromOf, onFalse: () => undefined }), call)
2894
+ }
2895
+
2896
+ /**
2897
+ * A driven change of `slots` toward `targetOf`, from `fromOf`'s first stops when it gives them, on its
2898
+ * call's transitions (which the Batch copies for it, so the Playhead driving them reaches its keys
2899
+ * alone), its `stagger()` counting the members it moves: an `animate` call's, or a keyed Batch's exits.
2900
+ */
2901
+ const changeOn = (
2902
+ slots: ReadonlyArray<number>,
2903
+ targetOf: (slot: number, k: number) => number,
2904
+ fromOf: ((slot: number, k: number) => number) | undefined,
2905
+ call: Pick<BatchCall, "transition" | "reducedMotion" | "skipAnimations" | "head" | "settled"> & { readonly onMemberLanded?: (slot: number) => void },
2906
+ ): BatchTrack => {
2907
+ const transition = Bool.match(call.skipAnimations, {
2908
+ onTrue: () => (): Batch.Transition => INSTANT,
2909
+ onFalse: () => {
2910
+ const planned = plannedOf(env.positionalKeys, keys, UndefinedOr.map(call.transition, unstaggered), call.reducedMotion)
2911
+ return (slot: number, k: number): Batch.Transition => {
2912
+ const plan = planned[k]
2913
+ if (Predicate.isNotUndefined(plan.own)) return plan.own
2914
+ return delayedBy(defaultFor(k, targetOf(slot, k)), plan.delay)
2915
+ }
2916
+ },
2917
+ })
2918
+ const options: { -readonly [K in keyof Batch.AnimateOptions]: Batch.AnimateOptions[K] } = { head: call.head, transition, onLanded: call.settled }
2919
+ if (Predicate.isNotUndefined(fromOf)) options.from = fromOf
2920
+ if (Predicate.isNotUndefined(call.onMemberLanded)) options.onMemberLanded = call.onMemberLanded
2921
+ const delay = Bool.match(call.skipAnimations, { onTrue: () => undefined, onFalse: () => staggerOf(call.transition) })
2922
+ if (Predicate.isNotUndefined(delay)) options.delay = delay
2923
+ return controlsOf(Batch.animate(made(), slots, targetOf, options))
2924
+ }
2925
+
2926
+ /** Whether member `i`'s element has arrived. */
2927
+ const hasArrived = (i: number): boolean => slotOf[i] !== NO_SLOT
2928
+
2929
+ /** The members a sequence's Segment moves (Q39): every member whose element has arrived, in the list's order, or those `named` names once theirs have. */
2930
+ const membersOf = (named: ReadonlyArray<number> | undefined): ReadonlyArray<number> =>
2931
+ Arr.filter(UndefinedOr.match(named, { onUndefined: form.inOrder, onDefined: identity }), hasArrived)
2932
+
2933
+ /** A sequence's Segment of the Batch (Q38, Q39): its members, and each key's value, a function's called with a member's index and the count. */
2934
+ const segmentOf = (named: ReadonlyArray<number> | undefined, target: Readonly<Record<string, unknown>>): BatchSegment => {
2935
+ if (Predicate.isUndefined(batch)) return { subjects: [], values: {} }
2936
+ const moving = membersOf(named)
2937
+ const values: Record<string, Sequence.Value> = {}
2938
+ Arr.forEach(Rec.keys(target), (key) => {
2939
+ const value = target[key]
2940
+ if (Predicate.isUndefined(value)) return
2941
+ if (!keyIndex.has(key)) return fail(`a sequence's Segment of a Batch gives "${key}", which isn't one of its keys (${keys.join(", ")})`)
2942
+ if (Predicate.isFunction(value)) {
2943
+ values[key] = (index: number) => segmentValueOf(key, value(indexOf[moving[index]], form.size()), form.nameOf(moving[index]))
2944
+ return
2945
+ }
2946
+ values[key] = segmentValueOf(key, value, undefined)
2947
+ })
2948
+ return { subjects: Arr.map(moving, (i) => UndefinedOr.getOrThrow(entries[i])), values }
2949
+ }
2950
+
2951
+ /** A sequence's Segment of members' elements (Q40): a Batch key's value a number, `null` or stops; no transform the Batch draws without it. */
2952
+ const checkElementSegment = (target: Readonly<Record<string, unknown>>): void =>
2953
+ Arr.forEach(Rec.keys(target), (key) => {
2954
+ const route = routeOf(key)
2955
+ if (route === "drawn") return drawnKey(key)
2956
+ if (route === "batch") segmentValueOf(key, target[key], undefined)
2957
+ })
2958
+
2959
+ /**
2960
+ * A sequence's track over its members (#665, Q36): each member's Batch keys through the stops and
2961
+ * tween core's Sequence compiled for it; reduced motion's Snap of a positional key, or `skipAnimations`,
2962
+ * landing it at once where its run would end, as an element's.
2963
+ */
2964
+ const sequenceTrack = (call: BatchSequenceCall): BatchTrack => {
2965
+ if (Predicate.isUndefined(batch)) return landedTrack(call.settled)
2966
+ const slots: Array<number> = []
2967
+ const animations: Array<Sequence.Animation | undefined> = []
2968
+ Arr.forEach(call.members, (i, n) => {
2969
+ const slot = slotOf[i]
2970
+ if (slot === NO_SLOT) return
2971
+ slots.push(slot)
2972
+ animations[slot] = call.animations[n]
2973
+ })
2974
+ // The groups Wardic elements hold of its members that it moves come back first (Q54).
2975
+ retakeFor(slots, givesGroup((slot, k) => Predicate.isNotUndefined(UndefinedOr.getOrThrow(animations[slot]).keyframes[keys[k]])))
2976
+ // Per member per key, once at its first play (#665): statements.
2977
+ const keyframesOf = (slot: number, k: number): Batch.Keyframes | undefined => {
2978
+ const key = keys[k]
2979
+ const animation = UndefinedOr.getOrThrow(animations[slot])
2980
+ const given = animation.keyframes[key]
2981
+ if (Predicate.isUndefined(given)) return undefined
2982
+ const transition = UndefinedOr.getOrThrow(animation.transition[key])
2983
+ const stops = Arr.map(given, stopNumber)
2984
+ const snaps = call.reducedMotion && env.positionalKeys.isPositional(key)
2985
+ if (!call.skipAnimations && !snaps) return { stops, transition }
2986
+ // Where its run would end, from where it is: after its delay for reduced motion's Snap, at once when
2987
+ // skipped. Its last stop is its last number: a sequence ends a key with a `null` when its last Segment ends first.
2988
+ const end = ReducedMotion.endOf(stops[0], lastNumber(stops), transition)
2989
+ let delay = 0
2990
+ if (!call.skipAnimations && Predicate.isNotUndefined(transition.delay)) delay = transition.delay
2991
+ return { stops: [Number.NaN, end], transition: landingAfter(delay) }
2992
+ }
2993
+ return controlsOf(Batch.keyframes(made(), slots, keyframesOf, { head: call.head, onLanded: call.settled }))
2994
+ }
2995
+
2996
+ /** A driven change's controls, as an `animate` call's track: played, it wakes the Batch's run. */
2997
+ const controlsOf = (animation: Batch.Animation): BatchTrack => ({
2998
+ run: () => {
2999
+ if (disposed) return
3000
+ wake(Batch.play(animation))
3001
+ },
3002
+ stop: () => {
3003
+ Batch.stop(animation)
3004
+ wake(0)
3005
+ },
3006
+ cancel: () => {
3007
+ Batch.cancel(animation)
3008
+ wake(0)
3009
+ },
3010
+ duration: () => Batch.durationOf(animation),
3011
+ })
3012
+
3013
+ const bound: BatchBinding = {
3014
+ track,
3015
+ entryOf: (i) => UndefinedOr.getOrThrow(entries[i]),
3016
+ routeOf,
3017
+ segmentOf,
3018
+ checkElementSegment,
3019
+ sequenceTrack,
3020
+ elementOf: (i) => elementOf[i],
3021
+ yieldGroup,
3022
+ reclaim,
3023
+ drawnValueOf,
3024
+ listen,
3025
+ host: gestureHost,
3026
+ targetsOf: () => form.targetsOf(),
3027
+ apply: (targets) => {
3028
+ if (disposed) return
3029
+ form.take(targets)
3030
+ if (Predicate.isUndefined(batch)) return
3031
+ change(movingNow(form.arrivedSlots()))
3032
+ },
3033
+ applyShifted: (targets) => {
3034
+ if (disposed) return
3035
+ form.take(targets)
3036
+ if (Predicate.isUndefined(batch)) return
3037
+ turnOn(movingNow(form.arrivedSlots()), configuredOf(), undefined, SHIFTED)
3038
+ Batch.draw(made())
3039
+ },
3040
+ refOf: (i) => form.refOf(i),
3041
+ memberFor: (key, presence) => form.memberFor(key, presence),
3042
+ namedOf: (entry) => {
3043
+ if (Predicate.isUndefined(entry.member)) return undefined
3044
+ // A keyed handle kept past its member's leave names nothing: its number may be another key's now.
3045
+ if (entries[entry.member] !== entry) return []
3046
+ return [entry.member]
3047
+ },
3048
+ styleOf: <Style>(style: Style): Style => ownStyleOf(style, drawn),
3049
+ dispose: () => {
3050
+ disposed = true
3051
+ // Its leavers let go at once, uncompleted, and its held elements' holds: a presence waits on them no more.
3052
+ Arr.forEach(Arr.map(exits, (_, i) => i), cutExit)
3053
+ Arr.forEach(Arr.fromIterable(holds.keys()), unhold)
3054
+ Iter.forEach(fibers, (fiber) => fiber.interruptUnsafe())
3055
+ fibers.clear()
3056
+ Arr.forEach(elementOf, (el, i) => {
3057
+ if (Predicate.isNotUndefined(el)) forget(el, i)
3058
+ })
3059
+ },
3060
+ }
3061
+ binding = bound
3062
+
3063
+ // Keyed: its first list taken in now, read as it was made (its binding calls this untracked); with `keys`
3064
+ // and no items yet, its core Batch made now too. By index: its keys are its members' first targets' and
3065
+ // starts', and its members fixed, each made now.
3066
+ if (keyed) {
3067
+ const first = keyedTargetsOf()
3068
+ if (Predicate.isNotUndefined(byKey.keys) && first.items.length === 0) {
3069
+ keysAre(byKey.keys)
3070
+ makeBatch(() => Number.NaN)
3071
+ }
3072
+ takeList(first)
3073
+ return bound
3074
+ }
3075
+ growMembersTo(Math.max(1, count))
3076
+ keysAre(withMoreKeys(keysOf(byIndex)))
3077
+ current = indexTargetsOf()
3078
+ makeBatch((k) => current[k])
3079
+ Arr.forEach(indices, (i) => {
3080
+ entries[i] = { binding: bound, member: i }
3081
+ indexOf[i] = i
3082
+ refs[i] = (el: Element) => arrive(i, el)
3083
+ })
3084
+ return bound
3085
+ }