@wardic/core 1.0.1 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/dist/Batch.d.ts +4 -2
  2. package/dist/Batch.d.ts.map +1 -1
  3. package/dist/Batch.js +80 -13
  4. package/dist/Batch.js.map +1 -1
  5. package/dist/DefaultTransition.d.ts.map +1 -1
  6. package/dist/DefaultTransition.js +1 -1
  7. package/dist/DefaultTransition.js.map +1 -1
  8. package/dist/LiveValue.d.ts +61 -0
  9. package/dist/LiveValue.d.ts.map +1 -1
  10. package/dist/LiveValue.js +79 -5
  11. package/dist/LiveValue.js.map +1 -1
  12. package/dist/Machine.d.ts +10 -1
  13. package/dist/Machine.d.ts.map +1 -1
  14. package/dist/Machine.js +18 -1
  15. package/dist/Machine.js.map +1 -1
  16. package/dist/Renderer.js +2 -2
  17. package/dist/Renderer.js.map +1 -1
  18. package/dist/Spans.d.ts +41 -0
  19. package/dist/Spans.d.ts.map +1 -0
  20. package/dist/Spans.js +39 -0
  21. package/dist/Spans.js.map +1 -0
  22. package/dist/index.d.ts +1 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/internal/frameLoop.d.ts +1 -1
  27. package/dist/internal/frameLoop.d.ts.map +1 -1
  28. package/dist/internal/frameLoop.js +42 -19
  29. package/dist/internal/frameLoop.js.map +1 -1
  30. package/dist/internal/options.d.ts.map +1 -1
  31. package/dist/internal/options.js +2 -2
  32. package/dist/internal/options.js.map +1 -1
  33. package/dist/internal/tracing.d.ts +34 -14
  34. package/dist/internal/tracing.d.ts.map +1 -1
  35. package/dist/internal/tracing.js +56 -24
  36. package/dist/internal/tracing.js.map +1 -1
  37. package/dist/unstable/AnimationControls.d.ts +110 -0
  38. package/dist/unstable/AnimationControls.d.ts.map +1 -0
  39. package/dist/unstable/AnimationControls.js +107 -0
  40. package/dist/unstable/AnimationControls.js.map +1 -0
  41. package/dist/unstable/AppearHandoff.d.ts +53 -0
  42. package/dist/unstable/AppearHandoff.d.ts.map +1 -0
  43. package/dist/unstable/AppearHandoff.js +23 -0
  44. package/dist/unstable/AppearHandoff.js.map +1 -0
  45. package/dist/unstable/Config.d.ts +285 -0
  46. package/dist/unstable/Config.d.ts.map +1 -0
  47. package/dist/unstable/Config.js +3 -0
  48. package/dist/unstable/Config.js.map +1 -0
  49. package/dist/unstable/FlushGate.d.ts +222 -0
  50. package/dist/unstable/FlushGate.d.ts.map +1 -0
  51. package/dist/unstable/FlushGate.js +567 -0
  52. package/dist/unstable/FlushGate.js.map +1 -0
  53. package/dist/unstable/FrameTime.d.ts +21 -0
  54. package/dist/unstable/FrameTime.d.ts.map +1 -0
  55. package/dist/unstable/FrameTime.js +45 -0
  56. package/dist/unstable/FrameTime.js.map +1 -0
  57. package/dist/unstable/MeasuredPairs.d.ts +51 -0
  58. package/dist/unstable/MeasuredPairs.d.ts.map +1 -0
  59. package/dist/unstable/MeasuredPairs.js +20 -0
  60. package/dist/unstable/MeasuredPairs.js.map +1 -0
  61. package/dist/unstable/OwnValues.d.ts +29 -0
  62. package/dist/unstable/OwnValues.d.ts.map +1 -0
  63. package/dist/unstable/OwnValues.js +22 -0
  64. package/dist/unstable/OwnValues.js.map +1 -0
  65. package/dist/unstable/PresenceRecord.d.ts +176 -0
  66. package/dist/unstable/PresenceRecord.d.ts.map +1 -0
  67. package/dist/unstable/PresenceRecord.js +26 -0
  68. package/dist/unstable/PresenceRecord.js.map +1 -0
  69. package/dist/unstable/Reactivity.d.ts +29 -0
  70. package/dist/unstable/Reactivity.d.ts.map +1 -0
  71. package/dist/unstable/Reactivity.js +15 -0
  72. package/dist/unstable/Reactivity.js.map +1 -0
  73. package/dist/unstable/Report.d.ts +30 -0
  74. package/dist/unstable/Report.d.ts.map +1 -0
  75. package/dist/unstable/Report.js +66 -0
  76. package/dist/unstable/Report.js.map +1 -0
  77. package/dist/unstable/RetargetLegs.d.ts +189 -0
  78. package/dist/unstable/RetargetLegs.d.ts.map +1 -0
  79. package/dist/unstable/RetargetLegs.js +834 -0
  80. package/dist/unstable/RetargetLegs.js.map +1 -0
  81. package/dist/unstable/Spine.d.ts +696 -0
  82. package/dist/unstable/Spine.d.ts.map +1 -0
  83. package/dist/unstable/Spine.js +2617 -0
  84. package/dist/unstable/Spine.js.map +1 -0
  85. package/dist/unstable/Stops.d.ts +82 -0
  86. package/dist/unstable/Stops.d.ts.map +1 -0
  87. package/dist/unstable/Stops.js +149 -0
  88. package/dist/unstable/Stops.js.map +1 -0
  89. package/dist/unstable/Subject.d.ts +11 -0
  90. package/dist/unstable/Subject.d.ts.map +1 -0
  91. package/dist/unstable/Subject.js +12 -0
  92. package/dist/unstable/Subject.js.map +1 -0
  93. package/dist/unstable/Timelines.d.ts +51 -0
  94. package/dist/unstable/Timelines.d.ts.map +1 -0
  95. package/dist/unstable/Timelines.js +10 -0
  96. package/dist/unstable/Timelines.js.map +1 -0
  97. package/dist/unstable/VariableValues.d.ts +27 -0
  98. package/dist/unstable/VariableValues.d.ts.map +1 -0
  99. package/dist/unstable/VariableValues.js +19 -0
  100. package/dist/unstable/VariableValues.js.map +1 -0
  101. package/dist/unstable/VariantTarget.d.ts +106 -0
  102. package/dist/unstable/VariantTarget.d.ts.map +1 -0
  103. package/dist/unstable/VariantTarget.js +185 -0
  104. package/dist/unstable/VariantTarget.js.map +1 -0
  105. package/dist/unstable/VariantTree.d.ts +351 -0
  106. package/dist/unstable/VariantTree.d.ts.map +1 -0
  107. package/dist/unstable/VariantTree.js +362 -0
  108. package/dist/unstable/VariantTree.js.map +1 -0
  109. package/dist/unstable/WardicConfigValue.d.ts +89 -0
  110. package/dist/unstable/WardicConfigValue.d.ts.map +1 -0
  111. package/dist/unstable/WardicConfigValue.js +106 -0
  112. package/dist/unstable/WardicConfigValue.js.map +1 -0
  113. package/dist/unstable/WardicServices.d.ts +46 -0
  114. package/dist/unstable/WardicServices.d.ts.map +1 -0
  115. package/dist/unstable/WardicServices.js +72 -0
  116. package/dist/unstable/WardicServices.js.map +1 -0
  117. package/package.json +1 -1
  118. package/src/Batch.ts +68 -12
  119. package/src/DefaultTransition.ts +1 -1
  120. package/src/LiveValue.ts +129 -5
  121. package/src/Machine.ts +22 -1
  122. package/src/Renderer.ts +2 -2
  123. package/src/Spans.ts +50 -0
  124. package/src/index.ts +1 -0
  125. package/src/internal/frameLoop.ts +44 -20
  126. package/src/internal/options.ts +2 -2
  127. package/src/internal/tracing.ts +82 -28
  128. package/src/unstable/AnimationControls.ts +199 -0
  129. package/src/unstable/AppearHandoff.ts +81 -0
  130. package/src/unstable/Config.ts +326 -0
  131. package/src/unstable/FlushGate.ts +730 -0
  132. package/src/unstable/FrameTime.ts +52 -0
  133. package/src/unstable/MeasuredPairs.ts +56 -0
  134. package/src/unstable/OwnValues.ts +32 -0
  135. package/src/unstable/PresenceRecord.ts +201 -0
  136. package/src/unstable/Reactivity.ts +35 -0
  137. package/src/unstable/Report.ts +75 -0
  138. package/src/unstable/RetargetLegs.ts +1062 -0
  139. package/src/unstable/Spine.ts +3275 -0
  140. package/src/unstable/Stops.ts +221 -0
  141. package/src/unstable/Subject.ts +13 -0
  142. package/src/unstable/Timelines.ts +58 -0
  143. package/src/unstable/VariableValues.ts +27 -0
  144. package/src/unstable/VariantTarget.ts +246 -0
  145. package/src/unstable/VariantTree.ts +643 -0
  146. package/src/unstable/WardicConfigValue.ts +154 -0
  147. package/src/unstable/WardicServices.ts +125 -0
@@ -0,0 +1,3275 @@
1
+ /**
2
+ * The motion spine's Retarget (ADR-0005), on every binding: what an element does from its mount on
3
+ * when its target changes. A binding mounts the element, resolves its Override stack reactively
4
+ * ({@link resolutionOf}), and calls {@link ElementSpine.retarget} on each change, read where its
5
+ * reactivity doesn't track; everything a Retarget does is here:
6
+ *
7
+ * end the running legs -> carry the keys no entry sets back to their Base values (ADR-0022) ->
8
+ * start each key from its Snapshot (ADR-0024) -> take over an Appear animation (ADR-0044) ->
9
+ * build the legs (`RetargetLegs`) and run each into the gate -> `gate.write`.
10
+ *
11
+ * With it, the helpers both bindings' Wards share: the Starting values, the Base values' start links,
12
+ * the sink wrappers, and what a server render reads.
13
+ *
14
+ * Unstable, for Wardic's own packages: public, with no semver promise.
15
+ *
16
+ * @module
17
+ */
18
+ // Unstable: ADR-0071, decision 5. #672: solid's `spine.ts`, moved for every binding's elements to run it
19
+ // from core, Foldkit's among them; with it, the Batch hold's slot (Q14).
20
+ import * as BaseValue from "../BaseValue.ts"
21
+ import type * as DefaultTransition from "../DefaultTransition.ts"
22
+ import * as Frame from "../Frame.ts"
23
+ import type * as FrameLoop from "../FrameLoop.ts"
24
+ import * as InterpolatorRegistry from "../InterpolatorRegistry.ts"
25
+ import * as Machine from "../Machine.ts"
26
+ import * as Override from "../Override.ts"
27
+ import type * as ReducedMotion from "../ReducedMotion.ts"
28
+ import * as Supersede from "../Supersede.ts"
29
+ import * as Values from "../Values.ts"
30
+ import * as Report from "./Report.ts"
31
+ import type * as MeasuredPairs from "./MeasuredPairs.ts"
32
+ import type * as OwnValues from "./OwnValues.ts"
33
+ import type * as VariableValues from "./VariableValues.ts"
34
+ import type * as Stops from "./Stops.ts"
35
+ import type * as Subject from "./Subject.ts"
36
+ import type * as FlushGate from "./FlushGate.ts"
37
+ import * as Arr from "effect/Array"
38
+ import * as Bool from "effect/Boolean"
39
+ import * as Cause from "effect/Cause"
40
+ import * as Context from "effect/Context"
41
+ import * as Effect from "effect/Effect"
42
+ import * as Equivalence from "effect/Equivalence"
43
+ import * as Exit from "effect/Exit"
44
+ import * as Fiber from "effect/Fiber"
45
+ import { constFalse, constUndefined, constVoid, identity } from "effect/Function"
46
+ import * as Iter from "effect/Iterable"
47
+ import * as Match from "effect/Match"
48
+ import * as Option from "effect/Option"
49
+ import * as Predicate from "effect/Predicate"
50
+ import * as Rec from "effect/Record"
51
+ import type * as Atom from "effect/reactivity/Atom"
52
+ import * as AtomRegistry from "effect/reactivity/AtomRegistry"
53
+ import * as UndefinedOr from "effect/UndefinedOr"
54
+ import * as AppearHandoff from "./AppearHandoff.ts"
55
+ import type * as Config from "./Config.ts"
56
+ import * as AnimationControls from "./AnimationControls.ts"
57
+ import * as FrameTime from "./FrameTime.ts"
58
+ import * as PresenceRecord from "./PresenceRecord.ts"
59
+ import type * as Reactivity from "./Reactivity.ts"
60
+ import * as RetargetLegs from "./RetargetLegs.ts"
61
+ import type * as WardicServices from "./WardicServices.ts"
62
+ import * as Timelines from "./Timelines.ts"
63
+ import * as VariantTree from "./VariantTree.ts"
64
+ import * as VariantTarget from "./VariantTarget.ts"
65
+
66
+ // #672: declared here, as core's `Microtask.ts` declares it, since core builds with no DOM in its lib.
67
+ declare const queueMicrotask: (callback: () => void) => void
68
+
69
+ export { NO_VARIANT_STATE, resolveTarget, type Target, transitionOfTarget, type VariantState } from "./VariantTarget.ts"
70
+
71
+ /** What an element's exit is resolved from (#277): its last config, kept current while it's alive. */
72
+ export interface ExitConfig {
73
+ readonly exit: Config.WardicVariant | Config.WardicVariantLabels | undefined
74
+ readonly variants: Config.WardicVariants | undefined
75
+ readonly custom: unknown
76
+ /** Its `transition`, or the one it inherits. */
77
+ readonly transition: Config.WardicTransition | undefined
78
+ }
79
+
80
+ /** No exit: an element outside a presence never resolves one. */
81
+ export const NO_EXIT_CONFIG: ExitConfig = { exit: undefined, variants: undefined, custom: undefined, transition: undefined }
82
+
83
+ /** A record's place in the variant tree (#290), from its config at setup. */
84
+ export const presenceTreeOf = (c: Config.SpineConfig): PresenceRecord.PresenceTree => ({
85
+ joins: VariantTree.isVariantChild(c),
86
+ provides: VariantTree.changesContext(c),
87
+ twin: Predicate.isNotUndefined(c.layoutId),
88
+ })
89
+
90
+ /**
91
+ * An element's ref that tells its presence it was made (#286, ADR-0048): its `key`, read once, and
92
+ * whether it's a twin. With no presence, `set` itself: nothing is made per element.
93
+ */
94
+ export const madeWith = <E extends Subject.Subject>(presence: PresenceRecord.PresenceContextValue<E> | undefined, set: (el: E) => void, c: Config.SpineConfig): ((el: E) => void) => {
95
+ if (Predicate.isUndefined(presence)) return set
96
+ const key = c.key
97
+ const twin = Predicate.isNotUndefined(c.layoutId)
98
+ return (el) => {
99
+ PresenceRecord.presenceMade(presence, el, key, twin)
100
+ set(el)
101
+ }
102
+ }
103
+
104
+ /** An element's {@link ExitConfig} from its config now. */
105
+ export const exitConfigOf = (c: Config.SpineConfig, parent: VariantTree.WardicVariantContextValue | undefined): ExitConfig => ({
106
+ exit: c.exit,
107
+ variants: c.variants,
108
+ custom: c.custom,
109
+ transition: VariantTree.ownOrInherited(c.transition, parent),
110
+ })
111
+
112
+ /** An exit resolved (#277): its values, and the transition it runs on. */
113
+ export type ExitTarget = PresenceRecord.PresenceExit
114
+
115
+ /**
116
+ * Resolve an element's exit as it leaves (#277): with its `<AnimatePresence custom>` when that's
117
+ * given (Motion's: the leaving element's own props can't change any more), else its own `custom`; on
118
+ * its own transition, else the element's.
119
+ */
120
+ export const exitTargetOf = (config: ExitConfig, presenceCustom: unknown, state: VariantTarget.VariantState, inherited: Config.WardicVariantLabels | undefined): ExitTarget => {
121
+ const custom = UndefinedOr.match(presenceCustom, { onUndefined: () => config.custom, onDefined: identity })
122
+ // Its own `exit` wins; a Variant child with none exits on the name its provider hands down (#290).
123
+ const entry: VariantTarget.Entry = UndefinedOr.match(config.exit, { onDefined: identity, onUndefined: (): VariantTarget.Entry => inherited })
124
+ const name = UndefinedOr.match(VariantTree.nameOf(config.exit), { onDefined: identity, onUndefined: () => inherited })
125
+ if (Arr.isArray(entry)) {
126
+ // A list (#297): merged, and each name's own keys on its own transition.
127
+ const targets = VariantTarget.resolveTargets(entry, config.variants, custom, state)
128
+ const merged = VariantTarget.mergedOf(targets)
129
+ return {
130
+ values: merged.values,
131
+ transition: VariantTarget.transitionOfTarget(merged.transition, config.transition),
132
+ name,
133
+ groups: exitGroupsOf(targets, config.transition),
134
+ keyframes: merged.keyframes,
135
+ }
136
+ }
137
+ const target = VariantTarget.resolveTarget(entry, config.variants, custom, state)
138
+ return { values: target.values, transition: VariantTarget.transitionOfTarget(target.transition, config.transition), name, keyframes: target.keyframes }
139
+ }
140
+
141
+ /** A list's exit groups (#297): each name, with the keys it's the last to set, on its own transition else `element`. */
142
+ const exitGroupsOf = (targets: ReadonlyArray<VariantTarget.NamedTarget>, element: Config.WardicTransition | undefined): ReadonlyArray<PresenceRecord.ExitGroup> =>
143
+ Arr.map(targets, (target, i) => ({
144
+ name: target.name as string,
145
+ values: Rec.filter(target.values, (_, key) => Bool.not(Arr.some(Arr.drop(targets, i + 1), (later) => Object.hasOwn(later.values, key)))),
146
+ transition: VariantTarget.transitionOfTarget(target.transition, element),
147
+ }))
148
+
149
+ /** A config given as a value or as an accessor, as an accessor. A config is always an object, so a function is the accessor. */
150
+ export const accessorOf = <A extends object>(config: A | Reactivity.Accessor<A>): Reactivity.Accessor<A> =>
151
+ Bool.match(Predicate.isFunction(config), { onTrue: () => config as Reactivity.Accessor<A>, onFalse: () => () => config as A })
152
+
153
+ /**
154
+ * `transition` with a stagger delay folded into its own and its entries' (ADR-0007, #301), reused
155
+ * while its fields are (#66).
156
+ */
157
+ const staggeredOf = (
158
+ transition: Config.WardicTransition | undefined,
159
+ extra: number,
160
+ reuse: (transition: Config.WardicTransition) => Config.WardicTransition,
161
+ ): Config.WardicTransition | undefined => UndefinedOr.map(RetargetLegs.delayedBy(transition, extra), reuse)
162
+
163
+ /**
164
+ * A Retarget's keys by the entry that drives each (#291), when an active entry (the base's included)
165
+ * has its own transition: the highest active entry that sets it, and the base for a key none sets (a
166
+ * return). `undefined` when none has: one transition for every key.
167
+ */
168
+ const keysByLayerOf = (
169
+ t: Values.Values,
170
+ layers: ReadonlyArray<OverrideEntry>,
171
+ extraDelay: ((name: string | undefined) => number) | undefined,
172
+ extra: number,
173
+ listed: boolean,
174
+ shut: ReadonlyArray<boolean> | undefined,
175
+ ): ReadonlyArray<ReadonlySet<string>> | undefined => {
176
+ // Per Retarget (#460): statements.
177
+ if (!Arr.some(layers, hasOwnTransition) && !delaysDiffer(layers, extraDelay, extra) && !anyShutOf(shut)) return undefined
178
+ // A list's returns in a group of their own, after its entries' (#297).
179
+ let returnsAt = 0
180
+ if (listed) returnsAt = layers.length
181
+ const groups = Arr.makeBy(Math.max(layers.length, returnsAt + 1), () => new Set<string>())
182
+ Arr.forEach(Rec.keys(t), (key) => {
183
+ // A key only a Transition end sets (#428) is in its entry's group too, as the entry's own.
184
+ const at = Option.getOrElse(Arr.findLastIndex(layers, (layer) => Bool.and(layer.active, Bool.or(Object.hasOwn(layer.values, key), Object.hasOwn(layer.ends, key)))), () => returnsAt)
185
+ UndefinedOr.map(groups[at], (group) => group.add(key))
186
+ })
187
+ return groups
188
+ }
189
+
190
+ /**
191
+ * The transition `key` animates on in a Retarget: its group's (#277, #297), else the Retarget's one,
192
+ * with no stagger (#448 reads its fields, not its delay).
193
+ */
194
+ const keyTransitionOf = (
195
+ resolution: Resolution,
196
+ groups: ReadonlyArray<ReadonlySet<string>> | undefined,
197
+ key: string,
198
+ transition: Config.WardicTransition | undefined,
199
+ element: Config.WardicTransition | undefined,
200
+ ): Config.WardicTransition | undefined => {
201
+ if (Predicate.isUndefined(groups)) return transition
202
+ return groupTransitionOf(resolution, groups, Option.getOrElse(Arr.findFirstIndex(groups, (group) => group.has(key)), () => -1), transition, element, undefined, identity)
203
+ }
204
+
205
+ /** Whether `given` gives `key` a velocity (#448, Motion's `valueTransition.velocity`): it kicks the key, so it animates though at its target. */
206
+ const givesVelocity = (given: Config.WardicTransition | undefined, key: string): boolean => {
207
+ const own = RetargetLegs.transitionForKey(given, key) as { readonly velocity?: unknown } | undefined
208
+ if (Predicate.isUndefined(own)) return false
209
+ return Bool.and(Predicate.isNumber(own.velocity), own.velocity !== 0)
210
+ }
211
+
212
+ /** A key's velocity in the Snapshot, 0 with none (#448). Per key, per Retarget: a guard. */
213
+ const velocityOf = (snapshot: { readonly velocities: Readonly<Record<string, number>> }, key: string): number => {
214
+ const velocity = snapshot.velocities[key]
215
+ if (Predicate.isUndefined(velocity)) return 0
216
+ return velocity
217
+ }
218
+
219
+ /** `t`'s keys in the `i`th group, or all of them when there are no groups. */
220
+ const pickKeys = (t: Values.Values, groups: ReadonlyArray<ReadonlySet<string>> | undefined, i: number): Values.Values => {
221
+ if (Predicate.isUndefined(groups)) return t
222
+ const group = groups[i]
223
+ if (Predicate.isUndefined(group)) return {}
224
+ return Rec.filter(t, (_, key) => group.has(key))
225
+ }
226
+
227
+ /** A transition's `delay`, 0 without one. */
228
+ export const delayOf = (transition: Config.WardicTransition | undefined): number =>
229
+ UndefinedOr.match(transition, { onUndefined: () => 0, onDefined: ({ delay = 0 }) => delay })
230
+
231
+ /** No keys: what a drag moves on a projected element, or one with no drag. */
232
+ const NO_KEYS: ReadonlyArray<string> = []
233
+
234
+ /** The keys a drag of `axis` moves directly. Built once, at module load. */
235
+ const dragMovesOf: (axis: boolean | "x" | "y") => ReadonlyArray<string> = Match.type<boolean | "x" | "y">().pipe(
236
+ Match.when("x", (): ReadonlyArray<string> => ["x"]),
237
+ Match.when("y", (): ReadonlyArray<string> => ["y"]),
238
+ Match.orElse((): ReadonlyArray<string> => ["x", "y"]),
239
+ )
240
+
241
+ /** Whether a start link's value takes its target's shape: both numbers, or both strings. */
242
+ const isSameKind = (value: number | string, like: number | string): boolean => Predicate.isNumber(value) === Predicate.isNumber(like)
243
+
244
+ /** The keys a drag direct-sets (ADR-0004). */
245
+ const TRANSLATE_KEYS: ReadonlySet<string> = new Set(["x", "y", "translateX", "translateY"])
246
+ const TRANSLATE_KEY_LIST: ReadonlyArray<string> = Arr.fromIterable(TRANSLATE_KEYS)
247
+
248
+ /** Whether a value map has any key. */
249
+ const hasKeys: Predicate.Predicate<Values.Values> = Predicate.not(Rec.isEmptyRecord)
250
+
251
+ /**
252
+ * Whether two transitions have the same keys, each holding the same value (`===`), an entry the
253
+ * same fields (#301: a stagger makes each entry anew).
254
+ */
255
+ const sameFields = (a: object, b: object): boolean => {
256
+ const ra = a as Readonly<Record<string, unknown>>
257
+ const rb = b as Readonly<Record<string, unknown>>
258
+ const keys = Rec.keys(ra)
259
+ if (keys.length !== Rec.keys(rb).length) return false
260
+ return Arr.every(keys, (key) => {
261
+ if (Bool.not(key in rb)) return false
262
+ return sameField(ra[key], rb[key])
263
+ })
264
+ }
265
+
266
+ /** Whether two fields are the same: `===`, or two entries with the same fields (#301). */
267
+ const sameField = (a: unknown, b: unknown): boolean => {
268
+ if (a === b) return true
269
+ if (Bool.and(Predicate.isObject(a), Predicate.isObject(b))) return sameFields(a as object, b as object)
270
+ return false
271
+ }
272
+
273
+ /** The Override stack resolved: a Retarget's input. */
274
+ export interface Resolution {
275
+ /** Each key's value from the highest active entry. */
276
+ readonly resolved: Values.Values
277
+ /** The base entry, the first link of a key's Base value (ADR-0022). */
278
+ readonly base: Values.Values
279
+ /** Whether a drag holds the translate keys (ADR-0004's strip). */
280
+ readonly dragging: boolean
281
+ /** The variant name (or list, #297) the base entry resolved: its own `animate`'s, else the one it inherits; none for a values map. */
282
+ readonly variant: Config.WardicVariantLabels | undefined
283
+ /** The entries it was resolved with (#257): a landing's gestures are the ones its Retarget started with. */
284
+ readonly active: Active
285
+ /** The base target's own transition (#277): the keys the base entry drives animate on it. */
286
+ readonly transition: Config.WardicVariantTransition | undefined
287
+ /**
288
+ * The Override stack's entries (#291): the base, then each gesture's, lowest first. A Retarget runs
289
+ * each key on the own transition of the highest active entry that sets it.
290
+ */
291
+ readonly layers: ReadonlyArray<OverrideEntry>
292
+ /** The names its active gesture layers resolved (#291): its own `while*` names, else those it took. */
293
+ readonly names: VariantTree.GestureNames
294
+ /**
295
+ * Which gesture layers are on and set values or a Transition end (#470); a named one is in `names`.
296
+ * One turning on or off is a new target, whatever it resolves, as a Motion type turning active
297
+ * animates (`animation-state.ts`).
298
+ */
299
+ readonly layersOn: VariantTree.GestureStates
300
+ /** Its entries' **Transition ends** (#428), when any active one has one. */
301
+ readonly ends: Ends | undefined
302
+ /** Each key's **Keyframes**, as the entry that drives it gives them (#429), when any active entry has some. */
303
+ readonly keyframes: KeyframesNow | undefined
304
+ /**
305
+ * The **Controls change** in effect (#433): its own controls' latest, else the one its provider is
306
+ * in, for a Variant child. A new one is a Retarget, whatever it resolves to.
307
+ */
308
+ readonly change: AnimationControls.ControlsChange | undefined
309
+ }
310
+
311
+ /**
312
+ * A key's **Keyframes** as a Retarget resolves them (#429): their stops, and the entry that drives the
313
+ * key, by its place in the Override stack and the variant name it resolved. Two are the same when all
314
+ * three are, Motion's rule for when Keyframes play again (`animation-state.ts`): an equal list, stop by
315
+ * stop, that a re-render makes runs on, where new stops, another entry driving the key (a hover over it
316
+ * ending) or a new name for its entry (`variantDidChange`) plays them again from their first stop.
317
+ */
318
+ export interface KeyframesAt {
319
+ readonly stops: Stops.Stops
320
+ readonly layer: number
321
+ readonly name: string | undefined
322
+ }
323
+
324
+ /** Each key's {@link KeyframesAt}. */
325
+ export type KeyframesNow = Readonly<Record<string, KeyframesAt>>
326
+
327
+ /**
328
+ * A resolution's **Transition ends** (#428): each key only an entry's Transition end sets, with the
329
+ * entry that drives it (the highest active one that sets it, as for any key), and each entry's end
330
+ * values for the keys it drives, a key it also animates among them.
331
+ */
332
+ export interface Ends {
333
+ readonly endOnly: ReadonlyMap<string, number>
334
+ readonly byLayer: ReadonlyArray<Values.Values | undefined>
335
+ }
336
+
337
+ /**
338
+ * One entry of the Override stack (#291): whether it's on, its values, its target's own transition,
339
+ * and the variant name it resolved (#297), `undefined` for a values map. A list of names is an entry
340
+ * a name, in order.
341
+ */
342
+ export interface OverrideEntry {
343
+ readonly active: boolean
344
+ readonly values: Values.Values
345
+ readonly transition: Config.WardicVariantTransition | undefined
346
+ readonly name: string | undefined
347
+ /** Its target's **Transition end** (#428): its keys are the entry's, set once its animated keys land. */
348
+ readonly ends: Values.Values
349
+ /** Its target's **Keyframes** (#429): each such key's stops, its value in `values` their last. */
350
+ readonly keyframes: VariantTarget.Keyframes | undefined
351
+ }
352
+
353
+ /** A gesture layer that's off: nothing is resolved for it. */
354
+ const OFF: OverrideEntry = { active: false, values: {}, transition: undefined, name: undefined, ends: {}, keyframes: undefined }
355
+
356
+ /**
357
+ * A gesture layer (#291), while it's on (its own, or its provider's): its own `while*` (a target, or
358
+ * a variant name), else the label its provider hands down. Off, or with neither, nothing is resolved.
359
+ * Whether it set values or a Transition end (#470).
360
+ */
361
+ const gestureLayersInto = (
362
+ layers: Array<OverrideEntry>,
363
+ own: VariantTarget.Entry,
364
+ on: boolean,
365
+ label: Config.WardicVariantLabels | undefined,
366
+ variants: Config.WardicVariants | undefined,
367
+ custom: unknown,
368
+ state: VariantTarget.VariantState,
369
+ ): boolean => {
370
+ if (Bool.not(on)) {
371
+ layers.push(OFF)
372
+ return false
373
+ }
374
+ const entry = UndefinedOr.match(own, { onDefined: identity, onUndefined: (): VariantTarget.Entry => label })
375
+ if (Predicate.isUndefined(entry)) {
376
+ layers.push(OFF)
377
+ return false
378
+ }
379
+ // A list is an entry a name, in order (#297): the last name that sets a key drives it.
380
+ if (Arr.isArray(entry)) {
381
+ let sets = false
382
+ Arr.forEach(VariantTarget.resolveTargets(entry, variants, custom, state), (target) => {
383
+ const layer = namedLayerOf(target)
384
+ layers.push(layer)
385
+ if (setsValues(layer)) sets = true
386
+ })
387
+ return sets
388
+ }
389
+ const layer = layerOf(VariantTarget.resolveTarget(entry, variants, custom, state), labelOrUndefined(entry))
390
+ layers.push(layer)
391
+ return setsValues(layer)
392
+ }
393
+
394
+ /**
395
+ * Whether a gesture layer sets values or a Transition end (#470). A values map with none sets
396
+ * nothing; a name that resolves none is told by its name (`names`), as Motion animates it.
397
+ */
398
+ const setsValues = (layer: OverrideEntry): boolean => {
399
+ if (hasKeys(layer.values)) return true
400
+ return hasKeys(layer.ends)
401
+ }
402
+
403
+ /** A single entry's name: itself, if a name; `undefined` for a values map. */
404
+ const labelOrUndefined = (entry: VariantTarget.Entry): string | undefined => Bool.match(Predicate.isString(entry), { onTrue: () => entry as string, onFalse: constUndefined })
405
+
406
+ /** Each gesture on: the element's own, or its provider's too when it has one handing any down. */
407
+ const gesturesOnOf = (active: Active, above: VariantTree.GestureHandDown): VariantTree.GestureStates => {
408
+ if (above === VariantTree.NO_HAND_DOWN) return active
409
+ return VariantTree.gesturesOn(active, above.on)
410
+ }
411
+
412
+ /**
413
+ * The name each gesture layer resolves while it's on (#291): its own `while*`, if a name, else the
414
+ * label it took. With none on, the shared empty one: nothing made.
415
+ */
416
+ const activeNamesFor = (c: Config.SpineConfig, on: VariantTree.GestureStates, labels: VariantTree.GestureNames): VariantTree.GestureNames => {
417
+ if (Bool.not(anyOn(on))) return VariantTree.NO_GESTURE_NAMES
418
+ return VariantTree.activeNamesOf(VariantTree.handDownOf(c, on, { on: VariantTree.NO_GESTURE_STATES, names: labels }))
419
+ }
420
+
421
+ /** Whether any gesture is on: per Retarget, so no closure. */
422
+ const anyOn = (on: VariantTree.GestureStates): boolean => on.inView || on.focused || on.hovered || on.pressed || on.dragged
423
+
424
+ /**
425
+ * Whether an active entry's name delays its keys otherwise than the first entry's (#297): a Variant
426
+ * child's names each take their own stagger slot. Never for an element that joins none, nor for one
427
+ * entry.
428
+ */
429
+ const delaysDiffer = (layers: ReadonlyArray<OverrideEntry>, extraDelay: ((name: string | undefined) => number) | undefined, extra: number): boolean => {
430
+ if (Bool.or(Predicate.isUndefined(extraDelay), layers.length < 2)) return false
431
+ return Arr.some(layers, (layer) => Bool.and(layer.active, extraOf(extraDelay, layer) !== extra))
432
+ }
433
+
434
+ /** An entry's stagger delay (ADR-0007, #297): its name's, for a Variant child; 0 for any other element. */
435
+ const extraOf = (extraDelay: ((name: string | undefined) => number) | undefined, layer: OverrideEntry | undefined): number => {
436
+ if (Predicate.isUndefined(extraDelay)) return 0
437
+ if (Predicate.isUndefined(layer)) return extraDelay(undefined)
438
+ return extraDelay(layer.name)
439
+ }
440
+
441
+ /**
442
+ * The transition a key group runs on (#291, #297): unsplit, the base's (`transition`, its delay
443
+ * folded in); split, its entry's own, else the element's, at its name's delay. A list's first
444
+ * group carries its returns too, which run on the element's transition, as a list's base has no one
445
+ * transition of its own.
446
+ */
447
+ const groupTransitionOf = (
448
+ resolution: Resolution,
449
+ groups: ReadonlyArray<ReadonlySet<string>> | undefined,
450
+ i: number,
451
+ transition: Config.WardicTransition | undefined,
452
+ element: Config.WardicTransition | undefined,
453
+ extraDelay: ((name: string | undefined) => number) | undefined,
454
+ reuse: (transition: Config.WardicTransition) => Config.WardicTransition,
455
+ ): Config.WardicTransition | undefined => {
456
+ if (Predicate.isUndefined(groups)) return transition
457
+ if (Bool.and(i === 0, Bool.not(Arr.isArray(resolution.variant)))) return transition
458
+ const layer = resolution.layers[i]
459
+ // A list's returns: the element's, at its whole orchestration's delay.
460
+ if (Predicate.isUndefined(layer)) return staggeredOf(element, extraOf(extraDelay, undefined), reuse)
461
+ return staggeredOf(VariantTarget.transitionOfTarget(layer.transition, element), extraOf(extraDelay, layer), reuse)
462
+ }
463
+
464
+ /** No names. */
465
+ const NO_NAMES: ReadonlyArray<string> = []
466
+
467
+ /** No legs. */
468
+ const NO_LEGS: ReadonlyArray<RetargetLegs.Leg> = []
469
+
470
+ /**
471
+ * Where a Retarget's legs land (#257, #325): what each running leg's frames and end are told to.
472
+ * The last Retarget's, which every running leg counts toward, the ones it carried included.
473
+ */
474
+ export interface Landing {
475
+ /** A leg drew a frame: its last, when `done`. */
476
+ readonly report: (done: boolean) => void
477
+ /** A leg settled. */
478
+ readonly settled: () => void
479
+ /** A leg failed (#257 item 4). */
480
+ readonly failed: (cause: Cause.Cause<unknown>) => void
481
+ }
482
+
483
+ /**
484
+ * A gated Retarget's landing (ADR-0007 `when`, #325): the legs it carries report the element
485
+ * unsettled, as it still owes an animation, and land nothing; the Retarget once the gate opens
486
+ * counts them.
487
+ */
488
+ const gatedLandingOf = (onFrame: ((done: boolean) => void) | undefined): Landing => ({
489
+ report: () => {
490
+ if (Predicate.isNotUndefined(onFrame)) onFrame(false)
491
+ },
492
+ settled: constVoid,
493
+ failed: constVoid,
494
+ })
495
+
496
+ /**
497
+ * A running leg (#325): the keys it draws, each with the target its Retarget resolved, and the
498
+ * landing its frames and end count toward. It's its machines' run options, with its own token
499
+ * (#200): a later Retarget that resolves a key to the same target leaves the leg that key, every
500
+ * other key is given up, and a leg left with none is ended.
501
+ */
502
+ export interface Running extends Machine.RunOptions {
503
+ /** Each key it animates, with the target its Retarget gave it. */
504
+ readonly targets: Values.Values
505
+ /** The resolution of the Retarget that started it: a `when` gate holds that change's legs. */
506
+ readonly resolution: Resolution
507
+ /** How many of its keys it still draws. */
508
+ count: number
509
+ /** A frame's values for the keys it still draws: the frame's own while it draws all of them. */
510
+ values: (value: Values.Values) => Values.Values
511
+ /** It drew its last frame: its keys landed. */
512
+ done: boolean
513
+ /** It gave up a key in this Retarget: what it still draws is worked out at the Retarget's end. */
514
+ losing: boolean
515
+ fiber: Fiber.Fiber<void> | undefined
516
+ /** The landing it counts toward: its Retarget's, then the one of each Retarget that carried it. */
517
+ landing: Landing
518
+ /** A list's names its end is told to (#297), for the Retarget it counts toward. */
519
+ names: ((end: unknown) => void) | undefined
520
+ /** Its kind (#464): a Blend leg's keys' velocities are its frames', a Snap's none, the rest write their own. */
521
+ readonly kind: RetargetLegs.Leg["_tag"]
522
+ /** The frames it has drawn (#464). */
523
+ frames: number
524
+ /** When it drew its last frame, on {@link FrameTime.frameNow}'s clock; -Infinity before its first (#464). */
525
+ lastAt: number
526
+ /** A Blend leg's last frame's values, and the ones before them (the Snapshot's, before its first) and when (#464). */
527
+ last: Values.Values | undefined
528
+ before: Values.Values | undefined
529
+ beforeAt: number
530
+ /**
531
+ * A Numbers leg's last Frame (#663): its keys' velocities are read from it when one is asked for, as
532
+ * a Blend leg's are from its frames, by index from a spring's. None before its first frame.
533
+ */
534
+ physics: Frame.MultiPhysics | undefined
535
+ }
536
+
537
+ /** No running legs. */
538
+ export const NO_RUNNING: ReadonlyArray<Running> = []
539
+
540
+ /**
541
+ * An entry's Transition end waiting for its keys to land (#428, #508): no fiber of its own. Its `running`
542
+ * holds the keys only it sets, counts toward its landing and is given up as any leg's; the landing of
543
+ * its keys' last leg makes it due, and it's written at the next flush.
544
+ */
545
+ interface PendingEnd {
546
+ readonly running: Running
547
+ /** The keys its entry animates, each held by the leg drawing it. */
548
+ readonly animated: ReadonlyArray<string>
549
+ /** Its Transition end, the keys it also animates among them. */
550
+ readonly writes: Values.Values
551
+ /**
552
+ * An end that owns no key, its values all keys its entry animates: the leg drawing each of
553
+ * `animated` as it was made. Nothing gives such an end up, so a key's leg given up or replaced
554
+ * before it lands, the target interrupted, drops it (ADR-0057 Q1). Undefined for one that owns keys,
555
+ * which an interrupt gives up.
556
+ */
557
+ readonly legs: ReadonlyArray<Running | undefined> | undefined
558
+ state: "waiting" | "due" | "written" | "dropped"
559
+ }
560
+
561
+ /** An element's waiting Transition ends (#508). */
562
+ interface WaitingEnds {
563
+ /** An entry's end, waiting for its keys, or due already when they've landed. */
564
+ readonly add: (end: PendingEnd) => void
565
+ /** A leg landed: each end whose keys now all have is due, written at the next flush. */
566
+ readonly land: () => void
567
+ /** The end `running` is, dropped, whether it waits or is due: given up, stopped or ended. */
568
+ readonly drop: (running: Running) => void
569
+ /** The element is gone: none is written. */
570
+ readonly dispose: () => void
571
+ }
572
+
573
+ /**
574
+ * The waiting Transition ends of element `id` (#508): made at its first end, so an element with none,
575
+ * nearly every one, pays nothing for them. `owners` holds the leg drawing each key.
576
+ */
577
+ const waitingEndsOf = (owners: Owners, snapshot: Snapshot, gate: FlushGate.Shape, id: string, recordFrame: (value: Values.Values) => void): WaitingEnds => {
578
+ const pending: Array<PendingEnd> = []
579
+ let disposed = false
580
+ /** Whether `key`'s leg has landed: it drew its last frame, or none draws it. */
581
+ const keyLanded = (key: string): boolean => ownerLanded(owners.get(key))
582
+ /** `end` off the list. */
583
+ const remove = (end: PendingEnd): void => {
584
+ const at = pending.indexOf(end)
585
+ if (at >= 0) pending.splice(at, 1)
586
+ }
587
+ /**
588
+ * An end written, at the flush after its keys landed: the frame its leg's write would have drawn in,
589
+ * and Motion's (`frame.update` once its animations resolve). It counts toward its landing as that leg
590
+ * did, so the landing's settle, told after the next flush, sees it (ADR-0057 Q4).
591
+ */
592
+ const write = (end: PendingEnd): void => {
593
+ if (Bool.or(disposed, end.state !== "due")) return
594
+ end.state = "written"
595
+ remove(end)
596
+ const running = end.running
597
+ const value = running.values(end.writes)
598
+ snapshot.values = { ...snapshot.values, ...value }
599
+ gate.write(id, value)
600
+ recordFrame(value)
601
+ drew(running, true, snapshot.now())
602
+ running.landing.settled()
603
+ const tell = running.names
604
+ if (Predicate.isNotUndefined(tell)) tell(undefined)
605
+ }
606
+ /** Whether a key-less end's target was interrupted: a leg it waits for given up or replaced before it landed. */
607
+ const interrupted = (end: PendingEnd): boolean => {
608
+ const legs = end.legs
609
+ if (Predicate.isUndefined(legs)) return false
610
+ return Arr.some(end.animated, (key, i) => {
611
+ const leg = legs[i]
612
+ if (Predicate.isUndefined(leg)) return false
613
+ if (leg.done) return false
614
+ return owners.get(key) !== leg
615
+ })
616
+ }
617
+ /** An end due once every key it waits for has landed, written at the next flush; dropped when its target was interrupted. */
618
+ const landOne = (end: PendingEnd): void => {
619
+ if (end.state !== "waiting") return
620
+ if (interrupted(end)) {
621
+ end.state = "dropped"
622
+ return
623
+ }
624
+ if (Bool.not(Arr.every(end.animated, keyLanded))) return
625
+ end.state = "due"
626
+ gate.afterFlush(() => write(end))
627
+ }
628
+ const dropped = (end: PendingEnd): boolean => end.state === "dropped"
629
+ const land = (): void => {
630
+ Arr.forEach(pending, landOne)
631
+ if (Arr.some(pending, dropped)) {
632
+ const kept = Arr.filter(pending, Predicate.not(dropped))
633
+ pending.length = 0
634
+ pending.push(...kept)
635
+ }
636
+ }
637
+ return {
638
+ add: (end) => {
639
+ pending.push(end)
640
+ land()
641
+ },
642
+ land,
643
+ drop: (running) =>
644
+ Option.match(Arr.findFirst(pending, (end) => end.running === running), {
645
+ onNone: constVoid,
646
+ onSome: (end) => {
647
+ end.state = "dropped"
648
+ remove(end)
649
+ },
650
+ }),
651
+ dispose: () => {
652
+ disposed = true
653
+ pending.length = 0
654
+ },
655
+ }
656
+ }
657
+
658
+ /** A leg's last frame lands the Transition ends waiting on it (#508); an element with none has nothing to ask. */
659
+ const landEndsOf = (waiting: WaitingEnds | undefined): void => {
660
+ if (Predicate.isNotUndefined(waiting)) waiting.land()
661
+ }
662
+
663
+ /** No values: what a spine's Retarget keys are before its first. */
664
+ export const NO_VALUES: Values.Values = {}
665
+
666
+ /**
667
+ * Whether a change's starts, targets or Keyframes stops hold a Variable value (#542): only then can
668
+ * the element's Key rule, its Variable values (#55), take a pair, so only then is a leg's machine
669
+ * built under it. It declines every pair with no `var()` at either end.
670
+ */
671
+ export const holdsVariable = (variables: VariableValues.Shape, from: Values.Values, to: Values.Values, stops: RetargetLegs.StopsByKey | undefined): boolean => {
672
+ // Per Retarget (#460): statements, Effect's calls data-first; the Environment's checks, built once.
673
+ const isValue = variables.isValue
674
+ if (Rec.some(from, isValue)) return true
675
+ if (Rec.some(to, isValue)) return true
676
+ if (Predicate.isUndefined(stops)) return false
677
+ return Rec.some(stops, stopsCheckOf(variables))
678
+ }
679
+
680
+ /** Each Environment's check of a key's Keyframes stops for a Variable value (#55), built at its first. */
681
+ // Module state (#460, Q7): one check per Environment's Variable values (#672), held weakly by them.
682
+ const stopsChecks = new WeakMap<VariableValues.Shape, (stops: ReadonlyArray<number | string>) => boolean>()
683
+
684
+ /** `variables`' check of a key's Keyframes stops: built once an Environment. */
685
+ const stopsCheckOf = (variables: VariableValues.Shape): ((stops: ReadonlyArray<number | string>) => boolean) => {
686
+ const kept = stopsChecks.get(variables)
687
+ if (Predicate.isNotUndefined(kept)) return kept
688
+ const check = (stops: ReadonlyArray<number | string>): boolean => Arr.some(stops, variables.isValue)
689
+ stopsChecks.set(variables, check)
690
+ return check
691
+ }
692
+
693
+ /** A Path's turn (#438, ADR-0065): the reserved key its Environment's renderer adds onto `rotate`. */
694
+ const PATH_ROTATION = "pathRotation"
695
+
696
+ /** The turn back at 0, written once no leg draws it (#460). */
697
+ const TURNED_BACK: Values.Values = { [PATH_ROTATION]: 0 }
698
+
699
+ /**
700
+ * Each key's Leg (#325): the one that draws it, or the last one that did, landed; `undefined` once
701
+ * none does. A key's entry is cleared in place, never deleted: a Retarget that gives up and restarts
702
+ * every key would otherwise leave the Map a hole a key each time, and rehash it.
703
+ */
704
+ export type Owners = Map<string, Running | undefined>
705
+
706
+ /** A leg over the keys of `to` (#325), counting toward `landing`: the spine gives it the keys. */
707
+ export const runningOf = (to: Values.Values, resolution: Resolution, landing: Landing, kind: RetargetLegs.Leg["_tag"]): Running => ({
708
+ supersede: Supersede.make(),
709
+ targets: to,
710
+ resolution,
711
+ count: 0,
712
+ values: identity,
713
+ done: false,
714
+ losing: false,
715
+ fiber: undefined,
716
+ landing,
717
+ names: undefined,
718
+ kind,
719
+ frames: 0,
720
+ // Doubles from the start (#464): a field made an integer turns every leg's shape when its first double
721
+ // comes, and a read of each leg made before goes the slow way (the bench's unmount, +6%).
722
+ lastAt: Number.NEGATIVE_INFINITY,
723
+ last: undefined,
724
+ before: undefined,
725
+ beforeAt: Number.NEGATIVE_INFINITY,
726
+ physics: undefined,
727
+ })
728
+
729
+ /**
730
+ * A Blend leg's velocity for `key` (#464, Motion's `getVelocity`): its last two frames' change over
731
+ * their time apart, at most `MAX_VELOCITY_DELTA`; none for a string, nor for a Snap, a leg that landed
732
+ * on its first frame (a `set`, a `duration: 0`).
733
+ */
734
+ const blendVelocityOf = (running: Running, key: string): number => {
735
+ if (Bool.and(running.done, running.frames < 2)) return 0
736
+ // Per key, per Retarget: guards, nothing made.
737
+ const lastValues = running.last
738
+ const beforeValues = running.before
739
+ if (Predicate.isUndefined(lastValues)) return 0
740
+ if (Predicate.isUndefined(beforeValues)) return 0
741
+ const last = lastValues[key]
742
+ const before = beforeValues[key]
743
+ if (Bool.not(Predicate.isNumber(last))) return 0
744
+ if (Bool.not(Predicate.isNumber(before))) return 0
745
+ const apart = Math.min(running.lastAt - running.beforeAt, FrameTime.MAX_VELOCITY_DELTA)
746
+ if (apart <= 0) return 0
747
+ return (((last as number) - (before as number)) * 1000) / apart
748
+ }
749
+
750
+ /** A leg's frame drawn (#325) at `now`: its last lands the keys it draws. Per frame: plain calls. */
751
+ const drew = (running: Running, done: boolean, now: number): void => {
752
+ if (done) running.done = true
753
+ running.frames++
754
+ running.lastAt = now
755
+ running.landing.report(done)
756
+ }
757
+
758
+ /**
759
+ * A frame's values for `kept` alone (#325): a leg a later Retarget took keys from draws only the
760
+ * rest. Built once, when it gives them up; each frame copies into the one object it returns.
761
+ */
762
+ const keepingOnly = <A,>(kept: ReadonlyArray<string>): ((value: Readonly<Record<string, A>>) => Readonly<Record<string, A>>) => {
763
+ const out: Record<string, A> = {}
764
+ let frame: Readonly<Record<string, A>> = out
765
+ const copy = (key: string): void => {
766
+ out[key] = frame[key] as A
767
+ }
768
+ return (value) => {
769
+ frame = value
770
+ Arr.forEach(kept, copy)
771
+ return out
772
+ }
773
+ }
774
+
775
+ /**
776
+ * Where `axis` rests when `target` leaves it out (#574): a leg drawing it though its own Retarget
777
+ * didn't resolve it, a Path's whose target left it out too (#438) or an Imperative animation's (#433,
778
+ * whose legs resolve nothing), was taking it somewhere, and it rests there. `undefined` with none in
779
+ * flight.
780
+ */
781
+ const restOf = (owners: Owners, target: Values.Values, axis: "x" | "y"): number | string | undefined => {
782
+ if (Object.hasOwn(target, axis)) return undefined
783
+ const owner = owners.get(axis)
784
+ if (Predicate.isUndefined(owner)) return undefined
785
+ if (owner.done) return undefined
786
+ if (Object.hasOwn(owner.resolution.resolved, axis)) return undefined
787
+ return owner.targets[axis]
788
+ }
789
+
790
+ /**
791
+ * Where a Path's axes that `target` leaves out rest (#574), read before their legs give them up: a
792
+ * new Path ends them there, so a toss caught mid-air curves back to its line. `undefined` for none:
793
+ * every element's Retarget asks, nearly always with no Path in flight, so guards, nothing built.
794
+ */
795
+ export const restsOf = (owners: Owners, target: Values.Values): Values.Values | undefined => {
796
+ const x = restOf(owners, target, "x")
797
+ const y = restOf(owners, target, "y")
798
+ if (Bool.and(Predicate.isUndefined(x), Predicate.isUndefined(y))) return undefined
799
+ if (Predicate.isUndefined(x)) return { y: UndefinedOr.getOrThrow(y) }
800
+ if (Predicate.isUndefined(y)) return { x }
801
+ return { x, y }
802
+ }
803
+
804
+ /** The groups of the keys a carried leg draws (#297, #325): the first alone when the keys aren't split. */
805
+ const groupsOfLeg = (running: Running, groups: ReadonlyArray<ReadonlySet<string>> | undefined, owners: Owners): ReadonlyArray<number> => {
806
+ if (Predicate.isUndefined(groups)) return [0]
807
+ const keys = Arr.filter(Rec.keys(running.targets), (key) => owners.get(key) === running)
808
+ return Arr.filter(Arr.makeBy(groups.length, identity), (g) => Arr.some(keys, (key) => UndefinedOr.match(groups[g], { onUndefined: constFalse, onDefined: (group) => group.has(key) })))
809
+ }
810
+
811
+ /** Each entry's gate shut now (#297's PR 2): a named one whose `when` holds its keys back. */
812
+ const shutOf = (layers: ReadonlyArray<OverrideEntry>, byName: VariantTree.NameOrchestration | undefined): ReadonlyArray<boolean> | undefined => {
813
+ if (Predicate.isUndefined(byName)) return undefined
814
+ return Arr.map(layers, (layer) => {
815
+ const name = layer.name
816
+ if (Predicate.isUndefined(name)) return false
817
+ return Bool.not(byName.mayStart(name))
818
+ })
819
+ }
820
+
821
+ /** Whether any entry's gate is shut (#297's PR 2): none without a list. */
822
+ const anyShutOf = (shut: ReadonlyArray<boolean> | undefined): boolean => {
823
+ if (Predicate.isUndefined(shut)) return false
824
+ return Arr.some(shut, identity)
825
+ }
826
+
827
+ /** A split Retarget's legs, each key group's (#291, #297), and the group each leg animates. */
828
+ interface SplitLegs {
829
+ readonly legs: ReadonlyArray<RetargetLegs.Leg>
830
+ readonly tags: ReadonlyArray<number>
831
+ }
832
+
833
+ /**
834
+ * A split Retarget's legs (#291, #297): each key group on its transition, over the keys that start a
835
+ * leg (`t`, #325). A group with none of them makes no leg: a list's settles at once as Motion's empty
836
+ * variant does, unless keys it drives stay running. A list's returns' Live values follow with its
837
+ * returns' group, last; any other's with the first group.
838
+ */
839
+ const splitLegsOf = (
840
+ t: Values.Values,
841
+ from: Values.Values,
842
+ groups: ReadonlyArray<ReadonlySet<string>>,
843
+ resolution: Resolution,
844
+ listed: boolean,
845
+ transition: Config.WardicTransition | undefined,
846
+ element: Config.WardicTransition | undefined,
847
+ extraDelay: ((name: string | undefined) => number) | undefined,
848
+ reuse: (transition: Config.WardicTransition) => Config.WardicTransition,
849
+ reduce: boolean,
850
+ skipped: boolean,
851
+ positionalKeys: ReducedMotion.PositionalKeys["Service"],
852
+ defaultTransition: DefaultTransition.DefaultTransition["Service"],
853
+ velocities: RetargetLegs.Velocities,
854
+ follow: RetargetLegs.Follows | undefined,
855
+ stops: RetargetLegs.StopsByKey | undefined,
856
+ measured: RetargetLegs.MeasuredPairs | undefined,
857
+ current: Values.Values,
858
+ rests: Values.Values | undefined,
859
+ ): SplitLegs => {
860
+ let returnsAt = 0
861
+ if (listed) returnsAt = resolution.layers.length
862
+ const legs: Array<RetargetLegs.Leg> = []
863
+ const tags: Array<number> = []
864
+ Arr.forEach(groups, (_, i) => {
865
+ // A group whose keys all stay starts none (#325), as one that drives no key.
866
+ const picked = pickKeys(t, groups, i)
867
+ if (Rec.isEmptyRecord(picked)) return
868
+ let followed: RetargetLegs.Follows | undefined
869
+ if (i === returnsAt) followed = follow
870
+ const groupLegs = RetargetLegs.legsOf(from, picked, groupTransitionOf(resolution, groups, i, transition, element, extraDelay, reuse), reduce, skipped, positionalKeys, defaultTransition, velocities, followed, stops, measured, current, rests)
871
+ Arr.forEach(groupLegs, (built) => {
872
+ legs.push(built)
873
+ tags.push(i)
874
+ })
875
+ })
876
+ return { legs, tags }
877
+ }
878
+
879
+ /** What a list's names make of a Retarget (#297): their settles told, and each shut one's legs' gate. */
880
+ interface Listing {
881
+ readonly names: NameSettles | undefined
882
+ readonly legGates: ReadonlyArray<string | undefined> | undefined
883
+ }
884
+
885
+ /** What {@link listingOf} reads of a Retarget. */
886
+ interface ListingOf {
887
+ readonly listed: boolean
888
+ readonly told: ToldNames | undefined
889
+ readonly byName: VariantTree.NameOrchestration | undefined
890
+ readonly resolution: Resolution
891
+ readonly groups: ReadonlyArray<ReadonlySet<string>> | undefined
892
+ readonly legGroups: ReadonlyArray<number> | undefined
893
+ readonly legCount: number
894
+ /** For each running leg it carries (#325), the groups of the keys it draws. */
895
+ readonly carriedGroups: ReadonlyArray<ReadonlyArray<number>>
896
+ readonly shut: ReadonlyArray<boolean> | undefined
897
+ /** Write a shut group's keys where they start. */
898
+ readonly hold: (group: number) => void
899
+ readonly afterFlush: (fn: () => void) => void
900
+ readonly config: Config.SpineConfig
901
+ }
902
+
903
+ /**
904
+ * A list's names at a Retarget (#297): told settled as the legs of the keys each drives settle, to
905
+ * the binding's callbacks (Solid 1's, PR 1) and to its orchestration (PR 2), told moving now; and each
906
+ * shut name's legs waiting on its gate (PR 2), its keys held where they start, so another name's first
907
+ * commit, which hands the element's style back (ADR-0034), doesn't drop them to their own value.
908
+ */
909
+ const listingOf = (of: ListingOf): Listing => {
910
+ const { listed, told, byName, resolution, groups, legGroups, legCount, carriedGroups, shut, config } = of
911
+ const listNames = Bool.match(listed, { onTrue: () => resolution.variant as ReadonlyArray<string>, onFalse: () => NO_NAMES })
912
+ const orchestrated = Bool.and(listed, Predicate.isNotUndefined(byName))
913
+ const toldNames = UndefinedOr.match(told, { onUndefined: () => NO_NAMES, onDefined: (list) => list.names })
914
+ let names: NameSettles | undefined
915
+ if (Bool.or(orchestrated, Predicate.isNotUndefined(told))) {
916
+ if (orchestrated) (byName as VariantTree.NameOrchestration).moving(listNames)
917
+ names = nameSettlesOf(Arr.dedupe([...listNames, ...toldNames]), resolution, groups, legGroups, legCount, carriedGroups, (settled) =>
918
+ of.afterFlush(() => {
919
+ UndefinedOr.map(told, (list) => {
920
+ const mine = Arr.filter(settled, (name) => Arr.contains(list.names, name))
921
+ if (mine.length > 0) list.tell(mine, config)
922
+ })
923
+ if (orchestrated) (byName as VariantTree.NameOrchestration).settled(Arr.filter(settled, (name) => Arr.contains(listNames, name)))
924
+ }))
925
+ }
926
+ let legGates: ReadonlyArray<string | undefined> | undefined
927
+ if (Bool.and(anyShutOf(shut), Predicate.isNotUndefined(legGroups))) {
928
+ const closed = shut as ReadonlyArray<boolean>
929
+ legGates = Arr.map(legGroups as ReadonlyArray<number>, (g) => gateNameOf(resolution.layers, closed, g))
930
+ Arr.forEach(closed, (isShut, g) => {
931
+ if (isShut) of.hold(g)
932
+ })
933
+ }
934
+ return { names, legGates }
935
+ }
936
+
937
+ /** The name a leg of key group `g` waits for, if its entry's gate is shut (#297's PR 2): a list's returns wait for none. */
938
+ const gateNameOf = (layers: ReadonlyArray<OverrideEntry>, shut: ReadonlyArray<boolean>, g: number): string | undefined => {
939
+ if (shut[g] !== true) return undefined
940
+ return UndefinedOr.match(layers[g], { onUndefined: constUndefined, onDefined: (layer) => layer.name })
941
+ }
942
+
943
+ /** A gate's wait (#297's PR 2): done once `open()` says so, read each tick. */
944
+ const gateWaitOf = (open: () => boolean): Machine.Machine<Frame.Frame<undefined>> =>
945
+ Machine.make({ settles: true, span: GATE_SPAN, start: () => () => ({ value: undefined, done: open() }) })
946
+
947
+ const GATE_SPAN = { name: "wardic.spine.whenGate", attributes: {} }
948
+
949
+ /** Nothing drawn while a gate is waited on. */
950
+ const NO_SINK = (): undefined => undefined
951
+
952
+ /** Whether a key's leg has landed (#428): its owner's done, or it has none. A guard: asked at each leg's landing while a Transition end waits (#508). */
953
+ const ownerLanded = (owner: Running | undefined): boolean => {
954
+ if (Predicate.isUndefined(owner)) return true
955
+ return owner.done
956
+ }
957
+
958
+ /** Whether `runtime` keeps a Debug log: read once a runtime, so a log no level keeps forks nothing (#618). */
959
+ // Module state (#460, Q7): each runtime's answer, held weakly by the runtime.
960
+ const logsDebug = new WeakMap<WardicServices.Runner<WardicServices.WardicServices>, boolean>()
961
+ const logsDebugOn = (runtime: WardicServices.Runner<WardicServices.WardicServices>): boolean => {
962
+ const known = logsDebug.get(runtime)
963
+ if (Predicate.isNotUndefined(known)) return known
964
+ const on = runtime.runSync(Report.debugKept)
965
+ logsDebug.set(runtime, on)
966
+ return on
967
+ }
968
+
969
+ /**
970
+ * No key taken by an Imperative animation (#433): every spine's until its first, shared, so an element
971
+ * none animates holds no map of its own (#460). Never written: a spine sets keys in a map of its own,
972
+ * and deletes only from one that has some.
973
+ */
974
+ // Module state (#460, Q7): a constant: an empty map every spine shares until its first, which none writes.
975
+ const NONE_TAKEN: Map<string, number | string | undefined> = new Map()
976
+
977
+ /**
978
+ * A leg that waits for its name's gate first (#297's PR 2), as Motion runs a variant's `when` per
979
+ * name: started once the gate opens, on the same token, so a later Retarget ends the wait as it ends
980
+ * a leg. Without a name, the leg as it is.
981
+ */
982
+ const gatedBy = <R,>(
983
+ name: string | undefined,
984
+ byName: VariantTree.NameOrchestration | undefined,
985
+ options: Machine.RunOptions,
986
+ program: Effect.Effect<unknown, never, R>,
987
+ ): Effect.Effect<unknown, never, R | FrameLoop.FrameLoop> => {
988
+ if (Bool.or(Predicate.isUndefined(name), Predicate.isUndefined(byName))) return program
989
+ const orchestration = byName as VariantTree.NameOrchestration
990
+ const gated = name as string
991
+ return gateWaitOf(() => orchestration.mayStart(gated)).pipe(
992
+ Machine.run(NO_SINK, options),
993
+ Effect.flatMap((end) => Bool.match(Supersede.isSuperseded(end), { onTrue: () => Effect.succeed(end as unknown), onFalse: () => program })),
994
+ )
995
+ }
996
+
997
+ /** Whether an entry is on with its own transition: hoisted, as it's asked per Retarget. */
998
+ const hasOwnTransition = (layer: OverrideEntry): boolean => Bool.and(layer.active, Predicate.isNotUndefined(layer.transition))
999
+
1000
+ /** A target as an active entry, with the name it resolved. */
1001
+ const layerOf = (target: VariantTarget.Target, name: string | undefined): OverrideEntry => ({
1002
+ active: true,
1003
+ values: target.values,
1004
+ transition: target.transition,
1005
+ name,
1006
+ ends: endsOfTarget(target),
1007
+ keyframes: target.keyframes,
1008
+ })
1009
+
1010
+ /** A list's target as an active entry (#297). */
1011
+ const namedLayerOf = (target: VariantTarget.NamedTarget): OverrideEntry => layerOf(target, target.name)
1012
+
1013
+ /** A target's Transition end as an entry's (#428): none shared, so the common case allocates nothing. Per entry, per Retarget (#460): a guard. */
1014
+ const endsOfTarget = (target: VariantTarget.Target): Values.Values => {
1015
+ if (Predicate.isUndefined(target.transitionEnd)) return NO_VALUES
1016
+ return target.transitionEnd
1017
+ }
1018
+
1019
+ /** Whether an entry is on with a Transition end (#428). */
1020
+ const hasEnds = (layer: OverrideEntry): boolean => Bool.and(layer.active, layer.ends !== NO_VALUES)
1021
+
1022
+ /** The highest active entry that sets `key`, in its values or its Transition end (#428). */
1023
+ const driverOf = (layers: ReadonlyArray<OverrideEntry>, key: string): number =>
1024
+ Option.getOrElse(Arr.findLastIndex(layers, (layer) => Bool.and(layer.active, Bool.or(Object.hasOwn(layer.values, key), Object.hasOwn(layer.ends, key)))), () => -1)
1025
+
1026
+ /**
1027
+ * The Override stack resolved (#428): `Override.resolve` as before when no active entry has a
1028
+ * Transition end; else over each entry's values and Transition end, its values winning a key both set, so
1029
+ * a key only an end sets is the entry's (Motion's `{ ...target, ...transitionEnd }`), and the ends
1030
+ * each entry drives.
1031
+ */
1032
+ const resolvedOf = (layers: ReadonlyArray<OverrideEntry>): Resolved => {
1033
+ if (!Arr.some(layers, hasEnds)) {
1034
+ const resolved = Override.resolve(layers)
1035
+ return { resolved, ends: undefined, keyframes: keyframesNowOf(layers, resolved) }
1036
+ }
1037
+ const merged = Arr.map(layers, (layer): OverrideEntry => Bool.match(hasEnds(layer), { onTrue: () => ({ ...layer, values: { ...layer.ends, ...layer.values } }), onFalse: () => layer }))
1038
+ const resolved = Override.resolve(merged)
1039
+ const endOnly = new Map<string, number>()
1040
+ const byLayer: Array<Record<string, number | string> | undefined> = Arr.makeBy(layers.length, constUndefined)
1041
+ Arr.forEach(Rec.keys(resolved), (key) => {
1042
+ const at = driverOf(layers, key)
1043
+ const layer = layers[at]
1044
+ if (Bool.or(Predicate.isUndefined(layer), Bool.not(Object.hasOwn((layer as OverrideEntry).ends, key)))) return
1045
+ const driving = layer as OverrideEntry
1046
+ if (Bool.not(Object.hasOwn(driving.values, key))) endOnly.set(key, at)
1047
+ const into = UndefinedOr.match(byLayer[at], { onUndefined: (): Record<string, number | string> => ({}), onDefined: identity })
1048
+ into[key] = driving.ends[key] as number | string
1049
+ byLayer[at] = into
1050
+ })
1051
+ return { resolved, ends: { endOnly, byLayer }, keyframes: keyframesNowOf(layers, resolved) }
1052
+ }
1053
+
1054
+ /** The Override stack resolved: each key's value, its entries' Transition ends (#428) and Keyframes (#429). */
1055
+ interface Resolved {
1056
+ readonly resolved: Values.Values
1057
+ readonly ends: Ends | undefined
1058
+ readonly keyframes: KeyframesNow | undefined
1059
+ }
1060
+
1061
+ /** Whether an entry is on with Keyframes (#429). Per entry, per Retarget (#452): guards, nothing built. */
1062
+ const hasKeyframes = (layer: OverrideEntry): boolean => {
1063
+ if (Predicate.isUndefined(layer.keyframes)) return false
1064
+ return layer.active
1065
+ }
1066
+
1067
+ /**
1068
+ * Each resolved key's Keyframes (#429): the stops of the entry that drives it, when that entry gives
1069
+ * it Keyframes. `undefined`, with nothing made, when no active entry has any: every element's common
1070
+ * case.
1071
+ */
1072
+ const keyframesNowOf = (layers: ReadonlyArray<OverrideEntry>, resolved: Values.Values): KeyframesNow | undefined => {
1073
+ if (!Arr.some(layers, hasKeyframes)) return undefined
1074
+ const now: Record<string, KeyframesAt> = {}
1075
+ Arr.forEach(Rec.keys(resolved), (key) => {
1076
+ const at = driverOf(layers, key)
1077
+ const layer = layers[at]
1078
+ if (Predicate.isUndefined(layer)) return
1079
+ const stops = UndefinedOr.map((layer as OverrideEntry).keyframes, (byKey) => byKey[key])
1080
+ if (Bool.or(Predicate.isUndefined(stops), Bool.not(Object.hasOwn((layer as OverrideEntry).values, key)))) return
1081
+ now[key] = { stops: stops as Stops.Stops, layer: at, name: (layer as OverrideEntry).name }
1082
+ })
1083
+ return Bool.match(Rec.isEmptyRecord(now), { onTrue: constUndefined, onFalse: (): KeyframesNow => now })
1084
+ }
1085
+
1086
+ /** Two values maps with the same keys, each holding the same value. Built once, at module load. */
1087
+ const sameValues: Equivalence.Equivalence<Values.Values> = Rec.makeEquivalence(Equivalence.strictEqual<number | string>())
1088
+
1089
+ /**
1090
+ * Whether two resolutions are the same target (#209, #470): the same values for the same keys, in
1091
+ * the base entry and resolved, the same drag, the same variant name, Keyframes and Transition ends,
1092
+ * and the same gesture layers on, with the same names. Motion's rule: a config that resolves to the
1093
+ * same values doesn't animate (a `transition` change applies from the next change), and a new
1094
+ * variant name does, even to the same values, as a gesture turning on or off does. Both bindings'
1095
+ * target memos compare with it, so a `style`, `transition` or callback change doesn't Retarget.
1096
+ */
1097
+ export const sameResolution = (a: Resolution, b: Resolution): boolean =>
1098
+ a.dragging === b.dragging && VariantTarget.sameLabels(a.variant, b.variant) && a.change === b.change && sameValues(a.resolved, b.resolved) && sameValues(a.base, b.base) &&
1099
+ sameKeyframesNow(a.keyframes, b.keyframes) && sameLayersOn(a.layersOn, b.layersOn) && sameNamesOn(a.names, b.names) && sameEnds(a.ends, b.ends)
1100
+
1101
+ /** Two resolutions' gesture layers on that set values (#470): none on both, the common case, at once. */
1102
+ const sameLayersOn = (a: VariantTree.GestureStates, b: VariantTree.GestureStates): boolean => {
1103
+ if (a === b) return true
1104
+ return a.inView === b.inView && a.focused === b.focused && a.hovered === b.hovered && a.pressed === b.pressed && a.dragged === b.dragged
1105
+ }
1106
+
1107
+ /** Two resolutions' active gesture names (#470): a named entry turning on or off, or a new name. None on both, the common case, at once. */
1108
+ const sameNamesOn = (a: VariantTree.GestureNames, b: VariantTree.GestureNames): boolean => {
1109
+ if (a === b) return true
1110
+ return VariantTree.sameGestureNames(a, b)
1111
+ }
1112
+
1113
+ /**
1114
+ * Two resolutions' Transition ends the same (#470), entry by entry: a key an entry both animates and
1115
+ * ends resolves to its value, so its end is compared here. `undefined` on both, the common case, at once.
1116
+ */
1117
+ const sameEnds = (a: Ends | undefined, b: Ends | undefined): boolean => {
1118
+ if (a === b) return true
1119
+ if (Predicate.isUndefined(a)) return false
1120
+ if (Predicate.isUndefined(b)) return false
1121
+ const y = b.byLayer
1122
+ if (a.byLayer.length !== y.length) return false
1123
+ return Arr.every(a.byLayer, (ends, i) => sameEndsAt(ends, y[i]))
1124
+ }
1125
+
1126
+ /** The value `key`'s Transition end sets it to in `ends` (#470): its driving entry's, the one entry that ends it. */
1127
+ const endFor = (ends: Ends | undefined, key: string): number | string | undefined => {
1128
+ if (Predicate.isUndefined(ends)) return undefined
1129
+ return Option.match(Arr.findFirst(ends.byLayer, (values) => endsKey(values, key)), { onNone: constUndefined, onSome: (values) => (values as Values.Values)[key] })
1130
+ }
1131
+
1132
+ /** Whether an entry's Transition end sets `key`. */
1133
+ const endsKey = (values: Values.Values | undefined, key: string): boolean => {
1134
+ if (Predicate.isUndefined(values)) return false
1135
+ return Object.hasOwn(values, key)
1136
+ }
1137
+
1138
+ /**
1139
+ * Whether `key`'s Transition end changed since the last Retarget (#470): Motion compares a target's
1140
+ * `transitionEnd` with its values, so a new end animates its key again. None on either, the common
1141
+ * case, at once.
1142
+ */
1143
+ const endMoved = (last: Resolution | undefined, now: Resolution, key: string): boolean => {
1144
+ if (Predicate.isUndefined(last)) return false
1145
+ if (last.ends === now.ends) return false
1146
+ return endFor(last.ends, key) !== endFor(now.ends, key)
1147
+ }
1148
+
1149
+ /** An entry's Transition end the same in two resolutions (#470): none on both, or the same values. */
1150
+ const sameEndsAt = (a: Values.Values | undefined, b: Values.Values | undefined): boolean => {
1151
+ if (a === b) return true
1152
+ if (Predicate.isUndefined(a)) return false
1153
+ if (Predicate.isUndefined(b)) return false
1154
+ return sameValues(a, b)
1155
+ }
1156
+
1157
+ /** Two lists of stops equal stop by stop (#429, Motion's `shallowCompare`). */
1158
+ const sameStops = (a: Stops.Stops, b: Stops.Stops): boolean => {
1159
+ if (a === b) return true
1160
+ if (a.length !== b.length) return false
1161
+ return Arr.every(a, (stop, i) => stop === b[i])
1162
+ }
1163
+
1164
+ /**
1165
+ * Whether a start that can't take its target's shape stays as it is (#430): it makes a Measured pair
1166
+ * with it, so its leg measures both ends rather than starting at the target.
1167
+ */
1168
+ const keepsStart = (pairs: MeasuredPairs.Shape, key: string, start: number | string | undefined, target: number | string): boolean => {
1169
+ if (Predicate.isUndefined(start)) return false
1170
+ return pairs.needs(key, start, target)
1171
+ }
1172
+
1173
+ /** The keys that may be Measured pairs (#430): those found, and each Keyframes key, its start now its first stop. */
1174
+ const measuringOf = (found: ReadonlyArray<string> | undefined, keyframes: KeyframesNow | undefined): ReadonlyArray<string> =>
1175
+ Arr.appendAll(UndefinedOr.match(found, { onUndefined: (): ReadonlyArray<string> => [], onDefined: identity }), UndefinedOr.match(keyframes, { onUndefined: (): ReadonlyArray<string> => [], onDefined: Rec.keys }))
1176
+
1177
+ /**
1178
+ * A Retarget's Measured pairs (#430): each of `keys` whose start and target are one, asked of the
1179
+ * end-of-task batch with the values the element draws now, but a key with Keyframes of more than two
1180
+ * stops (`many`, #460). `undefined` with none.
1181
+ */
1182
+ export const measuredOf = (measured: MeasuredPairs.Shape, element: Subject.Subject, keys: ReadonlyArray<string>, from: Values.Values, to: Values.Values, values: Values.Values, many: RetargetLegs.StopsByKey | undefined): RetargetLegs.MeasuredPairs | undefined => {
1183
+ const pairs: Record<string, { readonly from: number | string; readonly to: number | string }> = {}
1184
+ Arr.forEach(keys, (key) => {
1185
+ if (RetargetLegs.hasManyStops(many, key)) return
1186
+ const start = from[key]
1187
+ const target = to[key]
1188
+ if (Bool.or(Predicate.isUndefined(start), Predicate.isUndefined(target))) return
1189
+ if (measured.needs(key, start as number | string, target as number | string)) pairs[key] = { from: start as number | string, to: target as number | string }
1190
+ })
1191
+ if (Rec.isEmptyRecord(pairs)) return undefined
1192
+ return measured.measure(element, pairs, values)
1193
+ }
1194
+
1195
+ /** A key's Keyframes in `keyframes` (#429): per key, per Retarget, so a guard, nothing made. */
1196
+ const keyframesAtOf = (keyframes: KeyframesNow | undefined, key: string): KeyframesAt | undefined => {
1197
+ if (Predicate.isUndefined(keyframes)) return undefined
1198
+ return keyframes[key]
1199
+ }
1200
+
1201
+ /** Whether a key's Keyframes are the same (#429, {@link KeyframesAt}): its stops, its entry and that entry's name. */
1202
+ export const sameKeyframesAt = (a: KeyframesAt | undefined, b: KeyframesAt | undefined): boolean => {
1203
+ // Per key, per Retarget (#452): guards, the common case (neither) first.
1204
+ if (a === b) return true
1205
+ if (Predicate.isUndefined(a)) return false
1206
+ if (Predicate.isUndefined(b)) return false
1207
+ return Bool.and(Bool.and(a.layer === b.layer, a.name === b.name), sameStops(a.stops, b.stops))
1208
+ }
1209
+
1210
+ /** Whether two resolutions' Keyframes are the same, key by key (#429): `undefined` on both, the common case, at once. */
1211
+ const sameKeyframesNow = (a: KeyframesNow | undefined, b: KeyframesNow | undefined): boolean => {
1212
+ if (Bool.or(Predicate.isUndefined(a), Predicate.isUndefined(b))) return a === b
1213
+ const x = a as KeyframesNow
1214
+ const y = b as KeyframesNow
1215
+ const keys = Rec.keys(x)
1216
+ if (keys.length !== Rec.keys(y).length) return false
1217
+ return Arr.every(keys, (key) => sameKeyframesAt(x[key], y[key]))
1218
+ }
1219
+
1220
+ /** Whether `resolution` is `last` with only its `dragging` handed back (#340). */
1221
+ const handsBackOnly = (resolution: Resolution, last: Resolution | undefined): boolean =>
1222
+ UndefinedOr.match(last, { onUndefined: () => false, onDefined: (l) => sameResolution({ ...resolution, dragging: l.dragging }, l) })
1223
+
1224
+ /** Motion's `definition` of an animation (#257): a variant name, or its target values. */
1225
+ export type AnimationDefinition = Config.WardicVariantLabels | Values.Values
1226
+
1227
+ /**
1228
+ * A Retarget's `definition`, as Motion's `onAnimationStart` / `onAnimationComplete` hand it over
1229
+ * (#257): the variant name its base entry resolved, when that name differs from the last started
1230
+ * Retarget's (`previous`), else the target's values. Motion's definition is per animation type: a
1231
+ * new `animate` variant animates as its name, and a gesture turning on or off as values (its own,
1232
+ * or the keys it leaves falling back), so a variant's name is only told when the variant changed.
1233
+ */
1234
+ export const definitionOf = (resolution: Resolution, previous: Resolution | undefined): AnimationDefinition => {
1235
+ const name = resolution.variant
1236
+ // A list is told as a list (#297): a change name by name, as Motion's `checkVariantsDidChange`.
1237
+ if (Bool.and(Predicate.isNotUndefined(name), Bool.not(VariantTarget.sameLabels(name, UndefinedOr.map(previous, (p) => p.variant))))) return name as Config.WardicVariantLabels
1238
+ // A gesture's name that just came on (#291), the highest first, as Motion's names its type's.
1239
+ const before = UndefinedOr.match(previous, { onUndefined: () => VariantTree.NO_GESTURE_NAMES, onDefined: (p) => p.names })
1240
+ const started = Arr.findFirst(GESTURES_DOWN, (layer) =>
1241
+ Bool.and(Predicate.isNotUndefined(resolution.names[layer]), Bool.not(VariantTarget.sameLabels(resolution.names[layer], before[layer]))))
1242
+ return Option.match(started, { onNone: (): AnimationDefinition => resolution.resolved, onSome: (layer) => resolution.names[layer] as Config.WardicVariantLabels })
1243
+ }
1244
+
1245
+ /** The gesture layers, highest first. */
1246
+ const GESTURES_DOWN: ReadonlyArray<VariantTree.GestureLayer> = Arr.reverse(VariantTree.GESTURE_LAYERS)
1247
+
1248
+ /**
1249
+ * What a Retarget tells its binding (#257): that it started, and that its last leg settled. Each is
1250
+ * handed the Retarget's resolution, the variant name the last started Retarget resolved before it
1251
+ * (for {@link definitionOf}), and the config it read.
1252
+ */
1253
+ export interface AnimationHooks {
1254
+ /** A Retarget started its legs (the `when` gate let it); with no leg, it settles at once. */
1255
+ readonly started: (resolution: Resolution, previous: Resolution | undefined, config: Config.SpineConfig) => void
1256
+ /** That Retarget's last leg settled: not for one the next Retarget superseded, nor one a leg's failure cut off. */
1257
+ readonly settled: (resolution: Resolution, previous: Resolution | undefined, config: Config.SpineConfig) => void
1258
+ /**
1259
+ * A leg of that Retarget failed (#257 item 4): it can't land. Told once a Retarget, at once (a
1260
+ * leg that fails before it writes leaves no flush to wait for), and never before `started`; the
1261
+ * failure is logged and reported apart (ADR-0030).
1262
+ */
1263
+ readonly failed?: ((resolution: Resolution, error: unknown) => void) | undefined
1264
+ /**
1265
+ * Names of a list that settled (#297): a binding told each name's end on its own (Solid 1's
1266
+ * callbacks, Motion's `animateVariant` a name) has it, called as the legs of the keys each drives
1267
+ * settle; one with none hears the list's end through `settled` alone.
1268
+ */
1269
+ readonly namesSettled?: ((names: ReadonlyArray<string>, config: Config.SpineConfig) => void) | undefined
1270
+ }
1271
+
1272
+ /** A list a Retarget tells settled name by name (#297): its names, and what it tells. */
1273
+ interface ToldNames {
1274
+ readonly names: ReadonlyArray<string>
1275
+ readonly tell: (names: ReadonlyArray<string>, config: Config.SpineConfig) => void
1276
+ }
1277
+
1278
+ /** Whether a resolution resolved a list (#297): its base, or an active gesture's. Cheap for the common case. */
1279
+ const hasList = (resolution: Resolution): boolean => {
1280
+ if (Arr.isArray(resolution.variant)) return true
1281
+ if (resolution.names === VariantTree.NO_GESTURE_NAMES) return false
1282
+ return Arr.some(VariantTree.GESTURE_LAYERS, (layer) => Arr.isArray(resolution.names[layer]))
1283
+ }
1284
+
1285
+ /** The list a Retarget tells settled name by name (#297): when its binding is told so, and its definition is a list. */
1286
+ const namesToldOf = (animation: AnimationHooks | undefined, resolution: Resolution, previous: Resolution | undefined): ToldNames | undefined => {
1287
+ if (Predicate.isUndefined(animation)) return undefined
1288
+ const tell = animation.namesSettled
1289
+ if (Predicate.isUndefined(tell)) return undefined
1290
+ if (Bool.not(hasList(resolution))) return undefined
1291
+ const definition = definitionOf(resolution, previous)
1292
+ if (Bool.not(Arr.isArray(definition))) return undefined
1293
+ return { names: definition as ReadonlyArray<string>, tell }
1294
+ }
1295
+
1296
+ /**
1297
+ * A list's names told settled one by one (#297): what each leg's end is told to, legs started in the
1298
+ * Retarget's order, and each running leg it carries (#325), by its place in `carriedGroups`.
1299
+ */
1300
+ interface NameSettles {
1301
+ readonly leg: () => (end: unknown) => void
1302
+ readonly carried: (i: number) => (end: unknown) => void
1303
+ }
1304
+
1305
+ /**
1306
+ * A list's names, each told settled with the last leg of the keys it drives (#297): its entry's group,
1307
+ * or every leg's when the keys aren't split, the running legs the Retarget carries among them (#325).
1308
+ * A name that drives none is told at once.
1309
+ */
1310
+ const nameSettlesOf = (
1311
+ names: ReadonlyArray<string>,
1312
+ resolution: Resolution,
1313
+ groups: ReadonlyArray<ReadonlySet<string>> | undefined,
1314
+ legGroups: ReadonlyArray<number> | undefined,
1315
+ legCount: number,
1316
+ carriedGroups: ReadonlyArray<ReadonlyArray<number>>,
1317
+ tell: (names: ReadonlyArray<string>) => void,
1318
+ ): NameSettles => {
1319
+ const groupOf = (name: string): number => {
1320
+ if (Predicate.isUndefined(groups)) return 0
1321
+ return Option.getOrElse(Arr.findFirstIndex(resolution.layers, (layer) => layer.name === name), () => 0)
1322
+ }
1323
+ // The legs still running in each group.
1324
+ const left = new Map<number, number>()
1325
+ const add = (g: number): void => {
1326
+ left.set(g, Option.getOrElse(Option.fromUndefinedOr(left.get(g)), () => 0) + 1)
1327
+ }
1328
+ UndefinedOr.match(legGroups, {
1329
+ onUndefined: () => {
1330
+ if (legCount > 0) left.set(0, legCount)
1331
+ },
1332
+ onDefined: (tags) => Arr.forEach(tags, add),
1333
+ })
1334
+ Arr.forEach(carriedGroups, (gs) => Arr.forEach(gs, add))
1335
+ const running = (name: string): boolean => left.has(groupOf(name))
1336
+ let pending = Arr.filter(names, running)
1337
+ const idle = Arr.filter(names, (name) => Bool.not(running(name)))
1338
+ if (idle.length > 0) tell(idle)
1339
+ // A leg in group `g` ended: the names of that group are told once its last has.
1340
+ const endIn = (g: number): void => {
1341
+ const n = Option.getOrElse(Option.fromUndefinedOr(left.get(g)), () => 1) - 1
1342
+ if (n > 0) {
1343
+ left.set(g, n)
1344
+ return
1345
+ }
1346
+ left.delete(g)
1347
+ const done = Arr.filter(pending, (name) => groupOf(name) === g)
1348
+ pending = Arr.filter(pending, (name) => groupOf(name) !== g)
1349
+ if (done.length > 0) tell(done)
1350
+ }
1351
+ let next = 0
1352
+ return {
1353
+ leg: () => {
1354
+ const g = UndefinedOr.match(legGroups, { onUndefined: () => 0, onDefined: (tags) => Option.getOrElse(Option.fromUndefinedOr(tags[next]), () => 0) })
1355
+ next++
1356
+ return (end) => {
1357
+ // A Superseded leg (#200) settles nothing: the next Retarget's tells.
1358
+ if (Supersede.isSuperseded(end)) return
1359
+ endIn(g)
1360
+ }
1361
+ },
1362
+ carried: (i) => (end) => {
1363
+ if (Supersede.isSuperseded(end)) return
1364
+ Arr.forEach(UndefinedOr.match(carriedGroups[i], { onUndefined: (): ReadonlyArray<number> => [], onDefined: identity }), endIn)
1365
+ },
1366
+ }
1367
+ }
1368
+
1369
+ /**
1370
+ * Solid 1's animation callbacks (#257, Motion's props): each Retarget's start and settle told to the
1371
+ * config's `onAnimationStart` / `onAnimationComplete`, with its `definition`, as the Retarget read
1372
+ * the config. A callback that throws is reported, and the element animates on. The Solid 2 binding's
1373
+ * config has neither: it hands the same facts over as async values.
1374
+ */
1375
+ export const animationCallbacks = (runtime: WardicServices.Runner<WardicServices.WardicServices>, id: string): AnimationHooks => {
1376
+ // Per Retarget, per element: the callback looked up first, and nothing made without one.
1377
+ const tell = (name: "onAnimationStart" | "onAnimationComplete", callback: (definition: Config.WardicAnimationDefinition) => void, definition: Config.WardicAnimationDefinition): void => {
1378
+ try {
1379
+ callback(definition)
1380
+ } catch (defect) {
1381
+ runtime.runFork(Report.failure(`wardic.spine: ${name} failed`, Cause.die(defect)).pipe(Effect.annotateLogs({ id })))
1382
+ }
1383
+ }
1384
+ return {
1385
+ // A list starts as each of its names, in order (#297, Motion's `animateVisualElement` a name).
1386
+ started: (resolution, previous, config) => {
1387
+ const callback = config.onAnimationStart
1388
+ if (Predicate.isUndefined(callback)) return
1389
+ const definition = definitionOf(resolution, previous)
1390
+ if (Arr.isArray(definition)) {
1391
+ Arr.forEach(definition as ReadonlyArray<string>, (name) => tell("onAnimationStart", callback, name))
1392
+ return
1393
+ }
1394
+ tell("onAnimationStart", callback, definition)
1395
+ },
1396
+ // A list's names were each told as they settled (`namesSettled`).
1397
+ settled: (resolution, previous, config) => {
1398
+ const callback = config.onAnimationComplete
1399
+ if (Predicate.isUndefined(callback)) return
1400
+ const definition = definitionOf(resolution, previous)
1401
+ if (Arr.isArray(definition)) return
1402
+ tell("onAnimationComplete", callback, definition)
1403
+ },
1404
+ namesSettled: (names, config) => {
1405
+ const callback = config.onAnimationComplete
1406
+ if (Predicate.isUndefined(callback)) return
1407
+ Arr.forEach(names, (name) => tell("onAnimationComplete", callback, name))
1408
+ },
1409
+ }
1410
+ }
1411
+
1412
+ /** Which entries of the Override stack are active now, as the binding reads them. */
1413
+ export interface Active {
1414
+ /** In view (#273): `whileInView` applies. */
1415
+ readonly inView: boolean
1416
+ /** Focused, as the Environment shows it (`:focus-visible`, #273): `whileFocus` applies. */
1417
+ readonly focused: boolean
1418
+ readonly hovered: boolean
1419
+ readonly pressed: boolean
1420
+ /** A drag, or a **Keyboard reorder**'s lift (ADR-0037): `whileDrag` applies. */
1421
+ readonly dragged: boolean
1422
+ /** A drag: the translate keys are the drag's (ADR-0004). */
1423
+ readonly dragging: boolean
1424
+ }
1425
+
1426
+ /** The variant name an element animates to: its own `animate`'s, else the one its provider hands down. */
1427
+ const variantOf = (animate: Config.SpineConfig["animate"], parent: VariantTree.WardicVariantContextValue | undefined): Config.WardicVariantLabels | undefined => {
1428
+ if (Predicate.isNotUndefined(animate)) return VariantTree.nameOf(animate)
1429
+ if (Predicate.isUndefined(parent)) return undefined
1430
+ return parent.variant()
1431
+ }
1432
+
1433
+ /** The base target (ADR-0007): its own `animate`'s, else the inherited name's, else the seeded `initial`. */
1434
+ const baseTargetOf = (
1435
+ own: VariantTarget.Entry | undefined,
1436
+ variant: Config.WardicVariantLabels | undefined,
1437
+ variants: Config.WardicVariants | undefined,
1438
+ custom: unknown,
1439
+ state: VariantTarget.VariantState,
1440
+ initialLink: Values.Values,
1441
+ ): VariantTarget.Target => {
1442
+ if (Predicate.isNotUndefined(own)) return VariantTarget.resolveTarget(own, variants, custom, state)
1443
+ if (Predicate.isNotUndefined(variant)) return VariantTarget.resolveTarget(variant, variants, custom, state)
1444
+ return { values: initialLink, transition: undefined, transitionEnd: undefined, keyframes: undefined }
1445
+ }
1446
+
1447
+ /**
1448
+ * The Override stack resolved (ascending priority, Motion's `variantPriorityOrder`): base (animate, or
1449
+ * initial when no animate) -> whileInView -> whileFocus -> whileHover -> whileTap -> whileDrag (#273
1450
+ * added the first two). `Override.resolve` picks the last active entry per key. Pure:
1451
+ * a binding computes it in a memo, so a config change, an inherited variant name's
1452
+ * (`parent.variant()`, read only when there's no `animate`) or an entry's drives a Retarget.
1453
+ */
1454
+ export const resolutionOf = (
1455
+ c: Config.SpineConfig,
1456
+ parent: VariantTree.WardicVariantContextValue | undefined,
1457
+ initialLink: Values.Values,
1458
+ active: Active,
1459
+ state: VariantTarget.VariantState,
1460
+ own?: AnimationControls.ControlsChange | undefined,
1461
+ ): Resolution => {
1462
+ // The Controls change in effect (#433): its own controls', else its provider's, read here so a new one Retargets.
1463
+ const change = changeIn(own, parent)
1464
+ const variants = c.variants
1465
+ // Base target resolution priority (ADR-0007):
1466
+ // (1) local `animate` (a Values map or a variant name) — overrides any
1467
+ // inherited variant entirely;
1468
+ // (2) else an INHERITED variant name from the parent context, resolved
1469
+ // against THIS child's OWN `variants` (a child's "open" != its
1470
+ // sibling's "open"); read parent.variant() here so a parent flip
1471
+ // recomputes the memo and retargets;
1472
+ // (3) else the SSR-seeded `initial`.
1473
+ // Per Retarget, per element (#460, compose once): statements.
1474
+ const variant = variantOf(c.animate, parent)
1475
+ // A list of names (#297, Motion's `VariantLabels`): a base entry a name, in order, so the last name
1476
+ // that sets a key drives it. A single name or a values map takes the path below, as before.
1477
+ if (Arr.isArray(c.animate) || (Predicate.isUndefined(c.animate) && Arr.isArray(variant))) {
1478
+ const targets = VariantTarget.resolveTargets(variant as ReadonlyArray<string>, variants, c.custom, state)
1479
+ const merged = VariantTarget.mergedOf(targets)
1480
+ const listLayers: Array<OverrideEntry> = Arr.map(targets, namedLayerOf)
1481
+ return withGestures(c, parent, listLayers, merged.values, variant, active, merged.transition, state, change)
1482
+ }
1483
+ // A dynamic variant resolves with this element's own `custom` (#277), as Motion's each child's.
1484
+ // Animation controls never reach here: its binding reads them once, each change its entry (#433).
1485
+ const target = baseTargetOf(c.animate as VariantTarget.Entry | undefined, variant, variants, c.custom, state, initialLink)
1486
+ const base = target.values
1487
+ const baseLayer: OverrideEntry = layerOf(target, variant as string | undefined)
1488
+ // A Variant child's gestures are on while its provider's are (#291, Motion's `setActive`), each on
1489
+ // its own `while*`, else the label the provider hands down. With no provider, its own: nothing made.
1490
+ // The common case: nothing handed down and no gesture on. The base entry alone, and nothing else
1491
+ // made or called, at every element's mount and Retarget.
1492
+ if (VariantTree.handDownFrom(parent) === VariantTree.NO_HAND_DOWN && !anyOn(active)) {
1493
+ const alone: ReadonlyArray<OverrideEntry> = [baseLayer]
1494
+ const { resolved, ends, keyframes } = resolvedOf(alone)
1495
+ return { resolved, base, dragging: active.dragging, variant, active, transition: target.transition, layers: alone, names: VariantTree.NO_GESTURE_NAMES, layersOn: VariantTree.NO_GESTURE_STATES, ends, keyframes, change }
1496
+ }
1497
+ return withGestures(c, parent, [baseLayer], base, variant, active, target.transition, state, change)
1498
+ }
1499
+
1500
+ /** The **Controls change** in effect for an element (#433): its own, else its provider's; per Retarget, a guard. */
1501
+ const changeIn = (own: AnimationControls.ControlsChange | undefined, parent: VariantTree.WardicVariantContextValue | undefined): AnimationControls.ControlsChange | undefined => {
1502
+ if (Predicate.isNotUndefined(own)) return own
1503
+ if (Predicate.isUndefined(parent)) return undefined
1504
+ const inherited = parent.change
1505
+ if (Predicate.isUndefined(inherited)) return undefined
1506
+ return inherited()
1507
+ }
1508
+
1509
+ /**
1510
+ * `resolution` run on its Controls change's override (#433, Motion's `transitionOverride`): its base
1511
+ * entries' own transitions beaten by it, its gestures' kept. The first Retarget for the change only.
1512
+ */
1513
+ const overriddenOf = (resolution: Resolution, override: Config.WardicTransition): Resolution => {
1514
+ const variant = resolution.variant
1515
+ let base = 1
1516
+ if (Arr.isArray(variant)) base = variant.length
1517
+ return {
1518
+ ...resolution,
1519
+ transition: override as Config.WardicVariantTransition,
1520
+ layers: Arr.map(resolution.layers, (layer, i) => Bool.match(i < base, { onTrue: (): OverrideEntry => ({ ...layer, transition: override as Config.WardicVariantTransition }), onFalse: () => layer })),
1521
+ }
1522
+ }
1523
+
1524
+ /**
1525
+ * A resolution from its base entries (one, or one a name of a list, #297) and its gesture layers on
1526
+ * top (#291), each gesture's an entry a name too: the Override stack resolved, and the names its
1527
+ * active gestures resolved.
1528
+ */
1529
+ const withGestures = (
1530
+ c: Config.SpineConfig,
1531
+ parent: VariantTree.WardicVariantContextValue | undefined,
1532
+ layers: Array<OverrideEntry>,
1533
+ base: Values.Values,
1534
+ variant: Config.WardicVariantLabels | undefined,
1535
+ active: Active,
1536
+ transition: Config.WardicVariantTransition | undefined,
1537
+ state: VariantTarget.VariantState,
1538
+ change: AnimationControls.ControlsChange | undefined,
1539
+ ): Resolution => {
1540
+ const variants = c.variants
1541
+ const above = VariantTree.handDownFrom(parent)
1542
+ if (Bool.and(above === VariantTree.NO_HAND_DOWN, Bool.not(anyOn(active)))) {
1543
+ const { resolved, ends, keyframes } = resolvedOf(layers)
1544
+ return { resolved, base, dragging: active.dragging, variant, active, transition, layers, names: VariantTree.NO_GESTURE_NAMES, layersOn: VariantTree.NO_GESTURE_STATES, ends, keyframes, change }
1545
+ }
1546
+ const on = gesturesOnOf(active, above)
1547
+ const labels = above.names
1548
+ // In Motion's priority, lowest first: a literal's fields are evaluated in order.
1549
+ const layersOn: VariantTree.GestureStates = {
1550
+ inView: gestureLayersInto(layers, c.whileInView, on.inView, labels.inView, variants, c.custom, state),
1551
+ focused: gestureLayersInto(layers, c.whileFocus, on.focused, labels.focused, variants, c.custom, state),
1552
+ hovered: gestureLayersInto(layers, c.whileHover, on.hovered, labels.hovered, variants, c.custom, state),
1553
+ pressed: gestureLayersInto(layers, c.whileTap, on.pressed, labels.pressed, variants, c.custom, state),
1554
+ // whileDrag sits ABOVE tap (highest priority) — driven by the spring,
1555
+ // NOT stripped, so e.g. `scale: 1.1` animates while held and returns
1556
+ // after release.
1557
+ dragged: gestureLayersInto(layers, c.whileDrag, on.dragged, labels.dragged, variants, c.custom, state),
1558
+ }
1559
+ const { resolved, ends, keyframes } = resolvedOf(layers)
1560
+ const names = activeNamesFor(c, on, labels)
1561
+ return { resolved, base, dragging: active.dragging, variant, active, transition, layers, names, layersOn, ends, keyframes, change }
1562
+ }
1563
+
1564
+ /** The values an element starts from, read once at setup (ADR-0003, #134). */
1565
+ export interface Start {
1566
+ /** Its Starting style's values: its `initial` (own or inherited, #50), or its `animate` when it starts there. */
1567
+ readonly initialValues: Values.Values
1568
+ /** Its `initial` link in the Base-value chain and its fallback base entry: none when it started at `animate`. */
1569
+ readonly initialLink: Values.Values
1570
+ /** When it started at `animate`, those values, which come after `style` (Motion's `baseTarget`, ADR-0022). */
1571
+ readonly startedLink: Values.Values
1572
+ /**
1573
+ * Whether its mount tells nothing (#448, Motion's `animation-state.ts`): it starts at its `animate`
1574
+ * (`initial={false}`, or an `<AnimatePresence initial={false}>`'s first render), or its `initial` is
1575
+ * the same name, list or values map as its `animate`, each its own or inherited. Its first Retarget,
1576
+ * landing with nothing to animate, is told to no one.
1577
+ */
1578
+ readonly quiet: boolean
1579
+ }
1580
+
1581
+ /**
1582
+ * An element's {@link Start}, from its config read once and the context it inherits from. With
1583
+ * `initial={false}` (its own, inherited, or an `<AnimatePresence initial={false}>`'s first render)
1584
+ * it starts at its `animate`, and nothing animates at mount (#134).
1585
+ */
1586
+ export const startOf = (
1587
+ config: Config.SpineConfig,
1588
+ parent: VariantTree.WardicVariantContextValue | undefined,
1589
+ presenceBlocks: boolean,
1590
+ untrack: Reactivity.Reactivity["untrack"],
1591
+ ): Start => {
1592
+ const startedAtAnimate = VariantTree.startsAtAnimate(config, parent, presenceBlocks)
1593
+ const initialValues = VariantTree.startingValuesOf(config, parent, presenceBlocks, untrack)
1594
+ return {
1595
+ quiet: VariantTree.startsQuiet(config, parent, presenceBlocks, untrack),
1596
+ initialValues,
1597
+ initialLink: Bool.match(startedAtAnimate, { onTrue: () => ({}), onFalse: () => initialValues }),
1598
+ startedLink: Bool.match(startedAtAnimate, { onTrue: () => initialValues, onFalse: () => ({}) }),
1599
+ }
1600
+ }
1601
+
1602
+ /**
1603
+ * The Snapshot: each key's last emitted value, a number or a string, and the numeric velocities.
1604
+ * A Retarget starts each key from where it is, with its velocity carried across the seam (ADR-0005,
1605
+ * ADR-0024). Plain, not reactive; a drag writes its `x`/`y` into it too (ADR-0004).
1606
+ */
1607
+ export interface Snapshot {
1608
+ values: Values.Values
1609
+ /**
1610
+ * Each numeric key's velocity (#464, Motion's): a spring's own, a drag's pointer's, or, for a key a
1611
+ * leg let go, the one its last two frames gave it. Read through the spine, which takes a running
1612
+ * leg's and reads one drawn more than `MAX_VELOCITY_DELTA` ago as 0.
1613
+ */
1614
+ velocities: Record<string, number>
1615
+ /**
1616
+ * When each key's velocity here was last drawn, on {@link FrameTime.frameNow}'s clock (#464): the last frame of
1617
+ * the leg that let it go, or a drag's or a presence seed's setting.
1618
+ */
1619
+ drawnAt: Record<string, number>
1620
+ /** The leg drawing each key, its spine's (#464): a running leg's velocity is read from it. None before its spine runs. */
1621
+ owners: ReadonlyMap<string, Running | undefined> | undefined
1622
+ /** The time now, its provider's Clock's once its spine runs (#460, Q7), {@link FrameTime.frameNow} before. */
1623
+ now: () => number
1624
+ /**
1625
+ * Every numeric key's velocity now (#663), given the Snapshot: {@link velocitiesNowOf}, one function
1626
+ * every Snapshot shares. A resolver and Animation controls read these: `velocities` doesn't hold a
1627
+ * spring leg's. A method, so a Snapshot is a resolver's `VariantState`.
1628
+ */
1629
+ velocitiesNow(snapshot: Snapshot): Readonly<Record<string, number>>
1630
+ }
1631
+
1632
+ /** A Snapshot seeded from the Starting values, velocities 0, so frame 1 flows out of the seed (no snap). */
1633
+ export const snapshotOf = (start: Start): Snapshot => emptySnapshotOf({ ...start.initialValues })
1634
+
1635
+ /** A Snapshot of `values`, nothing moving: read as it is until a spine reads it. */
1636
+ export const emptySnapshotOf = (values: Values.Values): Snapshot => ({ values, velocities: {}, drawnAt: {}, owners: undefined, now: FrameTime.frameNow, velocitiesNow: velocitiesNowOf })
1637
+
1638
+ // --- Velocities (#464) ---------------------------------------------------------------------------
1639
+
1640
+ /** A leg's velocity for `key`: a Blend leg's from its frames, a Snap's none, a spring's or a follow's as it wrote it. */
1641
+ const legVelocityOf = (snapshot: Snapshot, running: Running, key: string): number => {
1642
+ if (running.kind === "Blend") return blendVelocityOf(running, key)
1643
+ if (running.kind === "Snap") return 0
1644
+ if (running.kind === "Numbers") return numbersVelocityOf(snapshot, running, key)
1645
+ return velocityOf(snapshot, key)
1646
+ }
1647
+
1648
+ /**
1649
+ * A Numbers leg's velocity for `key` (#663): its last Frame's, as it drew it, by index from a spring's
1650
+ * (whose velocity record it doesn't write), from the record of an inertia's; the Snapshot's before its
1651
+ * first frame, or for a key its Frame doesn't have. Per key, per Retarget: guards.
1652
+ */
1653
+ const numbersVelocityOf = (snapshot: Snapshot, running: Running, key: string): number => {
1654
+ const last = running.physics
1655
+ if (Predicate.isUndefined(last)) return velocityOf(snapshot, key)
1656
+ if (Frame.isSpringValues(last)) {
1657
+ const at = last.keys.indexOf(key)
1658
+ if (at < 0) return velocityOf(snapshot, key)
1659
+ return UndefinedOr.getOrThrow(last.velocities[at])
1660
+ }
1661
+ const velocity = last.velocity[key]
1662
+ if (Predicate.isUndefined(velocity)) return velocityOf(snapshot, key)
1663
+ return velocity
1664
+ }
1665
+
1666
+ /**
1667
+ * `key`'s velocity at `now` (#464, Motion's `getVelocity`): the leg drawing it, once it has drawn a
1668
+ * frame, else what the Snapshot holds for it (the last leg to let it go left it, a drag or a seed set
1669
+ * it), whichever drew it last; 0 once nothing has moved it for `MAX_VELOCITY_DELTA`. Read only for a
1670
+ * key a spring or a follow starts, or one a leg lets go: guards, nothing made.
1671
+ */
1672
+ export const velocityAt = (snapshot: Snapshot, owner: Running | undefined, key: string, now: number): number => {
1673
+ const at = snapshot.drawnAt[key]
1674
+ // Guards, not `Bool.and`, which reads both sides: a leg that hasn't drawn yet stands for nothing.
1675
+ if (Predicate.isNotUndefined(owner)) {
1676
+ if (owner.frames > 0) {
1677
+ if (Predicate.isUndefined(at) || owner.lastAt >= (at as number)) {
1678
+ if (now - owner.lastAt > FrameTime.MAX_VELOCITY_DELTA) return 0
1679
+ return legVelocityOf(snapshot, owner, key)
1680
+ }
1681
+ }
1682
+ }
1683
+ if (Predicate.isUndefined(at)) return 0
1684
+ if (now - at > FrameTime.MAX_VELOCITY_DELTA) return 0
1685
+ return velocityOf(snapshot, key)
1686
+ }
1687
+
1688
+ /**
1689
+ * `running` lets `key` go, having drawn it (#464): the velocity it gives the key now (0 once it's drawn
1690
+ * nothing for 30 ms) and its last frame's time stay on the Snapshot, as numbers. Keeping the leg itself
1691
+ * kept its Retarget's closures alive until the unmount, which paid for them. A string carries none.
1692
+ */
1693
+ const letGo = (snapshot: Snapshot, key: string, running: Running): void => {
1694
+ if (running.frames === 0) return
1695
+ if (!Predicate.isNumber(snapshot.values[key])) return
1696
+ snapshot.velocities[key] = velocityAt(snapshot, running, key, snapshot.now())
1697
+ snapshot.drawnAt[key] = running.lastAt
1698
+ }
1699
+
1700
+ /** Every numeric key's velocity now (#464): a presence's exit and takeover read it (#286). */
1701
+ export const velocitiesNowOf = (snapshot: Snapshot): Readonly<Record<string, number>> => {
1702
+ const now = snapshot.now()
1703
+ const owners = snapshot.owners
1704
+ return Rec.map(Rec.filter(snapshot.values, Predicate.isNumber), (_, key) =>
1705
+ velocityAt(snapshot, UndefinedOr.match(owners, { onUndefined: constUndefined, onDefined: (map) => map.get(key) }), key, now))
1706
+ }
1707
+
1708
+ /**
1709
+ * The transition a Retarget runs on (#66): the element's last one when the new one has the same
1710
+ * fields, so core's decode cache hits when the object is rebuilt with the same values (a staggered
1711
+ * child's, ADR-0007, or one Solid rebuilds as it reads a signal). One per element.
1712
+ */
1713
+ export const makeReuse = (): ((transition: Config.WardicTransition) => Config.WardicTransition) => {
1714
+ let lastTransition: Config.WardicTransition | undefined
1715
+ // Per Retarget (#460, compose once): statements.
1716
+ return (transition) => {
1717
+ if (Predicate.isNotUndefined(lastTransition) && sameFields(lastTransition, transition)) return lastTransition
1718
+ lastTransition = transition
1719
+ return transition
1720
+ }
1721
+ }
1722
+
1723
+ /**
1724
+ * A mounted element's Base-value links (ADR-0022), as its binding reads them: its Own value per key,
1725
+ * the links for a key's start coerced to the shape of its target (`like`), and that start.
1726
+ */
1727
+ // #672: the spine names what it calls; the binding's `startLinksOf` (`element-setup.ts`) makes them.
1728
+ export interface StartLinks {
1729
+ readonly ownValue: BaseValue.ValueLookup
1730
+ readonly linksFor: (like: number | string) => Pick<BaseValue.BaseSources, "style" | "own">
1731
+ readonly startLinkOf: (key: string, like: number | string) => Option.Option<BaseValue.BaseValue>
1732
+ }
1733
+
1734
+ /**
1735
+ * An element's presence record (ADR-0007 exit): seeded with its Starting values, so an exit that
1736
+ * fires before any frame still has a `from`, and its `exit` ref, which the ward keeps current. An exit key with no value starts
1737
+ * from its Base value's start links (ADR-0022), read from the Subject kept at the exit.
1738
+ */
1739
+ export const presenceRecordOf = <E extends Subject.Subject>(
1740
+ element: E,
1741
+ start: Start,
1742
+ exitOf: (custom: unknown, inherited: Config.WardicVariantLabels | undefined) => ExitTarget,
1743
+ links: StartLinks,
1744
+ tree: PresenceRecord.PresenceTree,
1745
+ snapshot: Snapshot,
1746
+ reducedMotion: () => boolean,
1747
+ skipAnimations: () => boolean,
1748
+ ): PresenceRecord.PresenceRecord<E> => ({
1749
+ element,
1750
+ snapshot: { current: { ...start.initialValues } },
1751
+ exitOf,
1752
+ tree,
1753
+ startOf: (key, like) => Option.getOrUndefined(Option.map(links.startLinkOf(key, like), (s) => s.value)),
1754
+ // Its spine's, read when a child back under its key takes over from it (#286): its running legs' too (#464).
1755
+ velocities: () => velocitiesNowOf(snapshot),
1756
+ // Its own, under its nearest WardicConfig (#434): its exit honours it, not the presence's.
1757
+ reducedMotion,
1758
+ // Its nearest WardicConfig's (#468): an exit is skipped as its element's animations are.
1759
+ skipAnimations,
1760
+ })
1761
+
1762
+ /**
1763
+ * Merge an emitted frame's value-map into a presence record's snapshot (nothing without one). It
1764
+ * mirrors what the gate accumulates, so an exit departs from the element's actual resting value-map.
1765
+ */
1766
+ export const recordFrameOf = (presence: PresenceRecord.PresenceRecord | undefined): ((value: Values.Values) => void) => (value) => {
1767
+ if (Predicate.isNotUndefined(presence)) Object.assign(presence.snapshot.current, value)
1768
+ }
1769
+
1770
+ /** Tell an element's Live routes the legs a Retarget starts ({@link LiveRoutes.started}): nothing for an element with none. */
1771
+ export const tellStarted = (live: LiveRoutes | undefined, legs: ReadonlyArray<RetargetLegs.Leg>): void => {
1772
+ if (Predicate.isUndefined(live)) return
1773
+ live.started(legs)
1774
+ }
1775
+
1776
+ // A Batch member's hold's slot (#665, #746; #672's Q14: the spine's, so it reads no Batch code).
1777
+ /** What a Batch member's hold reads of what its element's spine hands over (#746). */
1778
+ export type HoldHost = Pick<SpineHost, "element" | "gate" | "id" | "snapshot" | "owners" | "giveUp" | "keepTheRest" | "driven" | "returning">
1779
+
1780
+ /**
1781
+ * A Batch member's element's hold on the groups it takes from its Batch: its transform, or its opacity,
1782
+ * taken as a leg on a key of it starts or a drag moves it, and given back as its last leg on it ends, or
1783
+ * at its Batch's next change of it.
1784
+ */
1785
+ export interface MemberHold {
1786
+ /**
1787
+ * A Retarget's target `t` against the Batch (Q53): a group a key of it moves (its target other than
1788
+ * what's drawn) is taken; a key it'd leave where the Batch draws it stays the Batch's, out of `t`. A
1789
+ * drag holding `x`/`y` takes the transform.
1790
+ */
1791
+ readonly retarget: (t: Record<string, unknown>, dragged: boolean) => void
1792
+ /** A leg landed: each group no leg runs on any more goes back to the Batch (Q54), from where it is. */
1793
+ readonly settle: () => void
1794
+ /** Its drag reads or writes `x`/`y` (`true`): it takes the transform; or hands them back (`false`). */
1795
+ readonly drag: (on: boolean) => void
1796
+ /** Its element unmounted: every group back to the Batch. */
1797
+ readonly dispose: () => void
1798
+ }
1799
+
1800
+ /** How a spine finds its element a Batch member's, and makes its hold. */
1801
+ export interface MemberHolds {
1802
+ readonly isMember: (element: Subject.Subject) => boolean
1803
+ readonly make: (host: HoldHost) => MemberHold
1804
+ }
1805
+
1806
+ // Module state (#460, Q7): set once a Batch is made, so a spine can make a hold; none until then.
1807
+ let holds: MemberHolds | undefined
1808
+
1809
+ /** What a spine makes its member hold with: `undefined` while no Batch has been made. */
1810
+ export const memberHoldsNow = (): MemberHolds | undefined => holds
1811
+
1812
+ /**
1813
+ * Holds made from now on, through `holds` (`createBatch`, as it's called, gives a Batch's): a Batch's
1814
+ * members can be Wardic elements. The first one given stays.
1815
+ */
1816
+ export const provideMemberHolds = (given: MemberHolds): void => {
1817
+ if (Predicate.isNotUndefined(holds)) return
1818
+ holds = given
1819
+ }
1820
+
1821
+ /**
1822
+ * Each draggable element's spine's drag hook (#665's PR 4): told `true` as its drag reads where the
1823
+ * element rests or writes `x`/`y`, and `false` as it hands them back. A Batch member's takes its
1824
+ * transform from its Batch then, and gives it back.
1825
+ */
1826
+ // Module state (#460, Q7): held weakly by the element, so it goes with it.
1827
+ const DRAG_HOOKS = new WeakMap<Subject.Subject, (on: boolean) => void>()
1828
+
1829
+ /** `element`'s drag hook told `on`, when its spine has one: its binding's drag start and end, and a drag's claim. */
1830
+ export const tellDrag = (element: Subject.Subject, on: boolean): void => {
1831
+ UndefinedOr.map(DRAG_HOOKS.get(element), (tell) => tell(on))
1832
+ }
1833
+
1834
+ /**
1835
+ * What a spine calls of its element's Live values routed through its binding's props (#130, ADR-0043):
1836
+ * the routed keys' values now, and each one's change and removal as they come; and the legs each
1837
+ * Retarget starts, which its binding's routes may act on (`@wardic/dom`'s readies its element for them, #443).
1838
+ */
1839
+ // #672 (PR3-Q1): the spine names what it calls, so it reads no `style` code; dom's LiveStyle meets it.
1840
+ export interface LiveRoutes {
1841
+ readonly values: () => Values.Values
1842
+ readonly routes: (key: string) => boolean
1843
+ readonly valueOf: (key: string) => Option.Option<unknown>
1844
+ readonly isLive: (key: string) => boolean
1845
+ readonly atomOf: (key: string) => Atom.Atom<unknown> | undefined
1846
+ readonly started: (legs: ReadonlyArray<RetargetLegs.Leg>) => void
1847
+ readonly whenRouted: (setup: () => LiveFollower) => void
1848
+ readonly stop: () => void
1849
+ }
1850
+
1851
+ /** What a spine follows its routed keys with: each one's change, and its removal. */
1852
+ export interface LiveFollower {
1853
+ readonly change: (key: string, value: unknown) => void
1854
+ readonly removed: (key: string) => void
1855
+ }
1856
+
1857
+ /**
1858
+ * What a spine calls of its element's drag: a new target for `x` or `y` takes over a free drag's
1859
+ * release in flight (#340). Its binding's drag track gives it.
1860
+ */
1861
+ // #672 (Q15): the spine names what it calls, so it reads no drag code.
1862
+ export interface SpineDrag {
1863
+ readonly takeRelease: (retargeted: { readonly x: boolean; readonly y: boolean }) => boolean
1864
+ }
1865
+
1866
+ /** What {@link makeElementSpine} reads. */
1867
+ export interface ElementSpineOptions {
1868
+ /** The provider runtime the legs fork on. */
1869
+ readonly runtime: WardicServices.Runner<WardicServices.WardicServices>
1870
+ /** The provider-owned flush gate (ADR-0006). */
1871
+ readonly gate: FlushGate.Shape
1872
+ /** The element's gate id. */
1873
+ readonly id: string
1874
+ /** The mounted element. */
1875
+ readonly element: Subject.Subject
1876
+ /** Its tag, for a Handoff's check (its Environment routes some keys by it): `undefined` when it isn't known. */
1877
+ readonly tag: string | undefined
1878
+ /** Its config now, read where the binding doesn't track. */
1879
+ readonly config: () => Config.SpineConfig
1880
+ /** The variant context it inherits names and its default transition from (`variant-tree.ts`). */
1881
+ readonly parent: VariantTree.WardicVariantContextValue | undefined
1882
+ /** Whether a Retarget may start now (ADR-0007 `when`); omitted, always. */
1883
+ readonly canStart: (() => boolean) | undefined
1884
+ /** Its stagger delay in seconds, read at each Retarget (ADR-0007); omitted, none. */
1885
+ readonly extraDelay: ((name: string | undefined) => number) | undefined
1886
+ /** Told every frame whether it has settled (ADR-0007 orchestration). */
1887
+ readonly onFrame: ((done: boolean) => void) | undefined
1888
+ /** Whether reduced motion applies (ADR-0029), read at each Retarget. */
1889
+ readonly reducedMotion: () => boolean
1890
+ /**
1891
+ * Whether its animations are skipped (#468, its nearest `WardicConfig`'s `skipAnimations`), read at
1892
+ * each Retarget and each Imperative animation: every key lands at its end on the next tick. Omitted, never.
1893
+ */
1894
+ readonly skipAnimations?: (() => boolean) | undefined
1895
+ /** Which keys reduced motion Snaps (ADR-0036). */
1896
+ readonly positionalKeys: ReducedMotion.PositionalKeys["Service"]
1897
+ /** What a key with no transition of its own runs on (ADR-0051). */
1898
+ readonly defaultTransition: DefaultTransition.DefaultTransition["Service"]
1899
+ /** The Environment's reads of its Subjects' own values (#672), read once by its provider. */
1900
+ readonly ownValues: OwnValues.Shape
1901
+ /** The Environment's Measured pairs (#430, #672), read once by its provider. */
1902
+ readonly measuredPairs: MeasuredPairs.Shape
1903
+ /** The Environment's Variable values (#55, #672), read once by its provider. */
1904
+ readonly variableValues: VariableValues.Shape
1905
+ readonly start: Start
1906
+ readonly snapshot: Snapshot
1907
+ readonly reuse: (transition: Config.WardicTransition) => Config.WardicTransition
1908
+ readonly links: StartLinks
1909
+ /** The user's style now, read untracked: a key's `style` link (ADR-0022). */
1910
+ readonly styleNow: (() => object | string | undefined) | undefined
1911
+ /** Its routed `style` keys (#130, ADR-0043). */
1912
+ readonly live: LiveRoutes | undefined
1913
+ /**
1914
+ * Every Feature its provider has built so far, whichever section asked: where its Timeline values
1915
+ * are found (#240), once a `createScroll` has brought the `scroll` Feature. Omitted, it has none.
1916
+ */
1917
+ readonly builtFeatures?: (() => Context.Context<never>) | undefined
1918
+ /** Its presence record, under an `<AnimatePresence>`. */
1919
+ readonly presence: PresenceRecord.PresenceRecord | undefined
1920
+ /**
1921
+ * Whether a projection node owns its translate keys (ADR-0016): its drag drives its layout node. A
1922
+ * getter while its track waits for `drag` (#551, #582), so it's read where it's used.
1923
+ */
1924
+ readonly projected: boolean
1925
+ /** Its drag axis, `undefined` without a drag (ADR-0004). */
1926
+ readonly dragAxis: boolean | "x" | "y" | undefined
1927
+ /** Its drag track, whose release a Retarget may take `x`/`y` from (#340); omitted, the drag holds them while `dragging`. */
1928
+ readonly drag?: SpineDrag | undefined
1929
+ /** Its Appear animation, while hydrating (#48, ADR-0044 decision 6). */
1930
+ readonly handoff: AppearHandoff.Handoff | undefined
1931
+ /** Told each Retarget's start and settle (#257); omitted, nothing is told. */
1932
+ readonly animation?: AnimationHooks | undefined
1933
+ /**
1934
+ * A list's names orchestrated each on their own (#297's PR 2): a name's keys start once its gate
1935
+ * opens, and its starts and settles are told. Omitted for an element that joins nothing and
1936
+ * provides nothing.
1937
+ */
1938
+ readonly byName?: VariantTree.NameOrchestration | undefined
1939
+ /**
1940
+ * Development's diagnostics (#746, ADR-0067 *Amendment (#746)*, decision 6): each binding gives
1941
+ * its own under its development flag alone, so a production build ships none of their
1942
+ * code. The spine names no flag, as core, where the lift takes it (#672), has none. Omitted, nothing
1943
+ * is noted.
1944
+ */
1945
+ readonly diagnostics?: SpineDiagnostics | undefined
1946
+ }
1947
+
1948
+ /** What notes, in development, what an app may want to know but that changes nothing it draws (#746). */
1949
+ export interface SpineDiagnostics {
1950
+ /** Note, once, a Handoff whose Appear animation the server sampled from another mount animation than the client's. */
1951
+ readonly checkHandoff: (runtime: WardicServices.Runner<WardicServices.WardicServices>, id: string, handoff: AppearHandoff.Handoff, mount: AppearHandoff.MountAnimation) => void
1952
+ /** The log of a Retarget that started a key from its Base value, or returned one: run by the Retarget at its first leg. */
1953
+ readonly baseLog: (id: string, started: Record<string, string>, returns: ReadonlyArray<readonly [string, BaseValue.BaseSource]>) => Effect.Effect<void>
1954
+ }
1955
+
1956
+ /** Tell `timelineKeys` that each of `values`' keys is taken from its Live value (#240). */
1957
+ const takeEach = (timelineKeys: Timelines.TimelineKeys, values: Values.Values): void => {
1958
+ Arr.forEach(Rec.keys(values), (key) => timelineKeys.taken(key))
1959
+ }
1960
+
1961
+ /** What the follower reads of the element's Override stack and drag, untracked. */
1962
+ export interface FollowNow {
1963
+ readonly resolved: () => Values.Values
1964
+ readonly dragging: () => boolean
1965
+ }
1966
+
1967
+ /** What an **Imperative animation** tells of its legs on one element (#433). */
1968
+ export interface ImperativeHooks {
1969
+ /** Every leg it started on the element landed, told after the gate's flush of their last frames. */
1970
+ readonly settled: () => void
1971
+ /** A leg failed, reported already (ADR-0030). */
1972
+ readonly failed: (cause: Cause.Cause<unknown>) => void
1973
+ }
1974
+
1975
+ /** An **Imperative animation** on one element (#433): its legs, built at the call, run through its Playhead. */
1976
+ export interface ImperativeTrack {
1977
+ /** Run every leg from the Playhead's time: those running end first, so a seek starts them again there. */
1978
+ readonly run: () => void
1979
+ /** End every leg where it is: its keys stay there, the animation's. */
1980
+ readonly stop: () => void
1981
+ /** End every leg, and put its keys back where it started them. */
1982
+ readonly cancel: () => void
1983
+ /** How long its longest leg runs, in seconds (`Machine.durationOf`, Motion's `duration`). */
1984
+ readonly duration: () => number
1985
+ }
1986
+
1987
+ /**
1988
+ * What an element's spine hands over (#746, ADR-0067 *Amendment (#746)*): its state and its leg
1989
+ * machinery, read live, for the two that work on it from outside, `imperative.ts`, which builds an
1990
+ * **Imperative animation**'s track, and `member-hold.ts`, a Batch member's hold. An app with neither
1991
+ * ships neither's code. Made at the first call, once a spine.
1992
+ */
1993
+ export interface SpineHost {
1994
+ /** The resolution of the last Retarget, whose targets a taken key is noted with. */
1995
+ readonly lastResolution: () => Resolution | undefined
1996
+ /** The element's values, velocities and owners. */
1997
+ readonly snapshot: Snapshot
1998
+ /** Each key's running leg. */
1999
+ readonly owners: Owners
2000
+ /** Start a take: velocities read from now, and the map the keys an Imperative animation takes go in. */
2001
+ readonly taking: () => Map<string, number | string | undefined>
2002
+ /** The keys a Retarget returns, which a take stops returning. */
2003
+ readonly returning: () => Map<string, BaseValue.BaseSource>
2004
+ /** The keys a Retarget drove, each with its last target value. */
2005
+ readonly driven: Map<string, number | string>
2006
+ /** Its Timeline values, told of each key a take draws (#240). */
2007
+ readonly timelineKeys: () => Timelines.TimelineKeys | undefined
2008
+ /** Take `key` from `running`. */
2009
+ readonly giveUp: (key: string, running: Running) => void
2010
+ /** Its `initial` values: a key without one is owned when it's first drawn. */
2011
+ readonly initialValues: Values.Values
2012
+ /** Own `key` on the element (its style's value gives way). */
2013
+ readonly ownValue: (key: string) => void
2014
+ /** Start `key` where it's drawn, noting what it starts from in `started`. */
2015
+ readonly startKey: (key: string, like: number | string, started: Record<string, string>) => void
2016
+ /** Keep every key no leg takes where it's drawn. */
2017
+ readonly keepTheRest: () => void
2018
+ /** Whether reduced motion applies now. */
2019
+ readonly reducedMotion: () => boolean
2020
+ /** Whether its animations are skipped now (#468). */
2021
+ readonly skipAnimations: () => boolean
2022
+ readonly element: Subject.Subject
2023
+ readonly positionalKeys: ReducedMotion.PositionalKeys["Service"]
2024
+ readonly defaultTransition: DefaultTransition.DefaultTransition["Service"]
2025
+ /** Each key's velocity, as of the take. */
2026
+ readonly readVelocity: RetargetLegs.Velocities
2027
+ readonly gate: FlushGate.Shape
2028
+ /** A leg's keys drawn by none. */
2029
+ readonly forget: (running: Running) => void
2030
+ /** End a leg where it is. */
2031
+ readonly endLeg: (running: Running) => void
2032
+ /** Its routed `style` keys (#130), told the legs each Retarget starts. */
2033
+ readonly live: LiveRoutes | undefined
2034
+ /** A leg's keys owned by it. */
2035
+ readonly own: (running: Running) => void
2036
+ /** A leg's program: its machine's run into the gate. */
2037
+ readonly legProgram: (leg: RetargetLegs.Leg, running: Running, variables: boolean) => Effect.Effect<unknown, never, WardicServices.WardicServices>
2038
+ /** What a leg's end is told: it settles its landing, or reports its failure. */
2039
+ readonly legEnded: (running: Running) => (exit: Exit.Exit<unknown>) => Effect.Effect<void>
2040
+ /** A Path's turn back to 0 once no leg draws it (#460, ADR-0065 decision 3). */
2041
+ readonly turnBack: () => void
2042
+ /** Its gate id. */
2043
+ readonly id: string
2044
+ /** Record a value written, for its presence record. */
2045
+ readonly recordFrame: (value: Values.Values) => void
2046
+ readonly runtime: WardicServices.Runner<WardicServices.WardicServices>
2047
+ /** Its Variable values' Key rule (#55): a blend's are built with it. */
2048
+ readonly elementRules: ReadonlyArray<InterpolatorRegistry.KeyRule>
2049
+ /** The Environment's Measured pairs (#430, #672). */
2050
+ readonly measuredPairs: MeasuredPairs.Shape
2051
+ /** The Environment's Variable values (#55, #672). */
2052
+ readonly variableValues: VariableValues.Shape
2053
+ }
2054
+
2055
+ /** A mounted element's spine. */
2056
+ export interface ElementSpine {
2057
+ /** A Retarget toward `resolution`: called by the binding on each change of its target, untracked. */
2058
+ readonly retarget: (resolution: Resolution) => void
2059
+ /** Follow the element's Live values in `style` (#130), from its first routed key on. */
2060
+ readonly follow: (now: FollowNow) => void
2061
+ /** The element's teardown: following stops, and the legs end. */
2062
+ readonly dispose: () => void
2063
+ /**
2064
+ * Start where a leaver is drawn (#286, ADR-0048), before the first Retarget: each key's value and
2065
+ * velocity, drawn now. A key no entry sets returns to its Base value from there, as one a Retarget
2066
+ * drove does.
2067
+ */
2068
+ readonly seed: (from: PresenceRecord.PresenceSeed) => void
2069
+ /**
2070
+ * What the spine hands over (#746): to an **Imperative animation** of the element (#433), whose track
2071
+ * `imperative.ts` builds over it, and to a Batch member's hold (#665). Made at the first call, once.
2072
+ */
2073
+ readonly host: () => SpineHost
2074
+ /** End every running leg where it is (#433, **Animation controls**' `stop`): its keys stay there, until the next Retarget. */
2075
+ readonly stop: () => void
2076
+ }
2077
+
2078
+ /**
2079
+ * A mounted element's spine: its Retarget, the returns to its Base values, the follower of its
2080
+ * Live values, and its legs' lifetime. Every leg is a fiber of its provider's runtime, and joins
2081
+ * its Retarget's token: a Retarget ends the token before it starts its own legs, and {@link
2082
+ * ElementSpine.dispose} ends every leg's (#542). Both end the legs in the calling task: each leg's
2083
+ * run leaves the loop at once, and its fiber ends Superseded, inline (ADR-0027, decision 5,
2084
+ * *Amendment (#200)*). A leg the token didn't reach is interrupted (`endLeg`). The runtime's own
2085
+ * fiber Scope interrupts what's left when the provider ends.
2086
+ */
2087
+ export const makeElementSpine = (options: ElementSpineOptions): ElementSpine => {
2088
+ const { animation, byName, canStart, config, defaultTransition, diagnostics, element, extraDelay, gate, id, links, live, measuredPairs, onFrame, ownValues, parent, positionalKeys, presence, runtime, snapshot, start, styleNow, tag, variableValues } = options
2089
+ const { initialLink, initialValues, startedLink } = start
2090
+ const { linksFor, ownValue, startLinkOf } = links
2091
+ let handoff = options.handoff
2092
+ // Its mount tells nothing when it starts at its `animate` (#448): on until its first Retarget.
2093
+ let quiet = start.quiet
2094
+ // Its Variable values (#55, ADR-0035 *Amendment (#55)*): the Key rule bound to this element,
2095
+ // added to each leg it starts, so a `var()` end blends what it resolves to here.
2096
+ const elementRules = [variableValues.values(element)]
2097
+ const recordFrame = recordFrameOf(presence)
2098
+ // Whether its animations are skipped (#468): never, with nothing given.
2099
+ const skipAnimations = UndefinedOr.match(options.skipAnimations, { onUndefined: () => constFalse, onDefined: identity })
2100
+
2101
+ // A routed key a return handed back: written by the follower from now on (#130). Set by
2102
+ // `follow`; a return settles a tick after it runs at the earliest.
2103
+ let handBack: (key: string) => void = constVoid
2104
+
2105
+ // Its Timeline values (#240, ADR-0043 *Amendment (#240)*): the `scroll` Feature's, made at the first
2106
+ // write of a Live value once the provider has built it, and told of every key the follower writes
2107
+ // and every key anything else takes. `featuresSeen` is the built Features last looked in.
2108
+ let timelineKeys: Timelines.TimelineKeys | undefined
2109
+ let featuresSeen: Context.Context<never> | undefined
2110
+ /** Its Timeline values, made once they're there. Per write of a Live value: statements. */
2111
+ const timelineKeysNow = (routes: LiveRoutes): Timelines.TimelineKeys | undefined => {
2112
+ if (Predicate.isNotUndefined(timelineKeys)) return timelineKeys
2113
+ if (Predicate.isUndefined(options.builtFeatures)) return undefined
2114
+ const services = options.builtFeatures()
2115
+ if (services === featuresSeen) return undefined
2116
+ featuresSeen = services
2117
+ const timelines = Context.getOrUndefined(services as Context.Context<Timelines.Timelines>, Timelines.Timelines)
2118
+ if (Predicate.isUndefined(timelines)) return undefined
2119
+ timelineKeys = timelines.keysOf({ runtime, gate, id, element, live: routes })
2120
+ return timelineKeys
2121
+ }
2122
+
2123
+ // The keys a Retarget drove, each with its last target value (its shape), and the
2124
+ // ones returning to their Base value until that return settles (ADR-0022). Both are
2125
+ // the spine's: a Retarget mid-return carries them again, so a return is never
2126
+ // frozen half-way, and a key that settled has left them, so a Retarget of the same
2127
+ // target (a `when` gate reopening, ADR-0007) leaves it be. On a drag element, the keys
2128
+ // the drag moves leave the return while it runs, so they stay where it dropped them (C9)
2129
+ // until an entry sets them again; a projected element's drag moves none, its projection
2130
+ // target does (ADR-0016), and its own translate returns as any key does (#363).
2131
+ const driven = new Map<string, number | string>()
2132
+ let returning = new Map<string, BaseValue.BaseSource>()
2133
+ // Read as a drag holds them: `projected` is a getter while the track waits for `drag` (#551), whose
2134
+ // track may drive a layout node that arrived with it (#582).
2135
+ const dragMoves = (): ReadonlyArray<string> => {
2136
+ if (options.projected) return NO_KEYS
2137
+ return UndefinedOr.match(options.dragAxis, { onUndefined: () => NO_KEYS, onDefined: dragMovesOf })
2138
+ }
2139
+
2140
+ // A Retarget's returns have settled (ADR-0022, D4). A key back at its `style` value is
2141
+ // handed back to the element's style, so a later style change shows at rest and the
2142
+ // next gesture starts from it; any other key rests at its Base value where the gate drew
2143
+ // it, and leaves the target. A key a later Retarget took over is left alone. A routed key (#130) stays
2144
+ // in the gate, handed to the follower, which writes its value from now on.
2145
+ const settleReturns = (returns: ReadonlyArray<readonly [string, BaseValue.BaseSource]>): void => {
2146
+ // The returns still this Retarget's: a later one took over the rest.
2147
+ const settled = Arr.filter(returns, ([key, source]) => returning.get(key) === source)
2148
+ Arr.forEach(settled, ([key]) => {
2149
+ returning.delete(key)
2150
+ driven.delete(key)
2151
+ owners.set(key, undefined)
2152
+ })
2153
+ const toStyle = Arr.map(Arr.filter(settled, ([, source]) => source === "style"), ([key]) => key)
2154
+ const routedNow = (key: string): boolean => UndefinedOr.match(live, { onUndefined: constFalse, onDefined: (routes) => routes.routes(key) })
2155
+ Arr.forEach(Arr.filter(toStyle, routedNow), (key) => handBack(key))
2156
+ const handedBack = Arr.filter(toStyle, Predicate.not(routedNow))
2157
+ if (Arr.isReadonlyArrayEmpty(handedBack)) return
2158
+ // The gate writes the user's current value back, as the element's `style` would
2159
+ // (ADR-0034). A key gone from the user's style by now is cleared, not restored stale.
2160
+ const restore = UndefinedOr.map(styleNow, (now) => {
2161
+ const style = now()
2162
+ return Object.fromEntries(
2163
+ Arr.map(handedBack, (key) => [key, Option.match(ownValues.styleValueOf(style, key), { onNone: () => "", onSome: (value) => String(value) })]),
2164
+ ) as Record<string, string>
2165
+ })
2166
+ gate.release(id, handedBack, restore)
2167
+ Arr.forEach(handedBack, (key) => {
2168
+ delete snapshot.values[key]
2169
+ delete snapshot.velocities[key]
2170
+ if (Predicate.isNotUndefined(presence)) delete presence.snapshot.current[key]
2171
+ })
2172
+ }
2173
+
2174
+ // Each key's leg (#325, Motion's per-key rule): the running leg that draws it, or the last one that
2175
+ // did, landed. A Retarget leaves a key its running leg when it resolves it to the same target, starts
2176
+ // none for a key whose last leg landed there, and starts every other key afresh. Each leg has its
2177
+ // own token (#200, ADR-0027 *Amendment (#200)*), ended once it has no key left: Superseded, not
2178
+ // interrupted, so off the loop at once and its fiber ended normally, at about a sixth of an
2179
+ // interrupt's cost.
2180
+ const owners: Owners = new Map()
2181
+ // The keys an Imperative animation took (#433), each with the target the Override stack had for it
2182
+ // then: a Retarget leaves each where the animation leaves it while its target is still that one, and
2183
+ // takes it back once it isn't, as a newer animation of Motion's value takes it (latest-wins).
2184
+ // Every element reads it, nearly none sets it (#460): the shared empty one until the first key taken.
2185
+ let taken: Map<string, number | string | undefined> = NONE_TAKEN
2186
+ // The legs that gave up a key in this Retarget: what each still draws is worked out at its end.
2187
+ const losing: Array<Running> = []
2188
+ // The landing every running leg counts toward: the last Retarget's.
2189
+ let current: Landing | undefined
2190
+ // A gated Retarget's (ADR-0007 `when`, #325): made at the first.
2191
+ let gated: Landing | undefined
2192
+ // The variant name the last started Retarget resolved, for its successor's `definition` (#257).
2193
+ let lastResolution: Resolution | undefined
2194
+ // The Controls change (#433) it last joined, whether it's still counted there (until a landing),
2195
+ // and the one its last started Retarget ran for: only the first runs on its override.
2196
+ let joined: AnimationControls.ControlsChange | undefined
2197
+ let counted = false
2198
+ let startedChange: AnimationControls.ControlsChange | undefined
2199
+ /** Its Retargets' change is `change` now: it leaves the last, and joins this one, held or not. */
2200
+ const joinChange = (change: AnimationControls.ControlsChange | undefined): void => {
2201
+ if (counted) AnimationControls.leave(joined as AnimationControls.ControlsChange)
2202
+ joined = change
2203
+ counted = Predicate.isNotUndefined(change)
2204
+ if (counted) AnimationControls.join(change as AnimationControls.ControlsChange)
2205
+ }
2206
+ /** It landed, or can't (a leg failed, its unmount): it leaves its change. */
2207
+ const leaveChange = (): void => {
2208
+ if (!counted) return
2209
+ counted = false
2210
+ AnimationControls.leave(joined as AnimationControls.ControlsChange)
2211
+ }
2212
+ /** It landed: it leaves its change once the gate has flushed its last frame, unless it joined another meanwhile. */
2213
+ const leaveAfterFlush = (): void => {
2214
+ if (!counted) return
2215
+ const change = joined
2216
+ gate.afterFlush(() => {
2217
+ if (joined === change) leaveChange()
2218
+ })
2219
+ }
2220
+
2221
+ // The element's waiting Transition ends (#508), made at its first: most elements never have one.
2222
+ let waiting: WaitingEnds | undefined
2223
+
2224
+ // A leg with no key left ends. Its fiber ends inline (ADR-0027, *Amendment (#200)*); one its token
2225
+ // didn't reach, none of its runs on the loop, is interrupted. A Transition end it is (#508) is
2226
+ // dropped, written never, as its leg was.
2227
+ const endLeg = (running: Running): void => {
2228
+ Supersede.end(running.supersede)
2229
+ if (Predicate.isNotUndefined(waiting)) waiting.drop(running)
2230
+ const fiber = running.fiber
2231
+ if (Predicate.isUndefined(fiber)) return
2232
+ if (Predicate.isNotUndefined(fiber.pollUnsafe())) return
2233
+ // Interrupted here, nothing waiting on its end, as `runCallback`'s interruptor does: a forked
2234
+ // `Fiber.interrupt` was a fiber of its own per ended leg (#618, L2).
2235
+ fiber.interruptUnsafe()
2236
+ }
2237
+
2238
+ // A leg takes its keys (#325): each key's owner from now on. One callback a spine, not one a leg.
2239
+ let owning: Running | undefined
2240
+ const ownKey = (key: string): void => {
2241
+ owners.set(key, owning)
2242
+ }
2243
+ const own = (running: Running): void => {
2244
+ const keys = Rec.keys(running.targets)
2245
+ running.count = keys.length
2246
+ owning = running
2247
+ Arr.forEach(keys, ownKey)
2248
+ }
2249
+
2250
+ // The legs drawing each key: a running leg's velocity is read from it (#464).
2251
+ snapshot.owners = owners
2252
+ // Its time, its provider's Clock's (#460, Q7).
2253
+ snapshot.now = FrameTime.clockNowOf(runtime)
2254
+ // Each key's velocity, at the time the Retarget or Imperative animation reading it read (#464).
2255
+ let readAt = 0
2256
+ const readVelocity: RetargetLegs.Velocities = (key) => velocityAt(snapshot, owners.get(key), key, readAt)
2257
+
2258
+ // `key`'s leg gives it up: a leg ends with its last key, and draws only the rest before.
2259
+ const giveUp = (key: string, running: Running): void => {
2260
+ letGo(snapshot, key, running)
2261
+ owners.set(key, undefined)
2262
+ if (running.done) return
2263
+ running.count--
2264
+ if (running.count === 0) return endLeg(running)
2265
+ if (running.losing) return
2266
+ running.losing = true
2267
+ losing.push(running)
2268
+ }
2269
+
2270
+ // The keys the Retarget being worked out resolves, for `giveUpUnresolved`: one callback a spine,
2271
+ // not one a Retarget.
2272
+ let resolvedNow: Values.Values = NO_VALUES
2273
+ // Whether `running` is whole: it still draws every key it was started for, each held now, resolved
2274
+ // by the Retarget being worked out or taken by its Imperative animation. A key its Retarget didn't
2275
+ // resolve, a Path's turn or the axis its target leaves out (#438), is the leg's own: not counted.
2276
+ const holdsWhole = (running: Running): boolean =>
2277
+ Arr.every(Rec.keys(running.targets), (key) => {
2278
+ if (taken.has(key)) return owners.get(key) === running
2279
+ if (Bool.not(Object.hasOwn(running.resolution.resolved, key))) return true
2280
+ return Bool.and(owners.get(key) === running, Object.hasOwn(resolvedNow, key))
2281
+ })
2282
+ const giveUpUnresolved = (owner: Running | undefined, key: string): void => {
2283
+ if (Predicate.isUndefined(owner)) return
2284
+ // An Imperative animation's key (#433) is its own while taken.
2285
+ if (taken.has(key)) return
2286
+ if (Object.hasOwn(resolvedNow, key)) return
2287
+ if (Object.hasOwn(owner.resolution.resolved, key)) return giveUp(key, owner)
2288
+ // A key its leg draws though its own Retarget didn't resolve it rides on with that leg while the
2289
+ // leg is whole (#460, ADR-0065): a Retarget of another key leaves a Path as it was. Once the leg
2290
+ // loses a key, its turn goes back to 0 (`turnBack`) and an axis its target left out stays.
2291
+ if (holdsWhole(owner)) return
2292
+ giveUp(key, owner)
2293
+ }
2294
+
2295
+ // A Path's turn goes back to 0 once no leg draws it (#460, ADR-0065 decision 3): after a Retarget
2296
+ // whose legs don't turn, a stop, a cancel. Most elements never turn: a guard.
2297
+ const turnBack = (): void => {
2298
+ const turn = snapshot.values[PATH_ROTATION]
2299
+ if (Bool.or(Predicate.isUndefined(turn), turn === 0)) return
2300
+ if (Predicate.isNotUndefined(owners.get(PATH_ROTATION))) return
2301
+ snapshot.values = { ...snapshot.values, ...TURNED_BACK }
2302
+ snapshot.velocities = { ...snapshot.velocities, [PATH_ROTATION]: 0 }
2303
+ snapshot.drawnAt[PATH_ROTATION] = snapshot.now()
2304
+ gate.write(id, TURNED_BACK)
2305
+ recordFrame(TURNED_BACK)
2306
+ }
2307
+
2308
+ // Each leg that gave up keys draws the ones it kept from now on: once per such leg, a Retarget.
2309
+ const keepTheRest = (): void => {
2310
+ if (losing.length === 0) return
2311
+ Arr.forEach(losing, (running) => {
2312
+ running.losing = false
2313
+ if (running.count === 0) return
2314
+ const kept = Arr.filter(Rec.keys(running.targets), (key) => owners.get(key) === running)
2315
+ running.values = keepingOnly(kept)
2316
+ })
2317
+ losing.length = 0
2318
+ }
2319
+
2320
+ /**
2321
+ * Where `key` starts toward `like` (ADR-0024, D1; ADR-0022, D3): its Snapshot value, coerced to its
2322
+ * target's shape; one of another type on a positional key as it is, a Measured pair (#430); else
2323
+ * its Base value's start link, read at its first need, noted in `started`; with none, at its target
2324
+ * (no motion). Guards, not a match: per key, per Retarget, and a key with a value builds nothing.
2325
+ */
2326
+ const startKey = (key: string, like: number | string, started: Record<string, string>): void => {
2327
+ const coerced = ownValues.valueLike(snapshot.values[key], like)
2328
+ if (Option.isSome(coerced)) snapshot.values[key] = coerced.value
2329
+ // A start of another type than its target's, on a positional key, stays as it is: a Measured
2330
+ // pair (#430), measured at the end of the task.
2331
+ if (Option.isSome(coerced)) return
2332
+ if (keepsStart(measuredPairs, key, snapshot.values[key], like)) return
2333
+ const link = startLinkOf(key, like)
2334
+ if (Option.isSome(link) && isSameKind(link.value.value, like)) {
2335
+ snapshot.values[key] = link.value.value
2336
+ started[key] = link.value.source
2337
+ return
2338
+ }
2339
+ snapshot.values[key] = like
2340
+ started[key] = "target"
2341
+ }
2342
+
2343
+ // A key's leg ended by a failure (#257 item 4): nothing draws its keys, so a later Retarget starts them afresh.
2344
+ const forget = (running: Running): void =>
2345
+ Arr.forEach(Rec.keys(running.targets), (key) => {
2346
+ if (owners.get(key) !== running) return
2347
+ letGo(snapshot, key, running)
2348
+ owners.set(key, undefined)
2349
+ })
2350
+
2351
+ /**
2352
+ * A leg's run into its sink: one dispatcher, each sink built for the leg that needs it, a
2353
+ * Retarget's and an Imperative animation's (#433). A blend's machine is built under the element's
2354
+ * Key rules when its change holds a Variable value (`variables`, #542).
2355
+ */
2356
+ const legProgram = (leg: RetargetLegs.Leg, running: Running, variables: boolean): Effect.Effect<unknown, never, WardicServices.WardicServices> => {
2357
+ if (leg._tag === "Follow") {
2358
+ const key = leg.key
2359
+ const out: Record<string, number> = { [key]: 0 }
2360
+ // Per leg (#460): Machine's calls data-first; per frame, statements.
2361
+ return Effect.suspend(() =>
2362
+ Machine.run(leg.machine(), (frame) => {
2363
+ out[key] = frame.value
2364
+ snapshot.values[key] = frame.value
2365
+ let velocity = frame.velocity
2366
+ if (Predicate.isUndefined(velocity)) velocity = 0
2367
+ snapshot.velocities[key] = velocity
2368
+ gate.write(id, out)
2369
+ recordFrame(out)
2370
+ drew(running, frame.done, snapshot.now())
2371
+ if (frame.done) landEndsOf(waiting)
2372
+ return undefined
2373
+ }, running)
2374
+ )
2375
+ }
2376
+ if (leg._tag === "Numbers") {
2377
+ return Effect.suspend(() =>
2378
+ Machine.run(leg.machine(), (frame) => {
2379
+ // MULTI-OWNER MERGE (ADR-0004): merge the spring's keys into the snapshot
2380
+ // rather than replacing it, so the drag's direct-set x/y survive alongside the
2381
+ // spring's keys (drag owns x/y, spring owns the rest) and the post-drag
2382
+ // handoff continues from the rested position. Only the keys it still draws (#325).
2383
+ // In place, as the Follow sink writes (#659): a spread made two records per element per
2384
+ // frame. The Snapshot's records are always its own (`snapshotOf`, `emptySnapshotOf`), and
2385
+ // whatever keeps one copies it or reads it at once.
2386
+ const value = running.values(frame.value)
2387
+ Object.assign(snapshot.values, value)
2388
+ // Its velocities stay on its Frame (#663), read by index when one is asked for: copied into
2389
+ // the Snapshot each frame, they cost a boxed number a key a frame that only a Retarget read.
2390
+ running.physics = frame
2391
+ gate.write(id, value)
2392
+ recordFrame(value)
2393
+ drew(running, frame.done, snapshot.now())
2394
+ if (frame.done) {
2395
+ // Landed, its keys are at rest: the Snapshot says so for whatever reads it after it's gone.
2396
+ Arr.forEach(Rec.keys(value), (key) => {
2397
+ snapshot.velocities[key] = 0
2398
+ })
2399
+ landEndsOf(waiting)
2400
+ }
2401
+ return undefined
2402
+ }, running)
2403
+ )
2404
+ }
2405
+ // A snap's or a blend's frames: merged into the Snapshot (ADR-0004), as the spring's are. A blend's
2406
+ // last two are kept, its keys' velocities read from them (#464): the frame's own values, which a
2407
+ // blend makes anew each frame (`values` writes one object for a leg that lost keys).
2408
+ const sink = (frame: Frame.Frame<Values.Values>): undefined => {
2409
+ const value = running.values(frame.value)
2410
+ let before = running.last
2411
+ let beforeAt = running.lastAt
2412
+ // Its first frame: from the Snapshot's values, a nominal frame before it.
2413
+ if (Predicate.isUndefined(before)) {
2414
+ before = snapshot.values
2415
+ beforeAt = snapshot.now() - FrameTime.NOMINAL_FRAME
2416
+ }
2417
+ running.before = before
2418
+ running.beforeAt = beforeAt
2419
+ running.last = frame.value
2420
+ snapshot.values = { ...snapshot.values, ...value }
2421
+ gate.write(id, value)
2422
+ recordFrame(value)
2423
+ drew(running, frame.done, snapshot.now())
2424
+ if (frame.done) landEndsOf(waiting)
2425
+ return undefined
2426
+ }
2427
+ if (leg._tag === "Snap") {
2428
+ // A snapped key comes to rest, so a later spring starts it at rest.
2429
+ snapshot.velocities = { ...snapshot.velocities, ...Rec.fromEntries(Arr.map(leg.keys, (key) => [key, 0] as const)) }
2430
+ return Effect.suspend(() => Machine.run(leg.machine(), sink, running))
2431
+ }
2432
+ // Per leg (#460): a statement, Effect's calls data-first.
2433
+ let built = Effect.suspend(leg.machine)
2434
+ if (variables) built = InterpolatorRegistry.withKeyRules(built, elementRules)
2435
+ return Effect.flatMap(built, (machine) => Machine.run(machine, sink, running))
2436
+ }
2437
+
2438
+ // A leg's end, told its landing: a Retarget's legs' and an Imperative animation's (#433).
2439
+ const legEnded = (running: Running) => (exit: Exit.Exit<unknown>): Effect.Effect<void> => {
2440
+ // Its fiber has ended, and is let go: a leg kept for its keys' velocity (#464) keeps no fiber alive.
2441
+ running.fiber = undefined
2442
+ // Per leg (#460): statements.
2443
+ if (Exit.isSuccess(exit)) {
2444
+ // A Superseded leg (#200) counts toward nothing, nor tells a name: the next Retarget's legs
2445
+ // land. Nothing made for it: a Retarget ends its element's legs inline.
2446
+ const end = exit.value
2447
+ if (Supersede.isSuperseded(end)) return Effect.void
2448
+ return Effect.sync(() => {
2449
+ running.landing.settled()
2450
+ const tell = running.names
2451
+ if (Predicate.isNotUndefined(tell)) tell(end)
2452
+ })
2453
+ }
2454
+ // A leg its token didn't reach is interrupted: its keys are given up already, and it isn't a failure.
2455
+ const cause = exit.cause
2456
+ if (Cause.hasInterruptsOnly(cause)) return Effect.void
2457
+ return Report.failure("wardic.spine: a leg failed", cause).pipe(
2458
+ Effect.annotateLogs({ id }),
2459
+ Effect.andThen(Effect.sync(() => {
2460
+ forget(running)
2461
+ running.landing.failed(cause)
2462
+ })),
2463
+ )
2464
+ }
2465
+
2466
+ // A gated Retarget (ADR-0007 `when`, #325): a running key it resolves to its leg's target runs on,
2467
+ // the element reported unsettled meanwhile, when an earlier change started that leg; every other
2468
+ // running key freezes where it is. The change the gate holds may have started legs just before
2469
+ // it shut (a child Retargets before its provider's effect resets its `beforeChildren` wait; an
2470
+ // `afterChildren` provider starts before its children report): those freeze too, as before.
2471
+ const hold = (resolution: Resolution): void => {
2472
+ if (Predicate.isUndefined(gated)) gated = gatedLandingOf(onFrame)
2473
+ const landing = gated
2474
+ const resolved = resolution.resolved
2475
+ current = landing
2476
+ owners.forEach((running, key) => {
2477
+ if (Predicate.isUndefined(running)) return
2478
+ if (running.done) return
2479
+ // An Imperative animation's key (#433) is its own while taken.
2480
+ if (taken.has(key)) return
2481
+ if (Object.hasOwn(resolved, key) && running.targets[key] === resolved[key] && !sameResolution(running.resolution, resolution)) {
2482
+ running.landing = landing
2483
+ running.names = undefined
2484
+ return
2485
+ }
2486
+ giveUp(key, running)
2487
+ })
2488
+ keepTheRest()
2489
+ }
2490
+
2491
+ // The translate targets of the last Retarget that ran, held or not: what a takeover of the drag's
2492
+ // release looks for a change in (#340).
2493
+ let lastX: number | string | undefined = undefined
2494
+ let lastY: number | string | undefined = undefined
2495
+ // A Retarget took `x`/`y` from the release, and the hand-back of `dragging` hasn't come yet.
2496
+ let tookRelease = false
2497
+ /**
2498
+ * Whether the drag holds `x`/`y` for this Retarget (ADR-0004): while its pointer is down and
2499
+ * through its release, unless this Retarget gives the release's axis a new target. Then it takes
2500
+ * them from the release (#340, ADR-0016 *Amendment (#340)*), as a newer animation of Motion's value
2501
+ * stops the one running, and they go on from where the release has them, at its velocity. A key a
2502
+ * entry stops setting is no new target: it stays where the drag dropped it (ADR-0022).
2503
+ */
2504
+ const dragHolds = (resolution: Resolution): boolean => {
2505
+ const { x, y } = resolution.resolved
2506
+ // Per Retarget (#460, compose once): statements.
2507
+ const newX = Predicate.isNotUndefined(x) && x !== lastX
2508
+ const newY = Predicate.isNotUndefined(y) && y !== lastY
2509
+ lastX = x
2510
+ lastY = y
2511
+ if (!resolution.dragging) return false
2512
+ // From a takeover to the hand-back of `dragging` at the end of its task, the drag holds nothing.
2513
+ if (tookRelease) return false
2514
+ const drag = options.drag
2515
+ if (Predicate.isUndefined(drag)) return true
2516
+ if (!newX && !newY) return true
2517
+ tookRelease = drag.takeRelease({ x: newX, y: newY })
2518
+ return !tookRelease
2519
+ }
2520
+
2521
+ // --- What the spine hands over (#746) ----------------------------------------
2522
+ // To an Imperative animation (`imperative.ts`, #433) and a Batch member's hold (`member-hold.ts`, #665):
2523
+ // made at the first that asks, so an app with neither ships neither's code (ADR-0067 *Amendment (#746)*).
2524
+ let handedOver: SpineHost | undefined
2525
+ const host = (): SpineHost => {
2526
+ if (Predicate.isUndefined(handedOver)) {
2527
+ // Live reads are functions, not getters: V8 keeps a getter in its object's map, so with three of
2528
+ // its own each host had a map of its own, 1.9 KB a host against 0.5.
2529
+ handedOver = {
2530
+ lastResolution: () => lastResolution,
2531
+ snapshot,
2532
+ owners,
2533
+ taking: () => {
2534
+ readAt = snapshot.now()
2535
+ if (taken === NONE_TAKEN) taken = new Map()
2536
+ return taken
2537
+ },
2538
+ returning: () => returning,
2539
+ driven,
2540
+ timelineKeys: () => timelineKeys,
2541
+ giveUp,
2542
+ initialValues,
2543
+ ownValue,
2544
+ startKey,
2545
+ keepTheRest,
2546
+ reducedMotion: options.reducedMotion,
2547
+ skipAnimations,
2548
+ element,
2549
+ positionalKeys,
2550
+ defaultTransition,
2551
+ readVelocity,
2552
+ gate,
2553
+ forget,
2554
+ endLeg,
2555
+ live,
2556
+ own,
2557
+ legProgram,
2558
+ legEnded,
2559
+ turnBack,
2560
+ id,
2561
+ recordFrame,
2562
+ runtime,
2563
+ elementRules,
2564
+ measuredPairs,
2565
+ variableValues,
2566
+ }
2567
+ }
2568
+ return handedOver
2569
+ }
2570
+
2571
+ // --- A Batch member's element (#665's PR 4, ADR-0069 decision 17, Q52–Q54) -----------------------
2572
+
2573
+ // Its hold on what it takes from its Batch: made as its element is first found a member's, at a
2574
+ // Retarget or a drag. Nearly no element is one: the rest pay a WeakMap read a Retarget.
2575
+ let memberHold: MemberHold | undefined
2576
+ const holdNow = (): MemberHold | undefined => {
2577
+ if (Predicate.isNotUndefined(memberHold)) return memberHold
2578
+ // An app with no Batch has no way to make one, nor any member.
2579
+ const holds = memberHoldsNow()
2580
+ if (Predicate.isUndefined(holds)) return undefined
2581
+ if (!holds.isMember(element)) return undefined
2582
+ memberHold = holds.make(host())
2583
+ return memberHold
2584
+ }
2585
+ // A draggable element's drag tells it as it holds `x`/`y` and hands them back: a member's hold hears.
2586
+ if (Predicate.isNotUndefined(options.dragAxis)) {
2587
+ DRAG_HOOKS.set(element, (on) => {
2588
+ const member = holdNow()
2589
+ if (Predicate.isNotUndefined(member)) member.drag(on)
2590
+ })
2591
+ }
2592
+
2593
+ const retarget = (given: Resolution): void => {
2594
+ // A Controls change (#433): the element is in it from the Retarget it makes it run, held or not.
2595
+ if (given.change !== joined) joinChange(given.change)
2596
+ // A key an entry sets isn't its Live value's from this Retarget on, held or not: its Timeline value
2597
+ // stops (#240), and the gate draws the key in the flush that writes the entry's first value.
2598
+ if (Predicate.isNotUndefined(timelineKeys)) takeEach(timelineKeys, given.resolved)
2599
+
2600
+ // `when` start-gate (ADR-0007): when canStart() is false, the keys whose target changed freeze
2601
+ // where they are (#325: the rest run on), and the element waits; the binding retargets once
2602
+ // the gate flips true.
2603
+ if (Predicate.isNotUndefined(canStart) && !canStart()) {
2604
+ hold(given)
2605
+ // Report NOT settled: a gated child sits at its snapshot, still
2606
+ // owing an animation, so it must not count as settled (afterChildren).
2607
+ if (Predicate.isNotUndefined(onFrame)) onFrame(false)
2608
+ return
2609
+ }
2610
+ // The first Retarget a Controls change starts here runs on its override (#433); a later one, a
2611
+ // gesture's, on the targets' own.
2612
+ let resolution = given
2613
+ // On an override, every key starts again on it, a running leg toward the same target too: `set`
2614
+ // lands it at once, as Motion's.
2615
+ let restarting = false
2616
+ if (given.change !== startedChange) {
2617
+ startedChange = given.change
2618
+ const override = UndefinedOr.map(given.change, (change) => change.override)
2619
+ if (Predicate.isNotUndefined(override)) {
2620
+ resolution = overriddenOf(given, override)
2621
+ restarting = true
2622
+ }
2623
+ }
2624
+ const { resolved, base } = resolution
2625
+ // The hand-back of `dragging` after a takeover (#340): the last Retarget already ran with `x`/`y`
2626
+ // its own, so one that changes nothing else is no new animation, as Motion's has none. It goes
2627
+ // on, and lands and is told as itself.
2628
+ if (tookRelease && !resolution.dragging) {
2629
+ tookRelease = false
2630
+ if (handsBackOnly(resolution, lastResolution)) {
2631
+ lastResolution = resolution
2632
+ return
2633
+ }
2634
+ }
2635
+ const held = dragHolds(resolution)
2636
+ // The keys an Imperative animation took (#433): one whose target here isn't the one it had when
2637
+ // taken is the Override stack's again.
2638
+ if (taken.size > 0) Iter.forEach(taken, ([key, was]) => {
2639
+ if (resolved[key] !== was) taken.delete(key)
2640
+ })
2641
+
2642
+ // A key a Retarget drove and no entry sets now returns to its Base value
2643
+ // (ADR-0022); with none, it stays where it is (as before #47).
2644
+ const t: Values.Values = { ...resolved }
2645
+ Arr.forEach(Rec.keys(resolved), (key) => {
2646
+ driven.set(key, resolved[key])
2647
+ })
2648
+ if (held) Arr.forEach(dragMoves(), (key) => driven.delete(key))
2649
+ // A key the drag holds isn't its Live value's now: its Timeline value stops (#240).
2650
+ if (held) {
2651
+ const keys = timelineKeys
2652
+ if (Predicate.isNotUndefined(keys)) Arr.forEach(dragMoves(), (key) => keys.taken(key))
2653
+ }
2654
+ returning = new Map()
2655
+ // Over the Map itself: copying it into an array first costs ~20 times the walk, per element
2656
+ // per Retarget (#69's PR 4). Deleting the entry being visited is safe in a Map's iteration.
2657
+ Iter.forEach(driven, ([key, like]) => {
2658
+ // A translate key the strip below holds back returns once the drag lets go.
2659
+ if (Object.hasOwn(resolved, key) || (held && TRANSLATE_KEYS.has(key))) return
2660
+ // One an Imperative animation holds (#433) stays where it leaves it.
2661
+ if (taken.has(key)) return
2662
+ const back = BaseValue.of(key, { base, initial: initialLink, started: startedLink, ...linksFor(like) })
2663
+ if (Option.isNone(back)) {
2664
+ driven.delete(key)
2665
+ return
2666
+ }
2667
+ t[key] = back.value.value
2668
+ returning.set(key, back.value.source)
2669
+ })
2670
+ // MULTI-OWNER strip (ADR-0004): while dragging, x/y are DIRECT-SET by the
2671
+ // drag track, so strip the translate keys from the spring's target — the
2672
+ // spring must never fight the direct-set. Once dragging is false the
2673
+ // keys re-enter normally (post-drag handoff: the spring continues x/y only
2674
+ // if `animate` sets them, from the snapshot's rested position).
2675
+ if (held) Arr.forEach(TRANSLATE_KEY_LIST, (key) => delete t[key])
2676
+ // Every key an Imperative animation holds stays where it leaves it (#433).
2677
+ if (taken.size > 0) Iter.forEach(taken, ([key]) => {
2678
+ delete t[key]
2679
+ })
2680
+ // A Batch member's element (#665's PR 4, Q53): a group it moves is taken from its Batch first, and a
2681
+ // key it'd leave where the Batch draws it stays the Batch's. A drag takes `x` and `y`.
2682
+ const member = holdNow()
2683
+ if (Predicate.isNotUndefined(member)) member.retarget(t, held)
2684
+ // The keys this Retarget returns; once it lands, a key back at its `style` value is
2685
+ // handed back to the element's style (D4) and the rest rest where the gate drew them.
2686
+ const returns = [...returning]
2687
+ // The transition, read at Retarget time so a change applies to the next Retarget. A child
2688
+ // with no local transition inherits the parent context's (ADR-0007).
2689
+ const c = config()
2690
+
2691
+ // This Retarget's landing (#257, #325): it lands when every leg drawing a key it resolves has
2692
+ // settled, its own and the ones it carries. A leg's end, told apart (ADR-0027, decision 7): a
2693
+ // settle counts; a Superseded end (a Retarget, an unmount, #200) or an interruption (a leg its
2694
+ // token didn't reach) is nothing; anything else (a step or a sink that threw, the Frame loop's
2695
+ // own failure) is logged and reported (ADR-0030, decision 4), and doesn't count.
2696
+ let legs = 0
2697
+ // The variant the Retarget before this one resolved, set once this one starts (#257).
2698
+ let previous: Resolution | undefined
2699
+ const legDone = (): void => {
2700
+ if (current !== landing) return
2701
+ // A Batch member's groups go back as their last legs end (Q54), each on its own.
2702
+ if (Predicate.isNotUndefined(memberHold)) memberHold.settle()
2703
+ if (--legs !== 0) return
2704
+ settleReturns(returns)
2705
+ // The Retarget settled with its last leg (#257): told once the gate has flushed its last frame,
2706
+ // so the element shows where it landed. Its Controls change hears it then too (#433).
2707
+ if (Predicate.isNotUndefined(animation)) gate.afterFlush(() => animation.settled(resolution, previous, c))
2708
+ leaveAfterFlush()
2709
+ }
2710
+ // A leg's failure (#257 item 4): the Retarget can't land, so a binding waiting on it is told,
2711
+ // once, at once: a leg that fails before it writes leaves no flush to wait for. A leg failing
2712
+ // as it's built, before `started` is told, is told right after it.
2713
+ let failedTold = false
2714
+ let startedTold = false
2715
+ let failedEarly: { readonly error: unknown } | undefined
2716
+ const tellFailed = (error: unknown): void => {
2717
+ const hooks = animation as AnimationHooks
2718
+ // Called on its hooks, which may be a class's: not taken off them.
2719
+ if (Predicate.isNotUndefined(hooks.failed)) hooks.failed(resolution, error)
2720
+ }
2721
+ const legFailed = (cause: Cause.Cause<unknown>): void => {
2722
+ // It can't land: its Controls change waits for it no longer (#433).
2723
+ if (current === landing) leaveChange()
2724
+ if (failedTold || Predicate.isUndefined(animation)) return
2725
+ failedTold = true
2726
+ const error = Cause.squash(cause)
2727
+ if (startedTold) return tellFailed(error)
2728
+ failedEarly = { error }
2729
+ }
2730
+ // The element settles with its last leg (ADR-0024, D5): a string leg can outlast the
2731
+ // numeric one, so each leg's frames report, and only the last leg's settle reports done.
2732
+ let reporting = 0
2733
+ let settled = 0
2734
+ const report = (done: boolean): void => {
2735
+ if (done) settled++
2736
+ if (Predicate.isNotUndefined(onFrame)) onFrame(settled === reporting)
2737
+ }
2738
+ const landing: Landing = { report, settled: legDone, failed: legFailed }
2739
+ current = landing
2740
+
2741
+ // The Retarget's transitions, read before its keys: a key already there asks its own for a
2742
+ // velocity (#448).
2743
+ const elementTransition = VariantTree.ownOrInherited(c.transition, parent)
2744
+ // The base target's own transition (#277): the keys its entry drives animate on it.
2745
+ const baseTransition = VariantTarget.transitionOfTarget(resolution.transition, elementTransition)
2746
+ // Fold the per-child stagger delay (ADR-0007) into the effective
2747
+ // transition.delay = base.delay + computedDelay. extraDelay() is read
2748
+ // at Retarget time so a re-snapshot before this start is reflected. Each name's keys take that
2749
+ // name's delay (#297): the base's, its first name's.
2750
+ const layers = resolution.layers
2751
+ const extra = extraOf(extraDelay, layers[0])
2752
+ const transition = staggeredOf(baseTransition, extra, options.reuse)
2753
+ // With an entry's own transition (#277, #291), each key animates on its entry's: the base's keys
2754
+ // on the base target's, each active gesture's on its target's, else the element's, as Motion's
2755
+ // each animation type runs on its own.
2756
+ // A list's names (#297) split them too, each name's at its own delay; a list's returns run on the
2757
+ // element's transition, in a group of their own, last.
2758
+ // Guards, not matches: per Retarget, per element. A list's work (#297) is done apart, for a list:
2759
+ // the Retarget's other calls keep their inlining (docs/agents/effect-first.md).
2760
+ const listed = Arr.isArray(resolution.variant)
2761
+ // A list's names each wait for their own `when` (#297's PR 2): the entries whose gate is shut now.
2762
+ let shut: ReadonlyArray<boolean> | undefined
2763
+ if (listed) shut = shutOf(layers, byName)
2764
+ // Every key the Retarget resolves goes in its entry's group, the ones that stay too (#325): a
2765
+ // name's settle waits for them.
2766
+ const groups = keysByLayerOf(t, layers, extraDelay, extra, listed, shut)
2767
+ // Per key (#325, Motion's): a key whose running leg heads where this Retarget resolves it runs
2768
+ // on, counted toward this landing; one whose last leg landed there stays; every other's leg
2769
+ // gives it up, and it starts from its Snapshot value, coerced to its target's shape (ADR-0024,
2770
+ // D1). A key with no value yet, or one whose value can't take that shape, starts from its Base
2771
+ // value's start links, read here at its first need (ADR-0022, D3); with none, it starts at its
2772
+ // target (no motion).
2773
+ //
2774
+ // Every key's Own value is read first, at its first need, before anything writes it, so a return
2775
+ // later finds the element's value, not Wardic's (ADR-0022, D3). The read is kept: a later need is
2776
+ // a lookup. A transform key reads nothing.
2777
+ let stays: Set<string> | undefined
2778
+ let carried: Array<Running> | undefined
2779
+ let there: Record<string, number | string> | undefined
2780
+ const started: Record<string, string> = {}
2781
+ // Each key's Keyframes (#429), when any entry gives some: a key's carries on only toward the same.
2782
+ const keyframesNow = resolution.keyframes
2783
+ // The keys whose two ends may be a Measured pair (#430), found in the pass below.
2784
+ let measuring: Array<string> | undefined
2785
+ // Each key's velocity, read now (#464), for a key a spring starts or one already there.
2786
+ readAt = snapshot.now()
2787
+ // Where a Path's axis this target leaves out rests (#574), before the pass below gives up its leg.
2788
+ const rests = restsOf(owners, t)
2789
+ Arr.forEach(Rec.keys(t), (key) => {
2790
+ if (!Object.hasOwn(initialValues, key)) ownValue(key)
2791
+ const like = t[key]
2792
+ const owner = owners.get(key)
2793
+ const stops = keyframesAtOf(keyframesNow, key)
2794
+ // A leg drawing it toward another target: it's moving, so it's never already there (#448).
2795
+ let drawn = false
2796
+ if (Predicate.isNotUndefined(owner)) {
2797
+ drawn = !owner.done
2798
+ // A key whose Transition end changed starts again (#470), as Motion's value does, its end in
2799
+ // its resolved values.
2800
+ if (owner.targets[key] === like && !restarting && sameKeyframesAt(keyframesAtOf(owner.resolution.keyframes, key), stops) && !endMoved(lastResolution, resolution, key)) {
2801
+ if (Predicate.isUndefined(stays)) stays = new Set()
2802
+ stays.add(key)
2803
+ if (owner.done || owner.landing === landing) return
2804
+ owner.landing = landing
2805
+ owner.names = undefined
2806
+ legs++
2807
+ reporting++
2808
+ if (Predicate.isUndefined(carried)) carried = []
2809
+ carried.push(owner)
2810
+ return
2811
+ }
2812
+ giveUp(key, owner)
2813
+ }
2814
+ startKey(key, like, started)
2815
+ // A Measured pair (#430): its two ends of different types, found in this pass, so a Retarget
2816
+ // with none builds nothing for them.
2817
+ if (measuredPairs.needs(key, UndefinedOr.getOrThrow(snapshot.values[key]), like)) {
2818
+ if (Predicate.isUndefined(measuring)) measuring = []
2819
+ measuring.push(key)
2820
+ }
2821
+ // Already there (#448, Motion's `visual-element-target.ts`): a key at its target, coerced to its
2822
+ // shape, with no leg drawing it, at rest and given no velocity by its transition, starts none.
2823
+ // It stays, as a carried key does, and is written once more (below), as Motion sets it on the
2824
+ // next frame. One that started at its target had no value to show, so its leg writes it, as
2825
+ // Motion's does for a value it has none of. Keyframes are never there (#429): they play.
2826
+ // Its velocity read last, for a key there alone (#464): per key, per Retarget.
2827
+ let still = !drawn && started[key] !== "target"
2828
+ if (still) still = snapshot.values[key] === like
2829
+ if (still) still = readVelocity(key) === 0
2830
+ // Its transition asked last, for a key already there alone: per key, per Retarget. A quiet
2831
+ // mount's never asks (#475): Motion animates nothing at a first render that starts at its
2832
+ // `animate`, whatever velocity its transition gives (`animation-state.ts`, `shouldAnimate`).
2833
+ if (still && Predicate.isUndefined(stops) && (quiet || !givesVelocity(keyTransitionOf(resolution, groups, key, transition, elementTransition), key))) {
2834
+ if (Predicate.isUndefined(stays)) stays = new Set()
2835
+ stays.add(key)
2836
+ if (Predicate.isUndefined(there)) there = {}
2837
+ there[key] = like
2838
+ }
2839
+ // A quiet mount's Keyframes (#429): Motion animates nothing at a first render that starts at its
2840
+ // `animate`, so they stay where they start, `animate`'s last stop with `initial={false}`.
2841
+ if (quiet && Predicate.isNotUndefined(stops)) {
2842
+ if (Predicate.isUndefined(stays)) stays = new Set()
2843
+ stays.add(key)
2844
+ if (Predicate.isUndefined(there)) there = {}
2845
+ there[key] = UndefinedOr.getOrThrow(snapshot.values[key])
2846
+ }
2847
+ })
2848
+ // A key no longer resolved (one the drag holds, or one with no Base value) is given up: it stays
2849
+ // where it is.
2850
+ resolvedNow = t
2851
+ owners.forEach(giveUpUnresolved)
2852
+ keepTheRest()
2853
+ // The keys this Retarget starts legs for: all of them, unless some stay.
2854
+ let fresh: Values.Values = t
2855
+ if (Predicate.isNotUndefined(stays)) {
2856
+ const kept = stays
2857
+ fresh = Rec.filter(t, (_, key) => !kept.has(key))
2858
+ // A Path couples `x` and `y` (#438): either retargeted, the other goes along it to its target.
2859
+ fresh = RetargetLegs.withPathAxes(fresh, t, transition)
2860
+ }
2861
+ // A mount that starts at its `animate`, with nothing to animate, tells no one (#448, Motion's):
2862
+ // no start, no landing, and no list's names. It starts no leg, so it lands at once.
2863
+ const silent = quiet && Rec.isEmptyRecord(fresh) && Predicate.isUndefined(carried)
2864
+ quiet = false
2865
+ // A key only a Transition end sets (#428) starts no leg of its own: its entry's end leg holds it
2866
+ // where it is, and sets it once the entry's animated keys land.
2867
+ const ends = resolution.ends
2868
+ let freshEnds: Values.Values = NO_VALUES
2869
+ if (Predicate.isNotUndefined(ends)) {
2870
+ const endOnly = ends.endOnly
2871
+ freshEnds = Rec.filter(fresh, (_, key) => endOnly.has(key))
2872
+ if (hasKeys(freshEnds)) fresh = Rec.filter(fresh, (_, key) => !endOnly.has(key))
2873
+ }
2874
+ let from: Values.Values = Rec.map(fresh, (_, key) => UndefinedOr.getOrThrow(snapshot.values[key]))
2875
+ // Keyframes (#429) start at their first stop, a `null` one where the key is; those of more than
2876
+ // two stops run through them.
2877
+ let manyStops: RetargetLegs.StopsByKey | undefined
2878
+ if (Predicate.isNotUndefined(keyframesNow)) {
2879
+ const begun = RetargetLegs.keyframesFrom(from, fresh, Rec.map(keyframesNow, (at) => at.stops))
2880
+ from = begun.from
2881
+ manyStops = begun.stops
2882
+ }
2883
+ // Each leg: the base-value log at the head of the first, and, once the leg's run
2884
+ // settles, a count toward this landing, so the per-frame handlers stay as they were.
2885
+ let pendingLog: Effect.Effect<void> | undefined
2886
+ if (Predicate.isNotUndefined(diagnostics) && (returns.length > 0 || !Rec.isEmptyRecord(started))) pendingLog = diagnostics.baseLog(id, started, returns)
2887
+ // A list's names told settled one by one (#297, Solid 1's callbacks): each as the legs of the keys
2888
+ // it drives settle. Made only for a list with a binding that's told so.
2889
+ let names: NameSettles | undefined
2890
+ const leg = <R,>(running: Running, program: Effect.Effect<unknown, never, R>): Effect.Effect<void, never, R> => {
2891
+ legs++
2892
+ const log = pendingLog
2893
+ pendingLog = undefined
2894
+ // Per leg (#460): statements, Effect's calls data-first.
2895
+ let run: Effect.Effect<unknown, never, R> = program
2896
+ if (Predicate.isNotUndefined(log)) run = Effect.andThen(log, program)
2897
+ if (Predicate.isNotUndefined(names)) running.names = names.leg()
2898
+ return Effect.asVoid(Effect.onExit(run, legEnded(running)))
2899
+ }
2900
+ // Start a leg: forked on the provider's runtime, which runs it inline up to its add on the
2901
+ // loop, so every leg started in a task is on the loop by the end of that task and takes its
2902
+ // first step at the next tick (ADR-0027 decision 5, ADR-0033). Forked from a `runSync`, a leg
2903
+ // would inherit that call's scheduler (ADR-0027, decision 6). The runtime keeps it in its own
2904
+ // fiber Scope, which interrupts it if it's still running when the provider ends (#542).
2905
+ // The name the leg being started waits for (#297's PR 2), set as each is started; none for most.
2906
+ let gateNow: string | undefined
2907
+ const runLeg = <R extends WardicServices.WardicServices>(running: Running, program: Effect.Effect<unknown, never, R>): void => {
2908
+ let run: Effect.Effect<unknown, never, R | FrameLoop.FrameLoop> = program
2909
+ if (Predicate.isNotUndefined(gateNow)) run = gatedBy(gateNow, byName, running, program)
2910
+ running.fiber = runtime.runFork(leg(running, run))
2911
+ }
2912
+ // The legs (#48, ADR-0044 decision 8): one pure builder, which a server render's Appear
2913
+ // animation samples too, so the two can't drift. Built here; each leg's machine is built
2914
+ // in its own fiber, so a transition core rejects (#66, ADR-0025 *Amendment (#66)*) fails
2915
+ // that leg alone, reported as any leg's failure is, while the element's other legs run on.
2916
+ // The returns to a moving Live value (#130, ADR-0043 decision 6): a number's follows it,
2917
+ // in a leg of its own, and lands on it; the rest return to where it is now. Looked for
2918
+ // only when this Retarget returns a key.
2919
+ let follow: RetargetLegs.Follows | undefined
2920
+ if (returning.size > 0 && Predicate.isNotUndefined(live)) {
2921
+ const routes = live
2922
+ follow = { keysOf: (rest) => followingOf(routes, rest, returning), targetOf: (key, start) => liveTargetOf(ownValues, routes, key, start) }
2923
+ }
2924
+ const reduce = options.reducedMotion()
2925
+ const skipped = skipAnimations()
2926
+ // Measured pairs (#430), asked of the end-of-task batch, unless reduced motion snaps them or the
2927
+ // animation is skipped (#468): the keys found above, and those Keyframes of two stops start from their first.
2928
+ let measured: RetargetLegs.MeasuredPairs | undefined
2929
+ if (!reduce && !skipped && (Predicate.isNotUndefined(measuring) || Predicate.isNotUndefined(keyframesNow))) {
2930
+ measured = measuredOf(measuredPairs, element, measuringOf(measuring, keyframesNow), from, fresh, snapshot.values, manyStops)
2931
+ }
2932
+ let told: ToldNames | undefined
2933
+ if (!silent) told = namesToldOf(animation, resolution, lastResolution)
2934
+ // Every key on one transition when they aren't split, as before; else each group's legs, tagged.
2935
+ // A key that stays starts none, and no keys make no leg (#325).
2936
+ let retargetLegs: ReadonlyArray<RetargetLegs.Leg> = NO_LEGS
2937
+ let legGroups: ReadonlyArray<number> | undefined
2938
+ if (Predicate.isUndefined(groups) && hasKeys(fresh)) {
2939
+ // Where every key is now: a Path's axis the target leaves out starts there (#438), and ends where
2940
+ // it rests (#574).
2941
+ retargetLegs = RetargetLegs.legsOf(from, fresh, transition, reduce, skipped, positionalKeys, defaultTransition, readVelocity, follow, manyStops, measured, snapshot.values, rests)
2942
+ }
2943
+ if (Predicate.isNotUndefined(groups)) {
2944
+ const split = splitLegsOf(fresh, from, groups, resolution, listed, transition, elementTransition, extraDelay, options.reuse, reduce, skipped, positionalKeys, defaultTransition, readVelocity, follow, manyStops, measured, snapshot.values, rests)
2945
+ retargetLegs = split.legs
2946
+ legGroups = split.tags
2947
+ }
2948
+ // The Handoff (#48, ADR-0044 decision 6): the first Retarget that starts picks the Appear
2949
+ // animation up as far in as it has got, read at the legs' first tick.
2950
+ if (Predicate.isNotUndefined(handoff)) {
2951
+ const taken = handoff
2952
+ handoff = undefined
2953
+ if (Predicate.isNotUndefined(diagnostics)) {
2954
+ diagnostics.checkHandoff(runtime, id, taken, { tag, from, to: fresh, transition: baseTransition, reduced: reduce, layout: isLayoutNode(c), stops: manyStops, ...AppearHandoff.skippedField(skipped), ...templateField(c.transformTemplate) })
2955
+ }
2956
+ const at = AppearHandoff.startAtOf(taken, baseTransition, delayOf(transition))
2957
+ retargetLegs = Arr.map(retargetLegs, (one) => RetargetLegs.startingAt(one, at))
2958
+ }
2959
+ reporting += retargetLegs.length
2960
+ // A list's names (#297): told settled with the legs of the keys each drives, the ones a key that
2961
+ // stays carries too (#325), to the binding's callbacks and its orchestration, and each shut
2962
+ // one's legs waiting on its gate (PR 2).
2963
+ let legGates: ReadonlyArray<string | undefined> | undefined
2964
+ if (listed || Predicate.isNotUndefined(told)) {
2965
+ const carriedLegs = UndefinedOr.match(carried, { onUndefined: (): ReadonlyArray<Running> => NO_RUNNING, onDefined: identity })
2966
+ const listing = listingOf({
2967
+ listed,
2968
+ told,
2969
+ byName,
2970
+ resolution,
2971
+ groups,
2972
+ legGroups,
2973
+ legCount: retargetLegs.length,
2974
+ carriedGroups: Arr.map(carriedLegs, (running) => groupsOfLeg(running, groups, owners)),
2975
+ shut,
2976
+ hold: (g) => {
2977
+ const kept = pickKeys(from, groups, g)
2978
+ if (Bool.not(Rec.isEmptyRecord(kept))) gate.write(id, kept)
2979
+ },
2980
+ afterFlush: (fn) => gate.afterFlush(fn),
2981
+ config: c,
2982
+ })
2983
+ names = listing.names
2984
+ legGates = listing.legGates
2985
+ UndefinedOr.map(names, (settles) =>
2986
+ Arr.forEach(carriedLegs, (running, i) => {
2987
+ running.names = settles.carried(i)
2988
+ }))
2989
+ }
2990
+ // Its Live routes hear the legs it starts (#443, PR4-Q1).
2991
+ tellStarted(live, retargetLegs)
2992
+ // The element's Key rules only for a change a Variable value is in (#542).
2993
+ const variables = holdsVariable(variableValues, from, fresh, manyStops)
2994
+ // Each leg into its sink, in the builder's order (#69's PR 2: a Retarget is per element). Each
2995
+ // leg draws the keys it animates (#325) until a later Retarget takes them.
2996
+ Arr.forEach(retargetLegs, (leg: RetargetLegs.Leg, i): void => {
2997
+ if (Predicate.isNotUndefined(legGates)) gateNow = legGates[i]
2998
+ const running = runningOf(leg.to, resolution, landing, leg._tag)
2999
+ own(running)
3000
+ runLeg(running, legProgram(leg, running, variables))
3001
+ })
3002
+ // Each entry's Transition end (#428): a leg holding the keys only its end sets where they are,
3003
+ // waiting for the keys the entry animates to land (the legs drawing them now, this Retarget's or
3004
+ // carried), then setting its end values, the keys it also animates among them. It counts toward
3005
+ // this landing, so the landing includes it. A later Retarget that resolves its keys to the same
3006
+ // values carries it (#325); one that doesn't gives them up, and it never sets them.
3007
+ if (Predicate.isNotUndefined(ends)) {
3008
+ gateNow = undefined
3009
+ Arr.forEach(ends.byLayer, (writes, at) => {
3010
+ if (Predicate.isUndefined(writes)) return
3011
+ const owned = Rec.filter(freshEnds, (_, key) => ends.endOnly.get(key) === at)
3012
+ // Its end starts again when a key it also animates starts again, or its end for one changed
3013
+ // (#470, one already there starts none), or a key only it sets does.
3014
+ if (Bool.not(hasKeys(owned))) {
3015
+ const anew = Arr.some(Rec.keys(writes), (key) => {
3016
+ if (ends.endOnly.has(key)) return false
3017
+ if (Object.hasOwn(fresh, key)) return true
3018
+ return endMoved(lastResolution, resolution, key)
3019
+ })
3020
+ if (Bool.not(anew)) return
3021
+ }
3022
+ const animated = Arr.filter(Rec.keys(resolved), (key) => Bool.and(Bool.not(ends.endOnly.has(key)), driverOf(layers, key) === at))
3023
+ // Its keys set at their end, at once: no motion, so no velocity (#464).
3024
+ const running = runningOf(owned, resolution, landing, "Snap")
3025
+ own(running)
3026
+ // Held where they are: a key with nothing to start from (it would start at its target, no
3027
+ // motion) is left unset until its end, not set to it now.
3028
+ const holding = Rec.map(Rec.filter(owned, (_, key) => started[key] !== "target"), (_, key) => UndefinedOr.getOrThrow(snapshot.values[key]))
3029
+ if (hasKeys(holding)) gate.write(id, holding)
3030
+ snapshot.velocities = { ...snapshot.velocities, ...Rec.map(owned, () => 0) }
3031
+ // Counted toward this landing as a leg is (#508), with no fiber of its own: the landing of its
3032
+ // keys' last leg writes it, or the next flush when they've landed already.
3033
+ reporting++
3034
+ legs++
3035
+ const log = pendingLog
3036
+ pendingLog = undefined
3037
+ // Forked only where a Debug log is kept (#618); a leg's runs inside the leg's own fiber.
3038
+ if (Predicate.isNotUndefined(log)) {
3039
+ if (logsDebugOn(runtime)) runtime.runFork(log)
3040
+ }
3041
+ if (Predicate.isNotUndefined(names)) running.names = names.leg()
3042
+ // One that owns no key records the legs it waits for: their interrupt drops it (ADR-0057 Q1).
3043
+ let waitsOn: ReadonlyArray<Running | undefined> | undefined
3044
+ if (Bool.not(hasKeys(owned))) waitsOn = Arr.map(animated, (key) => owners.get(key))
3045
+ if (Predicate.isUndefined(waiting)) waiting = waitingEndsOf(owners, snapshot, gate, id, recordFrame)
3046
+ waiting.add({ running, animated, writes, legs: waitsOn, state: "waiting" })
3047
+ })
3048
+ }
3049
+ // A turn none of its legs draws now goes back (#460).
3050
+ turnBack()
3051
+ // The keys already there (#448), written with each key the Retarget moves at where it starts, as
3052
+ // its leg's first frame writes it: the element's first commit, which takes its Starting style off,
3053
+ // holds every key, whatever frame the legs first draw in (a gated name's draws later).
3054
+ if (Predicate.isNotUndefined(there)) {
3055
+ const written = { ...from, ...there }
3056
+ gate.write(id, written)
3057
+ recordFrame(written)
3058
+ }
3059
+ // The Retarget started, its legs on their way (#257); with none, its own or carried, it landed
3060
+ // at once (#325): its returns settle, and the element reports settled at the gate's next flush,
3061
+ // after the effects that start its orchestration's wait (ADR-0007).
3062
+ previous = lastResolution
3063
+ lastResolution = resolution
3064
+ const landed = legs === 0
3065
+ if (landed) {
3066
+ settleReturns(returns)
3067
+ if (Predicate.isNotUndefined(memberHold)) memberHold.settle()
3068
+ leaveAfterFlush()
3069
+ if (Predicate.isNotUndefined(pendingLog)) {
3070
+ if (logsDebugOn(runtime)) runtime.runFork(pendingLog)
3071
+ }
3072
+ if (Predicate.isNotUndefined(onFrame)) {
3073
+ const tell = onFrame
3074
+ gate.afterFlush(() => {
3075
+ if (current === landing) tell(true)
3076
+ })
3077
+ }
3078
+ }
3079
+ if (Predicate.isNotUndefined(animation) && !silent) {
3080
+ const hooks = animation as AnimationHooks
3081
+ hooks.started(resolution, previous, c)
3082
+ startedTold = true
3083
+ if (landed) hooks.settled(resolution, previous, c)
3084
+ if (Predicate.isNotUndefined(failedEarly)) tellFailed(failedEarly.error)
3085
+ }
3086
+ }
3087
+
3088
+ // --- Live values in `style` (#130, ADR-0043) ------------------------------
3089
+ // A routed key (a Live value, or a transform key) is its `style` link, live: while no entry of
3090
+ // the Override stack sets it, no return is running to it and no drag moves it, the element
3091
+ // follows it, written through the gate on every change. A return hands it back here when it
3092
+ // settles (`settleReturns`). The Starting style showed each one's value at render; from mount
3093
+ // the gate holds them.
3094
+ const follow = (now: FollowNow): void => {
3095
+ if (Predicate.isUndefined(live)) return
3096
+ const routes = live
3097
+ // Built at the first routed key, at mount or later: an element whose `style` routes none builds nothing.
3098
+ routes.whenRouted(() => {
3099
+ // Read at each ask: `projected` is a getter while the track waits for `drag` (#551, #582).
3100
+ const dragHolds = (): boolean => Bool.and(Bool.not(options.projected), Predicate.isNotUndefined(options.dragAxis))
3101
+ // Whether something other than the follower moves `key` now.
3102
+ const owned = (key: string): boolean =>
3103
+ Bool.some([
3104
+ driven.has(key),
3105
+ Object.hasOwn(now.resolved(), key),
3106
+ // An Imperative animation's (#433).
3107
+ taken.has(key),
3108
+ // The drag direct-sets both translate keys while it, and its release, run (ADR-0004).
3109
+ Bool.and(dragHolds(), Bool.and(now.dragging(), Bool.or(key === "x", key === "y"))),
3110
+ ])
3111
+ // Written as any frame is: into the gate, the Snapshot (at rest) and the presence record.
3112
+ const put = (values: Values.Values): void => {
3113
+ Arr.forEach(Rec.keys(values), (key) => {
3114
+ snapshot.values[key] = UndefinedOr.getOrThrow(values[key])
3115
+ delete snapshot.velocities[key]
3116
+ })
3117
+ gate.write(id, values)
3118
+ recordFrame(values)
3119
+ }
3120
+ // The element shows `key`'s Live value now: its Timeline value runs, when it has one (#240).
3121
+ const shown = (key: string): void => {
3122
+ const keys = timelineKeysNow(routes)
3123
+ if (Predicate.isNotUndefined(keys)) keys.shown(key)
3124
+ }
3125
+ handBack = (key) => {
3126
+ Option.match(Option.filter(routes.valueOf(key), isValue), {
3127
+ onNone: constVoid,
3128
+ onSome: (value) => {
3129
+ put({ [key]: value })
3130
+ shown(key)
3131
+ },
3132
+ })
3133
+ }
3134
+ // Every routed key nothing owns, with, before anything's committed, the values the Override
3135
+ // stack's keys start from, so a held start (a `when` gate) keeps showing them.
3136
+ const first = Rec.filter(routes.values(), (_, key) => Bool.not(owned(key)))
3137
+ if (hasKeys(first)) {
3138
+ put({ ...Values.pick(snapshot.values, now.resolved()), ...first })
3139
+ Arr.forEach(Rec.keys(first), shown)
3140
+ }
3141
+ return {
3142
+ change: (key, value) => {
3143
+ if (Bool.or(owned(key), Bool.not(isValue(value)))) return
3144
+ put({ [key]: value as number | string })
3145
+ shown(key)
3146
+ },
3147
+ removed: (key) => {
3148
+ if (Predicate.isNotUndefined(timelineKeys)) timelineKeys.taken(key)
3149
+ if (owned(key)) return
3150
+ delete snapshot.values[key]
3151
+ delete snapshot.velocities[key]
3152
+ if (Predicate.isNotUndefined(presence)) delete presence.snapshot.current[key]
3153
+ // Gone from `style`: the element's own value comes back, or none, its Environment's default now.
3154
+ const restore = Option.match(ownValues.styleValueOf(UndefinedOr.match(styleNow, { onUndefined: constUndefined, onDefined: (style) => style() }), key), {
3155
+ onNone: () => "",
3156
+ onSome: String,
3157
+ })
3158
+ gate.release(id, [key], { [key]: restore })
3159
+ },
3160
+ }
3161
+ })
3162
+ }
3163
+
3164
+ const dispose = (): void => {
3165
+ // Unmounted, it lands in no Controls change (#433).
3166
+ leaveChange()
3167
+ if (Predicate.isNotUndefined(live)) live.stop()
3168
+ if (Predicate.isNotUndefined(timelineKeys)) timelineKeys.dispose()
3169
+ // The legs end normally first, so closing the Scope has nothing left to interrupt. A Transition
3170
+ // end waiting or due writes nothing (#508).
3171
+ if (Predicate.isNotUndefined(waiting)) waiting.dispose()
3172
+ // Each leg not landed ends as a Retarget ends one (#542): by its token, and interrupted if its
3173
+ // token didn't reach it. Nothing else ends them before the provider does.
3174
+ owners.forEach((running) => {
3175
+ if (Predicate.isUndefined(running)) return
3176
+ if (!running.done) endLeg(running)
3177
+ })
3178
+ // Its Batch member's groups go back to the Batch (#665's PR 4).
3179
+ if (Predicate.isNotUndefined(memberHold)) memberHold.dispose()
3180
+ }
3181
+
3182
+ // A child back under its key (#286): its values and velocities from where the leaver is drawn, a
3183
+ // projected element's own translate among them (#363). Drawn at the end of the task, so nothing
3184
+ // paints the element at its `initial` first: not in the mount effect it's called in, where the
3185
+ // first commit's Starting-style switch would flush Solid 2 inside an effect.
3186
+ const seed = (from: PresenceRecord.PresenceSeed): void => {
3187
+ const values = from.values
3188
+ Object.assign(snapshot.values, values)
3189
+ snapshot.velocities = { ...snapshot.velocities, ...from.velocities }
3190
+ // Drawn now, by the leaver (#464).
3191
+ const now = snapshot.now()
3192
+ Arr.forEach(Rec.keys(from.velocities), (key) => {
3193
+ snapshot.drawnAt[key] = now
3194
+ })
3195
+ if (Predicate.isNotUndefined(presence)) Object.assign(presence.snapshot.current, values)
3196
+ Arr.forEach(Rec.keys(values), (key) => {
3197
+ driven.set(key, values[key])
3198
+ })
3199
+ queueMicrotask(() => gate.flushPass(() => gate.write(id, values)))
3200
+ }
3201
+
3202
+ // **Animation controls**' `stop` (#433): every running leg ends where it is, its keys given up, so
3203
+ // the next Retarget starts them from where they're drawn.
3204
+ const stop = (): void => {
3205
+ owners.forEach((running) => {
3206
+ if (Predicate.isUndefined(running)) return
3207
+ forget(running)
3208
+ if (Bool.not(running.done)) endLeg(running)
3209
+ })
3210
+ turnBack()
3211
+ }
3212
+
3213
+ return { retarget, follow, dispose, seed, host, stop }
3214
+ }
3215
+
3216
+ /**
3217
+ * `sink` with an `onCommit` that calls the config's current `onUpdate` (#233), when the config had
3218
+ * one at mount; `sink` as it is otherwise. `config` reads it untracked.
3219
+ */
3220
+ export const withOnUpdate = (sink: FlushGate.Sink, atMount: Config.SpineConfig["onUpdate"], config: () => Config.SpineConfig): FlushGate.Sink => {
3221
+ // Per element at mount: most have none, and pay a check.
3222
+ if (Predicate.isUndefined(atMount)) return sink
3223
+ return {
3224
+ ...sink,
3225
+ onCommit: (latest) => {
3226
+ const onUpdate = config().onUpdate
3227
+ if (Predicate.isNotUndefined(onUpdate)) onUpdate(latest as Readonly<Record<string, number | string>>)
3228
+ },
3229
+ }
3230
+ }
3231
+
3232
+ /**
3233
+ * A Retarget's note of the keys it started from their Base value, or returned to it (ADR-0022): run at
3234
+ * the head of its first leg, cold path (no fiber of its own: forking one per element cost 10-20 µs each
3235
+ * at a 1000-element mount).
3236
+ */
3237
+ export const baseLog = (id: string, started: Record<string, string>, returns: ReadonlyArray<readonly [string, BaseValue.BaseSource]>): Effect.Effect<void> =>
3238
+ Effect.logDebug("wardic.base: a key with no value started from, or returned to, its Base value (ADR-0022)").pipe(
3239
+ Effect.annotateLogs({ id, started, returned: Object.fromEntries(returns) }),
3240
+ )
3241
+
3242
+ /** The keys a Retarget returns to a Live value that's a number: each one's return follows it (#130). */
3243
+ const followingOf = (routes: LiveRoutes, rest: Values.Values, returning: ReadonlyMap<string, BaseValue.BaseSource>): ReadonlyArray<string> =>
3244
+ Arr.filter(Rec.keys(rest), (key) => Bool.and(returning.get(key) === "style", Bool.and(routes.isLive(key), Predicate.isNumber(rest[key]))))
3245
+
3246
+ /** Where `key`'s Live value is now, a number; where it last was when it's none (#130). */
3247
+ const liveTargetOf = (ownValues: OwnValues.Shape, routes: LiveRoutes, key: string, start: number): (() => number) => {
3248
+ let last = start
3249
+ return () => {
3250
+ const now = Option.flatMap(routes.valueOf(key), (raw) => ownValues.valueLike(raw, last))
3251
+ if (Option.isSome(now)) last = now.value as number
3252
+ return last
3253
+ }
3254
+ }
3255
+
3256
+ /** Whether a value is one an element can take: a number or a string. */
3257
+ const isValue = (value: unknown): value is number | string => Bool.or(Predicate.isNumber(value), Predicate.isString(value))
3258
+
3259
+ /** A provider runtime's `AtomRegistry`, read on first need: an element with no Atom never reads it. */
3260
+ export const registryOf = (runtime: WardicServices.Runner<WardicServices.WardicServices>): (() => AtomRegistry.AtomRegistry) => {
3261
+ let registry: AtomRegistry.AtomRegistry | undefined
3262
+ return () => {
3263
+ if (Predicate.isUndefined(registry)) registry = runtime.runSync(AtomRegistry.AtomRegistry)
3264
+ return registry
3265
+ }
3266
+ }
3267
+
3268
+ /** Whether a config makes its element a layout node: `layout` (or a mode), or a `layoutId`. */
3269
+ export const isLayoutNode = (c: Config.SpineConfig): boolean =>
3270
+ Bool.or(Bool.and(Predicate.isNotUndefined(c.layout), c.layout !== false), Predicate.isNotUndefined(c.layoutId))
3271
+
3272
+ /** A mount animation's template field (#443): left out with none, as its key reads it. */
3273
+ export const templateField = (template: Config.SpineConfig["transformTemplate"]): { readonly template?: Config.SpineConfig["transformTemplate"] } =>
3274
+ UndefinedOr.match(template, { onUndefined: () => ({}), onDefined: (t) => ({ template: t }) })
3275
+