@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,1037 @@
1
+ /**
2
+ * **Imperative animation** (#433, CONTEXT.md; Motion's `useAnimate`), for every DOM binding: an
3
+ * **Animation scope**'s `animate`, the elements it animates, and the **Playback controls** it returns.
4
+ * Each binding's `createAnimate()` builds on it.
5
+ *
6
+ * - **A Wardic element** animates through its own spine, registered here while it's mounted: the
7
+ * call takes the keys it animates, which stay where it leaves them until the element's own target
8
+ * for them changes (Motion's latest-wins).
9
+ * - **A plain element** animates through a spine of its own (#433's Q4), with no config, presence or
10
+ * layout node: it starts from the element's Own value (ADR-0022) and keeps its values for the next
11
+ * call, velocity included. It's in the gate only while it animates, so the gate keeps nothing of an
12
+ * element it isn't animating.
13
+ * - **The controls** are Motion's (`AnimationPlaybackControls`): awaitable, with `stop`, `cancel`,
14
+ * `complete`, `pause`, `play`, `speed`, `time` and `duration`, every element's legs run through
15
+ * one `Playback.Playhead`. Its `finished` resolves at a landing or `complete()`, never at a `stop()`
16
+ * or a `cancel()`, as Motion's.
17
+ * - **A sequence** (#433's PR 2, Motion's) is compiled by core's `Sequence` to each subject's
18
+ * Keyframes over the whole sequence, run on the same controls: each element animates as a call
19
+ * does, and a function Segment's value, from 0, is told to its callback each frame.
20
+ *
21
+ * Unstable, for Wardic's own packages: public, with no semver promise.
22
+ *
23
+ * @module
24
+ */
25
+ // Unstable: ADR-0071, decision 5. #672 (Q13): solid's `imperative.ts`, the DOM's `animate` (its Subjects
26
+ // elements, selectors and a Batch's handles), moved to dom for every DOM binding's `createAnimate`.
27
+ import type * as DefaultTransition from "@wardic/core/DefaultTransition"
28
+ import type * as Frame from "@wardic/core/Frame"
29
+ import * as InterpolatorRegistry from "@wardic/core/InterpolatorRegistry"
30
+ import * as Machine from "@wardic/core/Machine"
31
+ import * as Playback from "@wardic/core/Playback"
32
+ import * as ReducedMotion from "@wardic/core/ReducedMotion"
33
+ import type * as Values from "@wardic/core/Values"
34
+ import * as Sequence from "@wardic/core/Sequence"
35
+ import type * as FlushGate from "../FlushGate.ts"
36
+ import * as Report from "../Report.ts"
37
+ import * as BatchMembers from "./BatchMembers.ts"
38
+ import * as Arr from "effect/Array"
39
+ import * as Bool from "effect/Boolean"
40
+ import * as Cause from "effect/Cause"
41
+ import * as Effect from "effect/Effect"
42
+ import * as Exit from "effect/Exit"
43
+ import type * as Fiber from "effect/Fiber"
44
+ import { constVoid, identity } from "effect/Function"
45
+ import * as Iter from "effect/Iterable"
46
+ import * as Match from "effect/Match"
47
+ import * as Predicate from "effect/Predicate"
48
+ import * as Rec from "effect/Record"
49
+ import * as UndefinedOr from "effect/UndefinedOr"
50
+ import type * as WardConfig from "./WardConfig.ts"
51
+ import * as RetargetLegs from "@wardic/core/unstable/RetargetLegs"
52
+ import type * as MeasuredPairs from "@wardic/core/unstable/MeasuredPairs"
53
+ import type * as OwnValues from "@wardic/core/unstable/OwnValues"
54
+ import type * as VariableValues from "@wardic/core/unstable/VariableValues"
55
+ import type * as WardicServices from "@wardic/core/unstable/WardicServices"
56
+ import * as Spine from "@wardic/core/unstable/Spine"
57
+ import * as ElementSetup from "./ElementSetup.ts"
58
+ import * as VariantTarget from "@wardic/core/unstable/VariantTarget"
59
+ import * as VariantTree from "@wardic/core/unstable/VariantTree"
60
+
61
+ /** What an Imperative animation animates an element through: what its spine hands over (`host`). */
62
+ type Animatable = Pick<Spine.ElementSpine, "host">
63
+
64
+ /** Each mounted Wardic element's spine (Motion's `visualElementStore`). */
65
+ // Module state (#460, Q7): each Wardic element's animatable, held weakly by the element.
66
+ const wardicElements = new WeakMap<Element, Animatable>()
67
+
68
+ /**
69
+ * Register a mounted Wardic element's spine for the Imperative animations of it (#433): until the
70
+ * returned function, which its unmount calls.
71
+ */
72
+ export const registerAnimatable = (element: Element, spine: Animatable): (() => void) => {
73
+ wardicElements.set(element, spine)
74
+ return () => {
75
+ if (wardicElements.get(element) === spine) wardicElements.delete(element)
76
+ }
77
+ }
78
+
79
+ /** What a scope animates plain elements with: its provider's. */
80
+ export interface AnimateEnv {
81
+ readonly runtime: WardicServices.Runner<WardicServices.WardicServices>
82
+ readonly gate: FlushGate.Shape
83
+ readonly reducedMotion: () => boolean
84
+ /**
85
+ * Whether its animations are skipped (#468): its scope's nearest `WardicConfig`'s, read as each
86
+ * starts, and handed to each element's animation in its transition, as Motion's `useAnimate` does.
87
+ */
88
+ readonly skipAnimations: () => boolean
89
+ readonly positionalKeys: ReducedMotion.PositionalKeys["Service"]
90
+ readonly defaultTransition: DefaultTransition.DefaultTransition["Service"]
91
+ /** Its Environment's reads of its Subjects' own values (#672). */
92
+ readonly ownValues: OwnValues.Shape
93
+ /** Its Environment's Measured pairs (#430, #672). */
94
+ readonly measuredPairs: MeasuredPairs.Shape
95
+ /** Its Environment's Variable values (#55, #672). */
96
+ readonly variableValues: VariableValues.Shape
97
+ }
98
+
99
+ /** A plain element's spine (#433's Q4), its values, and how many of its animations run, which keep it in the gate. */
100
+ interface Plain {
101
+ readonly spine: Spine.ElementSpine
102
+ readonly snapshot: Spine.Snapshot
103
+ readonly id: string
104
+ running: number
105
+ unregister: () => void
106
+ }
107
+
108
+ /** Each gate's plain elements: a provider's own, kept while the element is. */
109
+ // Module state (#460, Q7): each gate's plain elements, held weakly by the gate.
110
+ const plainByGate = new WeakMap<FlushGate.Shape, WeakMap<Element, Plain>>()
111
+
112
+ /** The plain elements' gate ids, counted. */
113
+ // Module state (#460, Q7): an id counter, unique across every gate.
114
+ let plainIds = 0
115
+
116
+ /** No config: a plain element's. */
117
+ const NO_CONFIG = {}
118
+
119
+ /** `element`'s plain spine under `env`'s gate, made at its first animation. */
120
+ const plainOf = (env: AnimateEnv, element: Element): Plain => {
121
+ let byElement = plainByGate.get(env.gate)
122
+ if (Predicate.isUndefined(byElement)) {
123
+ byElement = new WeakMap()
124
+ plainByGate.set(env.gate, byElement)
125
+ }
126
+ const known = byElement.get(element)
127
+ if (Predicate.isNotUndefined(known)) return known
128
+ const el = element as HTMLElement
129
+ const id = `wardic-animate-${plainIds++}`
130
+ const snapshot: Spine.Snapshot = Spine.emptySnapshotOf({})
131
+ const spine = Spine.makeElementSpine({
132
+ runtime: env.runtime,
133
+ gate: env.gate,
134
+ id,
135
+ element: el,
136
+ tag: undefined,
137
+ config: () => NO_CONFIG,
138
+ parent: undefined,
139
+ canStart: undefined,
140
+ extraDelay: undefined,
141
+ onFrame: undefined,
142
+ reducedMotion: env.reducedMotion,
143
+ positionalKeys: env.positionalKeys,
144
+ defaultTransition: env.defaultTransition,
145
+ ownValues: env.ownValues,
146
+ measuredPairs: env.measuredPairs,
147
+ variableValues: env.variableValues,
148
+ start: { initialValues: {}, initialLink: {}, startedLink: {}, quiet: false },
149
+ snapshot,
150
+ reuse: Spine.makeReuse(),
151
+ links: ElementSetup.startLinksOf(el, undefined, undefined),
152
+ styleNow: undefined,
153
+ live: undefined,
154
+ presence: undefined,
155
+ projected: false,
156
+ dragAxis: undefined,
157
+ handoff: undefined,
158
+ })
159
+ const plain: Plain = { spine, snapshot, id, running: 0, unregister: constVoid }
160
+ byElement.set(element, plain)
161
+ return plain
162
+ }
163
+
164
+ /**
165
+ * `transition` with `skipAnimations` when its scope's animations are skipped (#468, Motion's
166
+ * `useAnimate`, which hands its config's to each animation): a Wardic element's own config can skip it
167
+ * too, and a plain element has none.
168
+ */
169
+ const skippedIn = (env: AnimateEnv, transition: WardConfig.WardicTransition | undefined): WardConfig.WardicTransition | undefined => {
170
+ if (Bool.not(env.skipAnimations())) return transition
171
+ return { ...transition, skipAnimations: true } as WardConfig.WardicTransition
172
+ }
173
+
174
+ /**
175
+ * The resolution an **Imperative animation**'s legs run under (#433): none of the Override stack's,
176
+ * so a Retarget that takes a key back never carries one as its own Keyframes or names.
177
+ */
178
+ const IMPERATIVE: Spine.Resolution = {
179
+ resolved: {},
180
+ base: {},
181
+ dragging: false,
182
+ variant: undefined,
183
+ active: { inView: false, focused: false, hovered: false, pressed: false, dragged: false, dragging: false },
184
+ transition: undefined,
185
+ layers: [],
186
+ names: VariantTree.NO_GESTURE_NAMES,
187
+ layersOn: VariantTree.NO_GESTURE_STATES,
188
+ ends: undefined,
189
+ keyframes: undefined,
190
+ change: undefined,
191
+ }
192
+
193
+ /**
194
+ * An **Imperative animation** of an element (#433), through its spine's `host`: it takes `target`'s
195
+ * keys from whatever runs them, each noted with the target the Override stack has for it now, so a
196
+ * Retarget leaves it where the animation leaves it until that target changes (Motion's latest-wins).
197
+ * Its legs start where the keys are drawn, with their velocity, on `given` (a key with none of its own
198
+ * on its Default transition), reduced motion as the provider says, and run through `head` once
199
+ * {@link Spine.ImperativeTrack.run} is called.
200
+ */
201
+ // #746 (ADR-0067, *Amendment (#746)*, decision 10): here, not in the spine, so an app that never animates
202
+ // imperatively ships none of it; the spine hands over what it takes (`SpineHost`).
203
+ const imperativeTrackOf = (host: Spine.SpineHost, target: VariantTarget.Target, given: WardConfig.WardicTransition | undefined, head: Playback.Playhead, hooks: Spine.ImperativeHooks): Spine.ImperativeTrack => {
204
+ const { snapshot, owners, giveUp, initialValues, ownValue, startKey, keepTheRest, element, positionalKeys, defaultTransition, readVelocity, gate, forget, endLeg, live, own, legProgram, legEnded, turnBack, id, recordFrame, runtime, elementRules, measuredPairs, variableValues } = host
205
+ /** A leg of an Imperative animation, forked as a Retarget's are; it lands on its track. */
206
+ // Data-first: a pipe's curried forms are two closures more for every leg (#618, H1).
207
+ const runImperative = (running: Spine.Running, program: Effect.Effect<unknown, never, WardicServices.WardicServices>): void => {
208
+ running.fiber = runtime.runFork(Effect.asVoid(Effect.onExit(program, legEnded(running))))
209
+ }
210
+ const to = target.values
211
+ const before = UndefinedOr.match(host.lastResolution(), { onUndefined: () => Spine.NO_VALUES, onDefined: (last) => last.resolved })
212
+ const started: Record<string, string> = {}
213
+ let measuring: Array<string> | undefined
214
+ // Each key taken from whatever runs it, noted with its target now, and started where it's drawn.
215
+ // Its velocity read now (#464), as its legs are built.
216
+ const takenNow = host.taking()
217
+ // Where a Path's axis this target leaves out rests (#574), before its keys are taken below.
218
+ const rests = Spine.restsOf(owners, to)
219
+ Arr.forEach(Rec.keys(to), (key) => {
220
+ takenNow.set(key, before[key])
221
+ host.returning().delete(key)
222
+ // Its Timeline value stops while the animation draws the key (#240).
223
+ const timelineKeys = host.timelineKeys()
224
+ if (Predicate.isNotUndefined(timelineKeys)) timelineKeys.taken(key)
225
+ const owner = owners.get(key)
226
+ if (Predicate.isNotUndefined(owner)) giveUp(key, owner)
227
+ if (!Object.hasOwn(initialValues, key)) ownValue(key)
228
+ const like = UndefinedOr.getOrThrow(to[key])
229
+ startKey(key, like, started)
230
+ if (measuredPairs.needs(key, UndefinedOr.getOrThrow(snapshot.values[key]), like)) {
231
+ if (Predicate.isUndefined(measuring)) measuring = []
232
+ measuring.push(key)
233
+ }
234
+ })
235
+ keepTheRest()
236
+ let from: Values.Values = Rec.map(to, (_, key) => UndefinedOr.getOrThrow(snapshot.values[key]))
237
+ let stops: RetargetLegs.StopsByKey | undefined
238
+ if (Predicate.isNotUndefined(target.keyframes)) {
239
+ const begun = RetargetLegs.keyframesFrom(from, to, target.keyframes)
240
+ from = begun.from
241
+ stops = begun.stops
242
+ }
243
+ const reduce = host.reducedMotion()
244
+ const skipped = host.skipAnimations()
245
+ let measured: RetargetLegs.MeasuredPairs | undefined
246
+ if (Bool.and(Bool.not(Bool.or(reduce, skipped)), Predicate.isNotUndefined(measuring))) measured = Spine.measuredOf(measuredPairs, element, UndefinedOr.getOrThrow(measuring), from, to, snapshot.values, stops)
247
+ // Built once: a seek or a replay runs the same legs, from the same start, with the same velocities.
248
+ const built = RetargetLegs.legsOf(from, to, given, reduce, skipped, positionalKeys, defaultTransition, readVelocity, undefined, stops, measured, snapshot.values, rests)
249
+ const variables = Spine.holdsVariable(variableValues, from, to, stops)
250
+ const legs = Arr.map(built, (leg) => RetargetLegs.mapMachine(leg, Playback.drive(head)))
251
+ let runnings: ReadonlyArray<Spine.Running> = Spine.NO_RUNNING
252
+ let left = 0
253
+ const landing: Spine.Landing = {
254
+ report: constVoid,
255
+ settled: () => {
256
+ left--
257
+ if (left === 0) gate.afterFlush(hooks.settled)
258
+ },
259
+ failed: hooks.failed,
260
+ }
261
+ // Its legs ended where they are: the keys they draw are drawn by none.
262
+ const end = (): void =>
263
+ Arr.forEach(runnings, (running) => {
264
+ forget(running)
265
+ if (Bool.not(running.done)) endLeg(running)
266
+ })
267
+ const run = (): void => {
268
+ end()
269
+ left = legs.length
270
+ Spine.tellStarted(live, legs)
271
+ runnings = Arr.map(legs, (leg) => {
272
+ const running = Spine.runningOf(leg.to, IMPERATIVE, landing, leg._tag)
273
+ own(running)
274
+ runImperative(running, legProgram(leg, running, variables))
275
+ return running
276
+ })
277
+ // A target with no key lands at once.
278
+ if (left === 0) gate.afterFlush(hooks.settled)
279
+ }
280
+ const cancel = (): void => {
281
+ end()
282
+ turnBack()
283
+ snapshot.values = { ...snapshot.values, ...from }
284
+ snapshot.velocities = { ...snapshot.velocities, ...Rec.map(from, () => 0) }
285
+ // Put back at once: at rest, newer than the legs that let them go (#464).
286
+ const now = snapshot.now()
287
+ Arr.forEach(Rec.keys(from), (key) => {
288
+ snapshot.drawnAt[key] = now
289
+ })
290
+ gate.write(id, from)
291
+ recordFrame(from)
292
+ }
293
+ // Each leg's machine, run from its start to rest, apart from the Playhead, which it would move: a
294
+ // blend's built with the element's Key rules.
295
+ const duration = (): number =>
296
+ Arr.reduce(built, 0, (longest, leg) => Math.max(longest, Machine.durationOf(machineOf(leg))))
297
+ const machineOf = (leg: RetargetLegs.Leg): Machine.Machine<Frame.Frame<unknown>> => {
298
+ if (leg._tag === "Blend") return runtime.runSync(Effect.suspend(leg.machine).pipe(InterpolatorRegistry.withKeyRules(elementRules)))
299
+ return leg.machine() as Machine.Machine<Frame.Frame<unknown>>
300
+ }
301
+ const stop = (): void => {
302
+ end()
303
+ turnBack()
304
+ }
305
+ return { run, stop, cancel, duration }
306
+ }
307
+
308
+ /**
309
+ * An element's animation of `target`: through its spine when it's a Wardic element's, else through its
310
+ * plain spine, in the gate while any of its animations runs.
311
+ */
312
+ const trackOf = (env: AnimateEnv, element: Element, target: WardConfig.WardicVariant, given: WardConfig.WardicTransition | undefined, head: Playback.Playhead, settled: () => void): Spine.ImperativeTrack => {
313
+ const resolved = VariantTarget.resolveTarget(target, undefined, undefined, VariantTarget.NO_VARIANT_STATE)
314
+ const own = wardicElements.get(element)
315
+ const hooks = { settled, failed: constVoid }
316
+ const transition = skippedIn(env, given)
317
+ if (Predicate.isNotUndefined(own)) return imperativeTrackOf(own.host(), resolved, transition, head, hooks)
318
+ const plain = plainOf(env, element)
319
+ // In the gate while it runs; out once its last animation is done, after the flush of its last frame.
320
+ let live = false
321
+ const enter = (): void => {
322
+ if (live) return
323
+ live = true
324
+ // Back in the gate with every value it holds, so a transform it draws keeps the keys it isn't animating.
325
+ if (plain.running === 0) {
326
+ plain.unregister = env.gate.register(plain.id, { target: element })
327
+ if (Bool.not(Rec.isEmptyRecord(plain.snapshot.values))) env.gate.write(plain.id, plain.snapshot.values)
328
+ }
329
+ plain.running++
330
+ }
331
+ const leave = (): void => {
332
+ if (Bool.not(live)) return
333
+ live = false
334
+ plain.running--
335
+ if (plain.running === 0) env.gate.afterFlush(() => {
336
+ if (plain.running === 0) plain.unregister()
337
+ })
338
+ }
339
+ const track = imperativeTrackOf(plain.spine.host(), resolved, transition, head, {
340
+ settled: () => {
341
+ leave()
342
+ settled()
343
+ },
344
+ failed: () => leave(),
345
+ })
346
+ return {
347
+ run: () => {
348
+ enter()
349
+ track.run()
350
+ },
351
+ stop: () => {
352
+ track.stop()
353
+ leave()
354
+ },
355
+ cancel: () => {
356
+ enter()
357
+ track.cancel()
358
+ leave()
359
+ },
360
+ duration: track.duration,
361
+ }
362
+ }
363
+
364
+ /** What `animate` animates: an element, a selector looked up inside the scope, or a list of elements. Motion's `ElementOrSelector`. */
365
+ export type WardicAnimationSubject = Element | string | ArrayLike<Element> | Iterable<Element> | null | undefined
366
+
367
+ /** A transition without its `delay`, each arm: `animate`'s and a Segment's take their own. */
368
+ type WithoutDelay = WardConfig.WardicTransition extends infer T ? (T extends unknown ? { readonly [K in keyof T as Exclude<K, "delay">]: T[K] } : never) : never
369
+
370
+ /** A `delay` that may be each element's (Motion's `delay(i, n)`; `stagger()` is #436). */
371
+ interface EachDelay {
372
+ readonly delay?: number | ((index: number, count: number) => number) | undefined
373
+ }
374
+
375
+ /**
376
+ * `animate`'s options: a transition, its `delay` a number, or a function of each element's index and
377
+ * their count, such as `stagger(0.05)`; and `onComplete`, called as it lands. Motion's.
378
+ */
379
+ export type WardicAnimateOptions = WithoutDelay & EachDelay & {
380
+ readonly onComplete?: (() => void) | undefined
381
+ }
382
+
383
+ /** The elements of `subject`: a selector's inside `scope`, else the page's. */
384
+ const subjectsOf = (subject: WardicAnimationSubject, scope: Element | undefined): ReadonlyArray<Element> => {
385
+ if (Predicate.isNullish(subject)) return []
386
+ if (Predicate.isString(subject)) return Arr.fromIterable(UndefinedOr.match(scope, { onUndefined: () => document, onDefined: (el): ParentNode => el }).querySelectorAll(subject))
387
+ if (Predicate.hasProperty(subject, "nodeType")) return [subject as Element]
388
+ // A list's missing members left out, as Motion's.
389
+ if (Predicate.isIterable(subject)) return Arr.filter(Arr.fromIterable(subject), Predicate.isNotNullish)
390
+ const list = subject as ArrayLike<Element>
391
+ return Arr.filter(Arr.makeBy(list.length, (i) => list[i] as Element), Predicate.isNotNullish)
392
+ }
393
+
394
+ /** A call's options without its `onComplete`: its transition. */
395
+ const withoutComplete = (given: WardicAnimateOptions): Readonly<Record<string, unknown>> => {
396
+ const { onComplete: _onComplete, ...rest } = given as Readonly<Record<string, unknown>>
397
+ return rest
398
+ }
399
+
400
+ /** Each element's transition: its `delay` worked out for it (Motion's `delay(i, n)`). */
401
+ const transitionFor = (options: WardicAnimateOptions | undefined, index: number, count: number): WardConfig.WardicTransition | undefined =>
402
+ UndefinedOr.map(options, (given) => {
403
+ const { delay, ...rest } = withoutComplete(given)
404
+ if (Predicate.isFunction(delay)) return { ...rest, delay: (delay as (index: number, count: number) => number)(index, count) } as WardConfig.WardicTransition
405
+ if (Predicate.isUndefined(delay)) return rest as WardConfig.WardicTransition
406
+ return { ...rest, delay } as WardConfig.WardicTransition
407
+ })
408
+
409
+ /** A Batch call's transition (#665): the options without `onComplete`, a `stagger()` delay kept for the Batch to count its movers. */
410
+ const batchTransitionOf = (options: WardicAnimateOptions | undefined): WardConfig.WardicTransition | undefined =>
411
+ UndefinedOr.map(options, (given) => withoutComplete(given) as WardConfig.WardicTransition)
412
+
413
+ /** A Batch call's track over `members` (every member when left out), driven by `head`: the call's options its transition. */
414
+ const batchTrackOf = (env: AnimateEnv, binding: BatchMembers.BatchBinding, target: BatchMembers.WardicBatchTarget, members: ReadonlyArray<number> | undefined, options: WardicAnimateOptions | undefined, head: Playback.Playhead, settled: () => void): Spine.ImperativeTrack =>
415
+ binding.track({
416
+ target,
417
+ transition: batchTransitionOf(options),
418
+ reducedMotion: env.reducedMotion(),
419
+ skipAnimations: skipsBatchCall(env, options),
420
+ head,
421
+ settled,
422
+ members,
423
+ })
424
+
425
+ /** Whether a Batch call lands at once: its scope's animations are skipped, or its own `skipAnimations` (#468). */
426
+ const skipsBatchCall = (env: AnimateEnv, options: WardicAnimateOptions | undefined): boolean => {
427
+ if (env.skipAnimations()) return true
428
+ return UndefinedOr.match(options, { onUndefined: () => false, onDefined: (given) => given.skipAnimations === true })
429
+ }
430
+
431
+ /** Where an animation is: `"idle"`, `"running"`, `"paused"` or `"finished"`. Motion's `AnimationPlayState`. */
432
+ export type WardicPlayState = "idle" | "running" | "paused" | "finished"
433
+
434
+ /**
435
+ * What `animate` returns: an animation's controls, and a promise of its landing, so it can be awaited.
436
+ * Motion's `AnimationPlaybackControls`.
437
+ */
438
+ // #433: every element's legs run through one Playhead.
439
+ export interface WardicPlaybackControls extends PromiseLike<void> {
440
+ /** Seconds played, a delay included. Set, it seeks: each key starts again there, holding while paused. */
441
+ time: number
442
+ /** How fast it plays: 1 as given, 2 twice as fast, 0 held, below 0 backwards. */
443
+ speed: number
444
+ /** How long it runs, in seconds: its longest element's longest key, a spring's to rest. */
445
+ readonly duration: number
446
+ readonly state: WardicPlayState
447
+ /** Resolves when it lands, or at `complete()`; never at `stop()` or `cancel()`, as Motion's. */
448
+ readonly finished: Promise<void>
449
+ /** Play it on: from where it's paused, or again from its start once it's finished or cancelled. Not after `stop()`. */
450
+ readonly play: () => void
451
+ /** Hold it where it is. */
452
+ readonly pause: () => void
453
+ /** End it where it is, for good: its keys stay there. */
454
+ readonly stop: () => void
455
+ /** End it, and put its keys back where it started them. */
456
+ readonly cancel: () => void
457
+ /** Go to its end at once, and finish. */
458
+ readonly complete: () => void
459
+ }
460
+
461
+ /** What a scope hears of its animations: each one's start and its end, however it ended. */
462
+ export interface AnimationWatch {
463
+ readonly started: (controls: WardicPlaybackControls) => void
464
+ /** It's no longer in flight: `landed` when it finished. */
465
+ readonly ended: (controls: WardicPlaybackControls, landed: boolean) => void
466
+ }
467
+
468
+ /** Playback controls over `tracks`, all run through `head`, started now. */
469
+ const controlsOf = (tracks: ReadonlyArray<Spine.ImperativeTrack>, head: Playback.Playhead, watch: AnimationWatch, onComplete: (() => void) | undefined): {
470
+ readonly controls: WardicPlaybackControls
471
+ readonly settledOne: () => void
472
+ } => {
473
+ let state: WardicPlayState = "running"
474
+ let stopped = false
475
+ let landed = 0
476
+ let resolve: (() => void) | undefined
477
+ let finished: Promise<void> | undefined
478
+ let isResolved = false
479
+ let duration: number | undefined
480
+ const durationNow = (): number => {
481
+ if (Predicate.isUndefined(duration)) duration = Arr.reduce(tracks, 0, (longest, track) => Math.max(longest, track.duration()))
482
+ return duration
483
+ }
484
+ const runAll = (): void => {
485
+ landed = 0
486
+ Arr.forEach(tracks, (track) => track.run())
487
+ }
488
+ const fresh = (): void => {
489
+ finished = undefined
490
+ resolve = undefined
491
+ isResolved = false
492
+ }
493
+ const end = (how: WardicPlayState, landedNow: boolean): void => {
494
+ const was = state
495
+ state = how
496
+ if (Bool.or(was === "running", was === "paused")) watch.ended(controls, landedNow)
497
+ }
498
+ const restart = (): void => {
499
+ const was = state
500
+ state = "running"
501
+ if (Bool.or(was === "finished", was === "idle")) watch.started(controls)
502
+ }
503
+ const controls: WardicPlaybackControls = {
504
+ get time() {
505
+ return head.time
506
+ },
507
+ set time(at: number) {
508
+ Playback.seek(head, at)
509
+ // A seek of one that isn't running holds where it goes, as Motion's.
510
+ if (state !== "running") {
511
+ Playback.pause(head)
512
+ if (Bool.or(state === "finished", state === "idle")) {
513
+ fresh()
514
+ watch.started(controls)
515
+ }
516
+ state = "paused"
517
+ }
518
+ runAll()
519
+ },
520
+ get speed() {
521
+ return head.speed
522
+ },
523
+ set speed(speed: number) {
524
+ Playback.setSpeed(head, speed)
525
+ },
526
+ get duration() {
527
+ return durationNow()
528
+ },
529
+ get state() {
530
+ return state
531
+ },
532
+ get finished() {
533
+ if (Predicate.isUndefined(finished)) {
534
+ finished = Bool.match(isResolved, {
535
+ onTrue: () => Promise.resolve(),
536
+ onFalse: () =>
537
+ new Promise<void>((done) => {
538
+ resolve = done
539
+ }),
540
+ })
541
+ }
542
+ return finished
543
+ },
544
+ then: (onResolve, onReject) => controls.finished.then(onResolve, onReject),
545
+ play: () => {
546
+ if (stopped) return
547
+ if (state === "paused") {
548
+ Playback.play(head)
549
+ state = "running"
550
+ return
551
+ }
552
+ if (state === "running") return
553
+ // Again from its start: its end when it plays backwards.
554
+ fresh()
555
+ Playback.play(head)
556
+ Playback.seek(head, Bool.match(head.speed < 0, { onTrue: durationNow, onFalse: () => 0 }))
557
+ restart()
558
+ runAll()
559
+ },
560
+ pause: () => {
561
+ if (stopped) return
562
+ Playback.pause(head)
563
+ if (state === "running") state = "paused"
564
+ },
565
+ stop: () => {
566
+ stopped = true
567
+ Arr.forEach(tracks, (track) => track.stop())
568
+ end("idle", false)
569
+ },
570
+ cancel: () => {
571
+ Arr.forEach(tracks, (track) => track.cancel())
572
+ Playback.seek(head, 0)
573
+ end("idle", false)
574
+ },
575
+ complete: () => {
576
+ if (stopped) return
577
+ if (state !== "running") restart()
578
+ Playback.play(head)
579
+ Playback.seek(head, durationNow())
580
+ runAll()
581
+ },
582
+ }
583
+ // Each element's legs landed: the last lands the animation.
584
+ const settledOne = (): void => {
585
+ landed++
586
+ if (landed < tracks.length) return
587
+ isResolved = true
588
+ UndefinedOr.map(resolve, (done) => done())
589
+ UndefinedOr.map(onComplete, (complete) => complete())
590
+ end("finished", true)
591
+ }
592
+ return { controls, settledOne }
593
+ }
594
+
595
+ /** An animation of no element: finished at once (a server's, or a subject that matched none). */
596
+ const finishedControls = (): WardicPlaybackControls => {
597
+ const done = Promise.resolve()
598
+ return {
599
+ time: 0,
600
+ speed: 1,
601
+ duration: 0,
602
+ state: "finished",
603
+ finished: done,
604
+ then: (onResolve, onReject) => done.then(onResolve, onReject),
605
+ play: constVoid,
606
+ pause: constVoid,
607
+ stop: constVoid,
608
+ cancel: constVoid,
609
+ complete: constVoid,
610
+ }
611
+ }
612
+
613
+ /**
614
+ * Where a Segment starts in a sequence: seconds in, `1.5`; after or before the end of the Segment
615
+ * before, `"+0.5"` or `"-0.5"`; at its start, `"<"`, or around it, `"<+0.5"` or `"<-0.5"`; or a label's
616
+ * name. Motion's `SequenceTime`.
617
+ */
618
+ export type WardicSequenceTime = number | "<" | `+${number}` | `-${number}` | `<+${number}` | `<-${number}` | (string & {})
619
+
620
+ /** A label in a sequence: a name for where the Segment before ends, or `{ name, at }` for a time of its own. Motion's. */
621
+ export type WardicSequenceLabel = string | { readonly name: string; readonly at: WardicSequenceTime }
622
+
623
+ /**
624
+ * A Segment's options: a transition, with a value's own entries laid over it; its `delay`, a number or
625
+ * a function of each element's index and count, such as `stagger(0.05)`; and `at`, where it starts. A
626
+ * spring through two stops or fewer plays as an easing over its time to rest. Motion's.
627
+ */
628
+ export type WardicSegmentOptions = WithoutDelay & EachDelay & {
629
+ readonly at?: WardicSequenceTime | undefined
630
+ }
631
+
632
+ /** A Segment's values: each a value or a list of keyframes, as a target's. */
633
+ export type WardicSegmentTarget = Omit<WardConfig.WardicTargetValues, "transition">
634
+
635
+ /** A Segment of elements, `[subject, target, options?]`: an element, a selector inside the scope, or a list. Motion's. */
636
+ export type WardicElementSegment =
637
+ | readonly [subject: WardicAnimationSubject, target: WardicSegmentTarget]
638
+ | readonly [subject: WardicAnimationSubject, target: WardicSegmentTarget, options: WardicSegmentOptions]
639
+
640
+ /**
641
+ * A function Segment, `[callback, value?, options?]`: its callback is given a value each frame, from 0
642
+ * to 1 unless it gives its own stops, for what isn't an element's style. Motion's, in place of its
643
+ * motion value Segments.
644
+ */
645
+ export type WardicFunctionSegment =
646
+ | readonly [callback: (value: number) => void]
647
+ | readonly [callback: (value: number) => void, options: WardicSegmentOptions]
648
+ | readonly [callback: (value: number) => void, value: number | WardConfig.WardicKeyframes<number>, options: WardicSegmentOptions]
649
+ | readonly [callback: (value: string) => void, value: string | WardConfig.WardicKeyframes<string>, options: WardicSegmentOptions]
650
+
651
+ /**
652
+ * A Segment of a Batch, `[batch, target, options?]`: a Batch, every member whose element has arrived, in
653
+ * member order, or a member's handle, `grid.at(i)`. Each of its keys a number, `null`, stops, or a
654
+ * function of a member's index and the Batch's count; a `stagger()` counts the Segment's members.
655
+ */
656
+ // #665, Q36–Q39: each member through its own stops, in the Batch.
657
+ export type WardicBatchSegment =
658
+ | readonly [batch: BatchMembers.WardicBatchSubject, target: BatchMembers.WardicBatchSegmentTarget]
659
+ | readonly [batch: BatchMembers.WardicBatchSubject, target: BatchMembers.WardicBatchSegmentTarget, options: WardicSegmentOptions]
660
+
661
+ /** One step of a sequence: a label, a Segment of elements, a function Segment, or a Segment of a Batch. */
662
+ export type WardicSegment = WardicSequenceLabel | WardicElementSegment | WardicFunctionSegment | WardicBatchSegment
663
+
664
+ /**
665
+ * A sequence: Segments played one after another, unless an `at` says where one starts, and labels to
666
+ * start them at. `animate(sequence, options)` plays it. Motion's `AnimationSequence`.
667
+ *
668
+ * @example
669
+ * animate([
670
+ * ["ul", { opacity: 1 }],
671
+ * ["li", { x: [-20, 0] }, { delay: stagger(0.05), at: "-0.1" }],
672
+ * ])
673
+ * @see https://wardic.dev/reference/solid/animation/sequences
674
+ */
675
+ // #433's PR 2.
676
+ export type WardicAnimationSequence = ReadonlyArray<WardicSegment>
677
+
678
+ /**
679
+ * A sequence's options: `duration`, the whole sequence scaled to it; `delay`; `repeat`, `repeatType`
680
+ * and `repeatDelay`; `defaultTransition`, each Segment's when it gives none (a 0.3 s `easeOut` tween
681
+ * otherwise); and `onComplete`, called as it lands. Motion's `SequenceOptions`.
682
+ */
683
+ export interface WardicSequenceOptions {
684
+ readonly duration?: number | undefined
685
+ readonly delay?: number | undefined
686
+ readonly repeat?: number | undefined
687
+ readonly repeatType?: "loop" | "reverse" | "mirror" | undefined
688
+ readonly repeatDelay?: number | undefined
689
+ readonly defaultTransition?: WardConfig.WardicTransition | undefined
690
+ readonly onComplete?: (() => void) | undefined
691
+ }
692
+
693
+ /**
694
+ * A scope's `animate`: `animate(subject, target, options?)` animates the subject's elements to
695
+ * `target`, and `animate(sequence, options?)` plays a sequence. Either returns its playback controls.
696
+ * Motion's `animate`, as `useAnimate` gives it.
697
+ */
698
+ // #433: through one Playhead.
699
+ export interface WardicAnimate {
700
+ (subject: WardicAnimationSubject, target: WardConfig.WardicVariant, options?: WardicAnimateOptions): WardicPlaybackControls
701
+ (batch: BatchMembers.WardicBatchSubject, target: BatchMembers.WardicBatchTarget, options?: WardicAnimateOptions): WardicPlaybackControls
702
+ (sequence: WardicAnimationSequence, options?: WardicSequenceOptions): WardicPlaybackControls
703
+ }
704
+
705
+ /**
706
+ * An **Animation scope**'s `animate` (#433): selectors looked up inside `scope()`, each animation
707
+ * told to `watch` as it starts and ends. Every element's legs start in the call, on the loop by
708
+ * the end of its task.
709
+ */
710
+ export const scopedAnimate = (env: AnimateEnv, scope: () => Element | undefined, watch: AnimationWatch): WardicAnimate =>
711
+ ((first: WardicAnimationSubject | WardicAnimationSequence, second?: WardConfig.WardicVariant | WardicSequenceOptions, third?: WardicAnimateOptions): WardicPlaybackControls => {
712
+ if (isSequence(first)) return sequenceOf(env, scope(), watch, first, second as WardicSequenceOptions | undefined)
713
+ // A Batch, or a member's handle (#665): one track over its members, on the Batch's own run.
714
+ const batch = BatchMembers.batchSubjectOf(first)
715
+ if (Predicate.isNotUndefined(batch)) {
716
+ const members = batch.binding.namedOf(batch)
717
+ return started(watch, 1, UndefinedOr.map(third, (given) => given.onComplete), (head, settled) => [
718
+ batchTrackOf(env, batch.binding, second as BatchMembers.WardicBatchTarget, members, third, head, settled),
719
+ ])
720
+ }
721
+ const elements = subjectsOf(first as WardicAnimationSubject, scope())
722
+ const target = second as WardConfig.WardicVariant
723
+ const onComplete = UndefinedOr.map(third, (given) => given.onComplete)
724
+ // No member's element among them: each element's track, building no parts (bench:solid --batch's
725
+ // per-element page, a call per element: 8.2 -> 8.5 ms at 1,000 with the parts built for every call; #665).
726
+ if (!Arr.some(elements, BatchMembers.isMemberElement)) {
727
+ return started(watch, elements.length, onComplete, (head, settled) =>
728
+ Arr.map(elements, (element, index) => trackOf(env, element, target, transitionFor(third, index, elements.length), head, settled)))
729
+ }
730
+ // A Batch's members' elements as one call over them, with its keys; the rest of each element's on its own (#665, Q14, Q35).
731
+ const parts = BatchMembers.callPartsOf(elements, target)
732
+ return started(watch, parts.members.length + parts.elements.length, onComplete, (head, settled) => [
733
+ ...Arr.map(parts.members, (part) => batchTrackOf(env, part.binding, part.target, part.members, third, head, settled)),
734
+ ...Arr.map(parts.elements, (part) => trackOf(env, part.element, part.target, transitionFor(third, part.index, elements.length), head, settled)),
735
+ ])
736
+ }) as WardicAnimate
737
+
738
+ /**
739
+ * An animation of `count` tracks started (#433): its controls over them, through one Playhead, told
740
+ * to `watch`, each track run. Finished at once with none.
741
+ */
742
+ const started = (
743
+ watch: AnimationWatch,
744
+ count: number,
745
+ onComplete: (() => void) | undefined,
746
+ tracksOf: (head: Playback.Playhead, settled: () => void) => ReadonlyArray<Spine.ImperativeTrack>,
747
+ ): WardicPlaybackControls => {
748
+ if (count === 0) return finishedControls()
749
+ const head = Playback.make()
750
+ let settledOne = constVoid
751
+ const tracks = tracksOf(head, () => settledOne())
752
+ const made = controlsOf(tracks, head, watch, onComplete)
753
+ settledOne = made.settledOne
754
+ watch.started(made.controls)
755
+ Arr.forEach(tracks, (track) => track.run())
756
+ return made.controls
757
+ }
758
+
759
+ /** A server's `animate`: nothing to animate. */
760
+ export const serverAnimate: WardicAnimate = () => finishedControls()
761
+
762
+ // --- Sequences (#433's PR 2) ------------------------------------------------------------------
763
+
764
+ /** Whether `animate` was given a sequence (Motion's `isSequence`): a list with a Segment in it. */
765
+ const isSequence = (given: unknown): given is WardicAnimationSequence =>
766
+ Bool.match(Arr.isArray(given), { onTrue: () => Arr.some(given as ReadonlyArray<unknown>, Arr.isArray), onFalse: () => false })
767
+
768
+ /** A function Segment's value (Motion's motion value): its own subject, its callback told each frame. */
769
+ interface Callback {
770
+ readonly call: (value: number | string) => void
771
+ }
772
+
773
+ /** What a sequence animates: elements, function Segments' values, and Batches' members (#665). */
774
+ type Subject = Element | Callback | BatchMembers.BatchMemberEntry
775
+
776
+ /** Whether a subject is a function Segment's value. */
777
+ const isCallback = (subject: Subject): subject is Callback => Predicate.hasProperty(subject, "call")
778
+
779
+ /** The key a function Segment's value animates under. */
780
+ const VALUE = "value"
781
+
782
+ /** A function Segment's stops with none given (Motion's). */
783
+ const ZERO_TO_ONE: ReadonlyArray<number> = [0, 1]
784
+
785
+ /** No fields. */
786
+ const NO_FIELDS: Readonly<Record<string, unknown>> = {}
787
+
788
+ /**
789
+ * What a Segment's transition doesn't take from the sequence's `defaultTransition` (Motion's): its
790
+ * delay, times and repeat, which are each Segment's own, and a value's own transitions.
791
+ */
792
+ const PLACING: ReadonlySet<string> = new Set(["delay", "times", "repeat", "repeatType", "repeatDelay", "reverse", "at"])
793
+
794
+ /** A Segment's default transition (Motion's): a 0.3 s `easeOut` tween. */
795
+ const SEGMENT_TWEEN: Sequence.Transition = { type: "tween" }
796
+
797
+ /** The fields of a sequence's options laid over each key's animation: `duration`, `delay` and the repeat. */
798
+ const WHOLE = ["duration", "delay", "repeat", "repeatType", "repeatDelay"] as const
799
+
800
+ /**
801
+ * The fields of a sequence's `defaultTransition` laid over each key's animation, under its own
802
+ * options' (Motion's): its delay and repeat. Its `duration` is a Segment's, never the sequence's.
803
+ */
804
+ const WHOLE_DEFAULTS = ["delay", "repeat", "repeatType", "repeatDelay"] as const
805
+
806
+ /** `fields`' `keys`, those it has. */
807
+ const picked = (fields: Readonly<Record<string, unknown>>, keys: ReadonlyArray<string>): Readonly<Record<string, unknown>> =>
808
+ Rec.filter(fields, (value, key) => Bool.and(Arr.contains(keys, key), Predicate.isNotUndefined(value)))
809
+
810
+ /**
811
+ * `key`'s transition in a Segment (Motion's `getValueTransition` for sequences): the Segment's,
812
+ * the value's own laid over it, over the sequence's `defaultTransition` less its placing; a spring
813
+ * or a tween as Wardic's transitions are (ADR-0051), Motion's 0.3 s `easeOut` tween when it defines
814
+ * neither; its `delay` kept as given, each element's when it's a function.
815
+ */
816
+ const segmentTransitionOf = (options: WardicSegmentOptions | undefined, key: string, defaults: WardConfig.WardicTransition | undefined): Sequence.Transition => {
817
+ const own = UndefinedOr.match(options as Readonly<Record<string, unknown>> | undefined, {
818
+ onUndefined: () => NO_FIELDS,
819
+ onDefined: (given) => ({ ...given, ...UndefinedOr.match(given[key], { onUndefined: () => NO_FIELDS, onDefined: (entry) => Bool.match(Predicate.isObject(entry), { onTrue: () => entry as Readonly<Record<string, unknown>>, onFalse: () => NO_FIELDS }) }) }),
820
+ })
821
+ const base = UndefinedOr.match(defaults as Readonly<Record<string, unknown>> | undefined, {
822
+ onUndefined: () => NO_FIELDS,
823
+ onDefined: (given) => Rec.filter(given, (_, field) => Bool.not(PLACING.has(field))),
824
+ })
825
+ const { delay, at: _at, ...fields } = own
826
+ // An inertia (#435) isn't a sequence's: a Segment's time is placed on its timeline, and a glide has none to place.
827
+ const run = UndefinedOr.match(RetargetLegs.runOf({ ...base, ...fields } as WardConfig.WardicTransition), {
828
+ onUndefined: () => SEGMENT_TWEEN,
829
+ onDefined: (made) => Bool.match(made.type === "inertia", { onTrue: () => SEGMENT_TWEEN, onFalse: () => made as Sequence.Transition }),
830
+ })
831
+ return Bool.match(Predicate.isUndefined(delay), { onTrue: () => run, onFalse: () => ({ ...run, delay }) as Sequence.Transition })
832
+ }
833
+
834
+ /** Whether a Segment's value is one: a number, a string, `null` or Keyframes. */
835
+ const isSegmentValue: Predicate.Predicate<unknown> = Predicate.or(Predicate.or(Predicate.isNumber, Predicate.isString), Predicate.or(Predicate.isNull, Arr.isArray))
836
+
837
+ /** A Segment's values: those that are a value, `null` or Keyframes. */
838
+ const segmentValuesOf = (target: WardicSegmentTarget): Readonly<Record<string, Sequence.Stop | ReadonlyArray<Sequence.Stop>>> =>
839
+ Rec.filter(target as Readonly<Record<string, unknown>>, isSegmentValue) as Readonly<Record<string, Sequence.Stop | ReadonlyArray<Sequence.Stop>>>
840
+
841
+ /** Each of `values`' keys' transition in a Segment. */
842
+ const segmentTransitionsOf = (values: Readonly<Record<string, unknown>>, options: WardicSegmentOptions | undefined, defaults: WardConfig.WardicTransition | undefined): Readonly<Record<string, Sequence.Transition>> =>
843
+ Rec.map(values, (_, key) => segmentTransitionOf(options, key, defaults))
844
+
845
+ /** A Segment's `at`, when it gives one. */
846
+ const atOf = (options: WardicSegmentOptions | undefined): Sequence.Time | undefined => UndefinedOr.map(options, (given) => given.at)
847
+
848
+ /**
849
+ * An element Segment's subjects (#665, Q40): each element, a member's as its member's entry, so its Batch
850
+ * keys run in its Batch, as one subject with the member a Segment of the Batch names. Each Batch checks
851
+ * the Segment's values once.
852
+ */
853
+ const subjectsIn = (elements: ReadonlyArray<Element>, target: Readonly<Record<string, unknown>>): ReadonlyArray<Subject> => {
854
+ if (!Arr.some(elements, BatchMembers.isMemberElement)) return elements
855
+ const checked = new Set<BatchMembers.BatchBinding>()
856
+ return Arr.map(elements, (element): Subject => {
857
+ const entry = BatchMembers.memberEntryOf(element)
858
+ if (Predicate.isUndefined(entry)) return element
859
+ if (Bool.not(checked.has(entry.binding))) {
860
+ checked.add(entry.binding)
861
+ entry.binding.checkElementSegment(target)
862
+ }
863
+ return entry
864
+ })
865
+ }
866
+
867
+ /**
868
+ * A sequence's steps for core (#433): labels as they are; an element Segment's elements (a selector
869
+ * looked up once a sequence, inside `scope`), values and each value's transition; a function
870
+ * Segment's own value, from 0 to 1 unless it gives its stops.
871
+ */
872
+ const stepsOf = (sequence: WardicAnimationSequence, scope: Element | undefined, defaults: WardConfig.WardicTransition | undefined): ReadonlyArray<Sequence.Step<Subject>> => {
873
+ const selected = new Map<string, ReadonlyArray<Element>>()
874
+ const elementsOf = (subject: WardicAnimationSubject): ReadonlyArray<Element> => {
875
+ if (Bool.not(Predicate.isString(subject))) return subjectsOf(subject, scope)
876
+ const selector = subject as string
877
+ const known = selected.get(selector)
878
+ if (Predicate.isNotUndefined(known)) return known
879
+ const found = subjectsOf(selector, scope)
880
+ selected.set(selector, found)
881
+ return found
882
+ }
883
+ return Arr.map(sequence, (segment): Sequence.Step<Subject> => {
884
+ if (Predicate.isString(segment)) return segment
885
+ if (Bool.not(Arr.isArray(segment))) return segment as { readonly name: string; readonly at: Sequence.Time }
886
+ const parts = segment as ReadonlyArray<unknown>
887
+ // A Batch, or a member's handle (#665, Q38, Q39): its members, each through its own stops in the Batch.
888
+ const batch = BatchMembers.batchSubjectOf(parts[0])
889
+ if (Predicate.isNotUndefined(batch)) {
890
+ const options = parts[2] as WardicSegmentOptions | undefined
891
+ const { subjects, values } = batch.binding.segmentOf(batch.binding.namedOf(batch), parts[1] as Readonly<Record<string, unknown>>)
892
+ return { subjects, target: values, transitions: segmentTransitionsOf(values, options, defaults), at: atOf(options) }
893
+ }
894
+ if (Predicate.isFunction(parts[0])) {
895
+ const call = parts[0] as (value: number | string) => void
896
+ const three = parts.length === 3
897
+ const given = Bool.match(three, { onTrue: () => parts[1] as Sequence.Stop | ReadonlyArray<Sequence.Stop>, onFalse: () => ZERO_TO_ONE })
898
+ const options = Bool.match(three, { onTrue: () => parts[2], onFalse: () => parts[1] }) as WardicSegmentOptions | undefined
899
+ const target = { [VALUE]: given }
900
+ return { subjects: [{ call }], target, transitions: segmentTransitionsOf(target, options, defaults), at: atOf(options) }
901
+ }
902
+ const [subject, values, options] = segment as WardicElementSegment
903
+ const target = segmentValuesOf(values)
904
+ return { subjects: subjectsIn(elementsOf(subject), target), target, transitions: segmentTransitionsOf(target, options, defaults), at: atOf(options) }
905
+ })
906
+ }
907
+
908
+ /**
909
+ * A function Segment's value animated (#433): its stops, a first `null` 0, through the
910
+ * Interpolators on its tween over the sequence, each frame told to its callback. Cancelled, the
911
+ * callback hears its first stop again, as Motion's motion value is set back.
912
+ */
913
+ const callbackTrackOf = (env: AnimateEnv, callback: Callback, animation: Sequence.Animation, head: Playback.Playhead, settled: () => void): Spine.ImperativeTrack => {
914
+ const stops = RetargetLegs.filledStops(UndefinedOr.getOrThrow(animation.keyframes[VALUE]), 0)
915
+ const options = UndefinedOr.getOrThrow(animation.transition[VALUE])
916
+ // Skipped (#468): its callback told the value it would end on, on the first tick.
917
+ const machine = Bool.match(env.skipAnimations(), {
918
+ onTrue: () => Effect.succeed(ReducedMotion.snap<Values.Values>({ [VALUE]: UndefinedOr.getOrThrow(stops[0]) }, { [VALUE]: ReducedMotion.endOf(UndefinedOr.getOrThrow(stops[0]), UndefinedOr.getOrThrow(stops[stops.length - 1]), options) })),
919
+ onFalse: () => Machine.keyframesValues({ [VALUE]: stops }, options),
920
+ })
921
+ let fiber: Fiber.Fiber<unknown> | undefined
922
+ const end = (): void => {
923
+ if (Predicate.isUndefined(fiber)) return
924
+ const running = fiber
925
+ fiber = undefined
926
+ // Nothing waits on its end: interrupted here, not by a fiber forked for it (#618, L2).
927
+ if (Predicate.isUndefined(running.pollUnsafe())) running.interruptUnsafe()
928
+ }
929
+ const landed = (exit: Exit.Exit<unknown>): Effect.Effect<void> =>
930
+ Exit.match(exit, {
931
+ onSuccess: () => Effect.sync(settled),
932
+ onFailure: (cause) => Bool.match(Cause.hasInterruptsOnly(cause), { onTrue: () => Effect.void, onFalse: () => Report.failure("wardic.animate: a function Segment failed", cause) }),
933
+ })
934
+ const run = (): void => {
935
+ end()
936
+ fiber = env.runtime.runFork(
937
+ machine.pipe(
938
+ Effect.map(Playback.drive(head)),
939
+ Effect.flatMap(Machine.run((frame) => {
940
+ callback.call(UndefinedOr.getOrThrow(frame.value[VALUE]))
941
+ return undefined
942
+ })),
943
+ Effect.onExit(landed),
944
+ ),
945
+ )
946
+ }
947
+ return {
948
+ run,
949
+ stop: end,
950
+ cancel: () => {
951
+ end()
952
+ callback.call(UndefinedOr.getOrThrow(stops[0]))
953
+ },
954
+ duration: () => Machine.durationOf(env.runtime.runSync(machine)),
955
+ }
956
+ }
957
+
958
+ /**
959
+ * A sequence started (#433's PR 2, Motion's): compiled by core's `Sequence`, each element animated
960
+ * through its Keyframes on its spine or its plain one, as a call animates it, and each function
961
+ * Segment's value told to its callback; one Playhead for all, so it seeks, pauses and awaits as one.
962
+ */
963
+ const sequenceOf = (env: AnimateEnv, scope: Element | undefined, watch: AnimationWatch, sequence: WardicAnimationSequence, options: WardicSequenceOptions | undefined): WardicPlaybackControls => {
964
+ const defaults = UndefinedOr.map(options, (given) => given.defaultTransition)
965
+ // The sequence's own options over its `defaultTransition`'s, as Motion's.
966
+ const whole = {
967
+ ...picked(UndefinedOr.match(defaults as Readonly<Record<string, unknown>> | undefined, { onUndefined: () => NO_FIELDS, onDefined: identity }), WHOLE_DEFAULTS),
968
+ ...picked(UndefinedOr.match(options as Readonly<Record<string, unknown>> | undefined, { onUndefined: () => NO_FIELDS, onDefined: identity }), WHOLE),
969
+ } as Sequence.Options
970
+ const compiled = Arr.fromIterable(Sequence.compile(stepsOf(sequence, scope, defaults), whole))
971
+ // Each Batch's members as one track, their other keys their elements' (#665, Q40).
972
+ const parts = BatchMembers.sequencePartsOf<Element | Callback>(compiled)
973
+ return started(watch, compiled.length, UndefinedOr.map(options, (given) => given.onComplete), (head, settled) => [
974
+ ...Arr.map(parts.others, ([subject, animation]) =>
975
+ Match.value(subject).pipe(
976
+ Match.when(isCallback, (callback) => callbackTrackOf(env, callback, animation, head, settled)),
977
+ Match.orElse((element) => trackOf(env, element as Element, animation.keyframes as WardConfig.WardicVariant, animation.transition as WardConfig.WardicTransition, head, settled)),
978
+ )),
979
+ ...Arr.map(parts.batches, (part) =>
980
+ part.binding.sequenceTrack({ members: part.members, animations: part.animations, reducedMotion: env.reducedMotion(), skipAnimations: env.skipAnimations(), head, settled })),
981
+ ])
982
+ }
983
+
984
+ /**
985
+ * An animation scope: give it as an element's `ref`, and `animate`'s selectors are looked up inside
986
+ * that element. Motion's `AnimationScope`.
987
+ */
988
+ // #433.
989
+ export interface WardicAnimationScope<T extends Element = HTMLElement> {
990
+ /** Give it as the element's `ref`. */
991
+ (element: T): void
992
+ /** The element, once it's mounted. */
993
+ readonly current: T | undefined
994
+ /** Its animations in flight: started, and neither finished, stopped nor cancelled. */
995
+ readonly animations: ReadonlyArray<WardicPlaybackControls>
996
+ }
997
+
998
+ /**
999
+ * An Animation scope's ref and what it hears of its animations (#433): each in `animations` while in
1000
+ * flight, and `also` told too (Solid 2's `settled()`). `stopAll` stops them, at its owner's cleanup.
1001
+ */
1002
+ export const scopeOf = <T extends Element>(also?: AnimationWatch): {
1003
+ readonly scope: WardicAnimationScope<T>
1004
+ readonly watch: AnimationWatch
1005
+ readonly stopAll: () => void
1006
+ } => {
1007
+ let current: T | undefined
1008
+ // A set, and its array built only when `animations` is read, then kept until the set changes (#659):
1009
+ // an array copied at every start and every end made starting and ending n of them O(n²).
1010
+ const live = new Set<WardicPlaybackControls>()
1011
+ let listed: ReadonlyArray<WardicPlaybackControls> | undefined
1012
+ const animationsNow = (): ReadonlyArray<WardicPlaybackControls> => {
1013
+ if (Predicate.isUndefined(listed)) listed = Arr.fromIterable(live)
1014
+ return listed
1015
+ }
1016
+ const ref = (element: T): void => {
1017
+ current = element
1018
+ }
1019
+ const scope = Object.defineProperties(ref, {
1020
+ current: { get: () => current },
1021
+ animations: { get: animationsNow },
1022
+ }) as WardicAnimationScope<T>
1023
+ const watch: AnimationWatch = {
1024
+ started: (controls) => {
1025
+ live.add(controls)
1026
+ listed = undefined
1027
+ UndefinedOr.map(also, (more) => more.started(controls))
1028
+ },
1029
+ ended: (controls, landed) => {
1030
+ live.delete(controls)
1031
+ listed = undefined
1032
+ UndefinedOr.map(also, (more) => more.ended(controls, landed))
1033
+ },
1034
+ }
1035
+ // Stopping one ends it, which deletes it from the set: safe in the set's own walk.
1036
+ return { scope, watch, stopAll: () => Iter.forEach(live, (controls) => controls.stop()) }
1037
+ }