@wardic/core 1.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/unstable/AnimationControls.d.ts +110 -0
  2. package/dist/unstable/AnimationControls.d.ts.map +1 -0
  3. package/dist/unstable/AnimationControls.js +107 -0
  4. package/dist/unstable/AnimationControls.js.map +1 -0
  5. package/dist/unstable/AppearHandoff.d.ts +53 -0
  6. package/dist/unstable/AppearHandoff.d.ts.map +1 -0
  7. package/dist/unstable/AppearHandoff.js +23 -0
  8. package/dist/unstable/AppearHandoff.js.map +1 -0
  9. package/dist/unstable/Config.d.ts +285 -0
  10. package/dist/unstable/Config.d.ts.map +1 -0
  11. package/dist/unstable/Config.js +3 -0
  12. package/dist/unstable/Config.js.map +1 -0
  13. package/dist/unstable/FlushGate.d.ts +222 -0
  14. package/dist/unstable/FlushGate.d.ts.map +1 -0
  15. package/dist/unstable/FlushGate.js +567 -0
  16. package/dist/unstable/FlushGate.js.map +1 -0
  17. package/dist/unstable/FrameTime.d.ts +21 -0
  18. package/dist/unstable/FrameTime.d.ts.map +1 -0
  19. package/dist/unstable/FrameTime.js +45 -0
  20. package/dist/unstable/FrameTime.js.map +1 -0
  21. package/dist/unstable/MeasuredPairs.d.ts +51 -0
  22. package/dist/unstable/MeasuredPairs.d.ts.map +1 -0
  23. package/dist/unstable/MeasuredPairs.js +20 -0
  24. package/dist/unstable/MeasuredPairs.js.map +1 -0
  25. package/dist/unstable/OwnValues.d.ts +29 -0
  26. package/dist/unstable/OwnValues.d.ts.map +1 -0
  27. package/dist/unstable/OwnValues.js +22 -0
  28. package/dist/unstable/OwnValues.js.map +1 -0
  29. package/dist/unstable/PresenceRecord.d.ts +176 -0
  30. package/dist/unstable/PresenceRecord.d.ts.map +1 -0
  31. package/dist/unstable/PresenceRecord.js +26 -0
  32. package/dist/unstable/PresenceRecord.js.map +1 -0
  33. package/dist/unstable/Reactivity.d.ts +29 -0
  34. package/dist/unstable/Reactivity.d.ts.map +1 -0
  35. package/dist/unstable/Reactivity.js +15 -0
  36. package/dist/unstable/Reactivity.js.map +1 -0
  37. package/dist/unstable/Report.d.ts +30 -0
  38. package/dist/unstable/Report.d.ts.map +1 -0
  39. package/dist/unstable/Report.js +66 -0
  40. package/dist/unstable/Report.js.map +1 -0
  41. package/dist/unstable/RetargetLegs.d.ts +189 -0
  42. package/dist/unstable/RetargetLegs.d.ts.map +1 -0
  43. package/dist/unstable/RetargetLegs.js +834 -0
  44. package/dist/unstable/RetargetLegs.js.map +1 -0
  45. package/dist/unstable/Spine.d.ts +696 -0
  46. package/dist/unstable/Spine.d.ts.map +1 -0
  47. package/dist/unstable/Spine.js +2617 -0
  48. package/dist/unstable/Spine.js.map +1 -0
  49. package/dist/unstable/Stops.d.ts +82 -0
  50. package/dist/unstable/Stops.d.ts.map +1 -0
  51. package/dist/unstable/Stops.js +149 -0
  52. package/dist/unstable/Stops.js.map +1 -0
  53. package/dist/unstable/Subject.d.ts +11 -0
  54. package/dist/unstable/Subject.d.ts.map +1 -0
  55. package/dist/unstable/Subject.js +12 -0
  56. package/dist/unstable/Subject.js.map +1 -0
  57. package/dist/unstable/Timelines.d.ts +51 -0
  58. package/dist/unstable/Timelines.d.ts.map +1 -0
  59. package/dist/unstable/Timelines.js +10 -0
  60. package/dist/unstable/Timelines.js.map +1 -0
  61. package/dist/unstable/VariableValues.d.ts +27 -0
  62. package/dist/unstable/VariableValues.d.ts.map +1 -0
  63. package/dist/unstable/VariableValues.js +19 -0
  64. package/dist/unstable/VariableValues.js.map +1 -0
  65. package/dist/unstable/VariantTarget.d.ts +106 -0
  66. package/dist/unstable/VariantTarget.d.ts.map +1 -0
  67. package/dist/unstable/VariantTarget.js +185 -0
  68. package/dist/unstable/VariantTarget.js.map +1 -0
  69. package/dist/unstable/VariantTree.d.ts +351 -0
  70. package/dist/unstable/VariantTree.d.ts.map +1 -0
  71. package/dist/unstable/VariantTree.js +362 -0
  72. package/dist/unstable/VariantTree.js.map +1 -0
  73. package/dist/unstable/WardicConfigValue.d.ts +89 -0
  74. package/dist/unstable/WardicConfigValue.d.ts.map +1 -0
  75. package/dist/unstable/WardicConfigValue.js +106 -0
  76. package/dist/unstable/WardicConfigValue.js.map +1 -0
  77. package/dist/unstable/WardicServices.d.ts +46 -0
  78. package/dist/unstable/WardicServices.d.ts.map +1 -0
  79. package/dist/unstable/WardicServices.js +72 -0
  80. package/dist/unstable/WardicServices.js.map +1 -0
  81. package/package.json +1 -1
  82. package/src/unstable/AnimationControls.ts +199 -0
  83. package/src/unstable/AppearHandoff.ts +81 -0
  84. package/src/unstable/Config.ts +326 -0
  85. package/src/unstable/FlushGate.ts +730 -0
  86. package/src/unstable/FrameTime.ts +52 -0
  87. package/src/unstable/MeasuredPairs.ts +56 -0
  88. package/src/unstable/OwnValues.ts +32 -0
  89. package/src/unstable/PresenceRecord.ts +202 -0
  90. package/src/unstable/Reactivity.ts +35 -0
  91. package/src/unstable/Report.ts +75 -0
  92. package/src/unstable/RetargetLegs.ts +1062 -0
  93. package/src/unstable/Spine.ts +3275 -0
  94. package/src/unstable/Stops.ts +221 -0
  95. package/src/unstable/Subject.ts +13 -0
  96. package/src/unstable/Timelines.ts +58 -0
  97. package/src/unstable/VariableValues.ts +27 -0
  98. package/src/unstable/VariantTarget.ts +246 -0
  99. package/src/unstable/VariantTree.ts +643 -0
  100. package/src/unstable/WardicConfigValue.ts +154 -0
  101. package/src/unstable/WardicServices.ts +125 -0
@@ -0,0 +1,1062 @@
1
+ /**
2
+ * A Retarget's legs as one pure builder (#48, ADR-0044 decision 8): which machines a Retarget
3
+ * runs, each from where and on which transition, with nothing of the element's (its gate, its
4
+ * Snapshot, its fibers). The spine runs each leg into its sinks; a server render samples a mount's
5
+ * legs into an Appear animation, so the two can't drift.
6
+ *
7
+ * - **Which transition** (ADR-0051, #357): a key runs on the transition it resolves to (#301), as
8
+ * Motion's: with none defined there, on its Environment's Default transition for it ({@link runOf}).
9
+ * - **A tween** runs every key, numbers and strings, in one `animateValues` leg; with a key's
10
+ * Keyframes among them (#429, ADR-0058), or `times` or an `ease` per Interval, in one
11
+ * `keyframesValues` leg.
12
+ * - **A spring** runs the numbers in one `springValues` leg, carrying velocity, and the strings in
13
+ * one `springBlend` leg on the same spring (ADR-0024, D5). It takes two stops: Keyframes of more
14
+ * are Motion's error, and land on their last stop.
15
+ * - **Keyframes of two stops** run as a target does, from their first stop ({@link keyframesFrom}).
16
+ * - **A Measured pair** (#430, its Environment's `MeasuredPairs`) runs in a leg of its own, between its ends
17
+ * in px, measured at the end of the task, and lands on its target as given.
18
+ * - **Reduced motion** (ADR-0029): when it applies, the positional keys snap in a leg of their own,
19
+ * after the delay their transition gives, to where their leg would have ended.
20
+ * - **A return to a moving Live value** (#130, ADR-0043 decision 6) runs a leg of its own per key,
21
+ * a tween easing toward it, a spring chasing it.
22
+ *
23
+ * The legs come in the order the spine starts them: the snap, the follows, then the rest. A leg's
24
+ * machine is built when it's called, inside the leg's own fiber, so a transition core rejects
25
+ * fails that leg alone (#66).
26
+ *
27
+ * Unstable, for Wardic's own packages: public, with no semver promise.
28
+ *
29
+ * @module
30
+ */
31
+ // Unstable: ADR-0071, decision 5. #672: solid's `retarget-legs.ts`, moved for the spine to build its
32
+ // legs in core.
33
+ import type * as Arc from "../Arc.ts"
34
+ import * as DefaultTransition from "../DefaultTransition.ts"
35
+ import * as Easing from "../Easing.ts"
36
+ import type * as Frame from "../Frame.ts"
37
+ import * as Inertia from "../Inertia.ts"
38
+ import type * as InterpolatorRegistry from "../InterpolatorRegistry.ts"
39
+ import * as Machine from "../Machine.ts"
40
+ import * as ReducedMotion from "../ReducedMotion.ts"
41
+ import * as Spring from "../Spring.ts"
42
+ import * as Values from "../Values.ts"
43
+ import type * as CoreMeasuredPairs from "./MeasuredPairs.ts"
44
+ import type * as Stops from "./Stops.ts"
45
+ import * as Arr from "effect/Array"
46
+ import * as Bool from "effect/Boolean"
47
+ import * as Effect from "effect/Effect"
48
+ import { identity, type LazyArg } from "effect/Function"
49
+ import * as Match from "effect/Match"
50
+ import * as Option from "effect/Option"
51
+ import * as Predicate from "effect/Predicate"
52
+ import * as Rec from "effect/Record"
53
+ import * as UndefinedOr from "effect/UndefinedOr"
54
+ import type * as Config from "./Config.ts"
55
+
56
+ /** A Retarget's returns that follow a moving Live value (#130, ADR-0043 decision 6). */
57
+ export interface Follows {
58
+ /** The keys among the animated ones whose return follows its Live value. */
59
+ readonly keysOf: (rest: Values.Values) => ReadonlyArray<string>
60
+ /** Where a following key's Live value is now, read each step. */
61
+ readonly targetOf: (key: string, start: number) => () => number
62
+ }
63
+
64
+ /** A leg that snaps the positional keys (ADR-0029). */
65
+ export interface Snap {
66
+ readonly _tag: "Snap"
67
+ /** The keys it snaps: a spring starts each of them at rest after. */
68
+ readonly keys: ReadonlyArray<string>
69
+ /** Each key it snaps, with the target the Retarget gave it (#325). */
70
+ readonly to: Values.Values
71
+ readonly machine: () => Machine.Machine<Frame.Frame<Values.Values>>
72
+ }
73
+
74
+ /** A leg that follows one key's moving Live value (#130). */
75
+ export interface Follow {
76
+ readonly _tag: "Follow"
77
+ readonly key: string
78
+ /** Its key, with where its Live value was at the Retarget (#325). */
79
+ readonly to: Values.Values
80
+ readonly machine: () => Machine.Machine<Frame.Frame<number> & { readonly velocity?: number }>
81
+ }
82
+
83
+ /** A leg over the numeric keys, carrying their velocities: a spring's. */
84
+ export interface Numbers {
85
+ readonly _tag: "Numbers"
86
+ /** Each key it animates, with its target (#325). */
87
+ readonly to: Values.Values
88
+ readonly machine: () => Machine.Machine<Frame.MultiPhysics>
89
+ }
90
+
91
+ /** A leg over values through the Interpolators: a tween's keys, or a spring's strings. */
92
+ export interface Blend {
93
+ readonly _tag: "Blend"
94
+ /** Each key it animates, with its target (#325). */
95
+ readonly to: Values.Values
96
+ readonly machine: () => Effect.Effect<Machine.Machine<Frame.Frame<Values.Values>>, never, InterpolatorRegistry.InterpolatorRegistry>
97
+ }
98
+
99
+ /** One leg of a Retarget. */
100
+ export type Leg = Snap | Follow | Numbers | Blend
101
+
102
+ /**
103
+ * Each key's velocity now (#464): read only for a key a spring or a follow starts, so a tween's
104
+ * Retarget reads none. A spring takes its transition's own `velocity` over it, as Motion's
105
+ * `{ velocity: value.getVelocity(), ...valueTransition }`.
106
+ */
107
+ export type Velocities = (key: string) => number
108
+
109
+ /** No velocity: every key at rest. */
110
+ export const NO_VELOCITY: Velocities = () => 0
111
+
112
+ /** Each key's velocity from a record of them, 0 for one it doesn't have. */
113
+ export const velocitiesOf = (record: Readonly<Record<string, number>>): Velocities => (key) => {
114
+ const velocity = record[key]
115
+ if (Predicate.isUndefined(velocity)) return 0
116
+ return velocity
117
+ }
118
+
119
+ /**
120
+ * The fields no machine reads: the orchestration's (ADR-0007), the variant tree's, and a Path
121
+ * (#438), which {@link legsOf} takes out to `x` and `y`'s leg. Neither defines a transition.
122
+ */
123
+ const ORCHESTRATION = ["staggerChildren", "delayChildren", "from", "staggerDirection", "when", "path"] as const
124
+
125
+ /** A transition as a machine takes it: without the orchestration's fields (#243) or its Path (#438), each arm. */
126
+ export type MotionTransition = Config.WardicTransition extends infer T ? (T extends unknown ? Omit<T, (typeof ORCHESTRATION)[number]> : never) : never
127
+
128
+ /** Each transition without its orchestration, by the transition: one object each, so core's decode cache hits (#66). */
129
+ // Module state (#460, Q7): a cache held weakly by the object it's for, so it goes with it.
130
+ const MOTIONS = new WeakMap<Config.WardicTransition, MotionTransition>()
131
+
132
+ /**
133
+ * A transition as its machines take it: without the orchestration's fields (#243). A stagger's
134
+ * `from` (`"last"`, `"center"`) is the variant tree's, and a spring decodes `from` as its starting
135
+ * position, so it failed every leg; the rest of those fields a machine ignores. The same transition,
136
+ * one with none of them.
137
+ */
138
+ export const motionOf = (transition: Config.WardicTransition | undefined): MotionTransition | undefined =>
139
+ UndefinedOr.map(transition, (t): MotionTransition =>
140
+ Bool.match(Arr.some(ORCHESTRATION, (key) => Object.hasOwn(t, key)), {
141
+ onFalse: () => t as MotionTransition,
142
+ onTrue: () =>
143
+ Option.getOrElse(Option.fromUndefinedOr(MOTIONS.get(t)), () => {
144
+ const motion = Rec.filter(t as Record<string, unknown>, (_, key) => Bool.not(Arr.contains(ORCHESTRATION, key))) as MotionTransition
145
+ MOTIONS.set(t, motion)
146
+ return motion
147
+ }),
148
+ }))
149
+
150
+ // --- Per-value transitions (#301, Motion's `getValueTransition`) ---------------------------
151
+
152
+ /**
153
+ * A transition's entries (#301): its own fields, and each value's entry (`default` and `layout`
154
+ * among them). Each entry is resolved at its first need and kept, so its keys run on the same object
155
+ * at every Retarget (#66's decode cache keys on it).
156
+ */
157
+ interface Entries {
158
+ readonly own: Config.WardicTransition
159
+ readonly byKey: Readonly<Record<string, Config.WardicTransition>>
160
+ /** Whether any entry is a value's, not `default` or `layout`: else every value runs on one transition. */
161
+ readonly byValue: boolean
162
+ readonly resolved: Map<string, Config.WardicTransition>
163
+ }
164
+
165
+ /** A transition with no entry: what nearly every transition is. */
166
+ const NONE: unique symbol = Symbol("wardic.noEntries")
167
+
168
+ /** Each transition's entries, worked out once per object (#301). */
169
+ // Module state (#460, Q7): a cache held weakly by the object it's for, so it goes with it.
170
+ const ENTRIES = new WeakMap<object, Entries | typeof NONE>()
171
+
172
+ /** The entries that aren't a value's. */
173
+ const NOT_VALUES: ReadonlySet<string> = new Set(["default", "layout"])
174
+
175
+ /**
176
+ * Whether a field is an entry (#301): a transition, under a value's name, `default` or `layout`. No
177
+ * option of a transition's own is a plain object: an easing is a function, `times` an array.
178
+ */
179
+ const isEntry = (value: unknown): boolean => Predicate.isObject(value)
180
+
181
+ /**
182
+ * A transition's entries (#301), or `undefined` for one with none: worked out once per transition
183
+ * object, so an element whose transitions have none pays a lookup per Retarget.
184
+ */
185
+ export const entriesOf = (given: Config.WardicTransition | undefined): Entries | undefined => {
186
+ if (Predicate.isUndefined(given)) return undefined
187
+ const known = ENTRIES.get(given)
188
+ if (known === NONE) return undefined
189
+ if (Predicate.isNotUndefined(known)) return known
190
+ const fields = given as Readonly<Record<string, unknown>>
191
+ const keys = Arr.filter(Rec.keys(fields), (key) => isEntry(fields[key]))
192
+ if (keys.length === 0) {
193
+ ENTRIES.set(given, NONE)
194
+ return undefined
195
+ }
196
+ const made: Entries = {
197
+ own: Rec.filter(fields, (value) => Bool.not(isEntry(value))) as Config.WardicTransition,
198
+ byKey: Rec.fromEntries(Arr.map(keys, (key) => [key, fields[key] as Config.WardicTransition] as const)),
199
+ byValue: Arr.some(keys, (key) => Bool.not(NOT_VALUES.has(key))),
200
+ resolved: new Map(),
201
+ }
202
+ ENTRIES.set(given, made)
203
+ return made
204
+ }
205
+
206
+ /**
207
+ * The transition `key` runs on (#301, Motion's `getValueTransition`): its entry, else `default`, else
208
+ * the transition's own fields; an entry with `inherit: true` laid over the own fields, its own winning.
209
+ * The reduced-motion opt-out is the whole transition's, as the orchestration is: an entry without
210
+ * its own takes the top level's.
211
+ */
212
+ const forKey = (entries: Entries, key: string): Config.WardicTransition => {
213
+ if (Object.hasOwn(entries.byKey, key)) return entryNamed(entries, key)
214
+ if (Object.hasOwn(entries.byKey, "default")) return entryNamed(entries, "default")
215
+ return entries.own
216
+ }
217
+
218
+ /** The entry `name` resolved, once: every key on it runs on the one object, so they share a leg. */
219
+ const entryNamed = (entries: Entries, name: string): Config.WardicTransition => {
220
+ const kept = entries.resolved.get(name)
221
+ if (Predicate.isNotUndefined(kept)) return kept
222
+ const made = resolvedEntry(entries.own, entries.byKey[name] as Config.WardicTransition)
223
+ entries.resolved.set(name, made)
224
+ return made
225
+ }
226
+
227
+ /**
228
+ * An entry as its key runs on it (#301): over the own fields with `inherit`, else with their
229
+ * reduced-motion opt-out and their `skipAnimations` alone (#468: Motion skips every value of a
230
+ * transition that says so).
231
+ */
232
+ const resolvedEntry = (own: Config.WardicTransition, entry: Config.WardicTransition): Config.WardicTransition => {
233
+ const { inherit, ...rest } = entry as Config.WardicTransition & { readonly inherit?: boolean }
234
+ if (inherit === true) return { ...own, ...rest } as Config.WardicTransition
235
+ let made = rest as Config.WardicTransition
236
+ if (Bool.and(Predicate.isNotUndefined(own.respectReducedMotion), Predicate.isUndefined(rest.respectReducedMotion))) made = { ...made, respectReducedMotion: own.respectReducedMotion } as Config.WardicTransition
237
+ if (own.skipAnimations === true) made = { ...made, skipAnimations: true } as Config.WardicTransition
238
+ return made
239
+ }
240
+
241
+ /**
242
+ * The transition `key` runs on in `given` (#301): its entry, else `default`, else `given`'s own
243
+ * fields. `given` itself when it has no entry.
244
+ */
245
+ export const transitionForKey = (given: Config.WardicTransition | undefined, key: string): Config.WardicTransition | undefined => {
246
+ const entries = entriesOf(given)
247
+ if (Predicate.isUndefined(entries)) return given
248
+ return forKey(entries, key)
249
+ }
250
+
251
+ /**
252
+ * `given` held back by `extra` more seconds (ADR-0007's stagger, #290's exit delays): its own `delay`,
253
+ * and each entry's (#301), so a key on its entry waits as the rest do. An `inherit` entry with no
254
+ * `delay` of its own takes the own fields' as they are.
255
+ */
256
+ export const delayedBy = (given: Config.WardicTransition | undefined, extra: number): Config.WardicTransition | undefined => {
257
+ if (extra === 0) return given
258
+ const own = { ...given, delay: delayIn(given) + extra } as Config.WardicTransition
259
+ const entries = entriesOf(given)
260
+ if (Predicate.isUndefined(entries)) return own
261
+ return {
262
+ ...own,
263
+ ...Rec.map(entries.byKey, (entry) => {
264
+ const fields = entry as Config.WardicTransition & { readonly inherit?: boolean }
265
+ if (Bool.and(fields.inherit === true, Predicate.isUndefined(fields.delay))) return entry
266
+ return { ...entry, delay: delayIn(entry) + extra }
267
+ }),
268
+ } as Config.WardicTransition
269
+ }
270
+
271
+ /** A transition's `delay`, 0 without one. */
272
+ const delayIn = (transition: Config.WardicTransition | undefined): number =>
273
+ UndefinedOr.match(transition, { onUndefined: () => 0, onDefined: (t) => UndefinedOr.match(t.delay, { onUndefined: () => 0, onDefined: identity }) })
274
+
275
+ // --- A transition as its legs run it (ADR-0051, #357) -----------------------------------------
276
+
277
+ /**
278
+ * A transition as its legs run it: a spring or a tween, Motion's fields filled in (ADR-0051), with
279
+ * its reduced-motion opt-out.
280
+ */
281
+ export type Run = (DefaultTransition.Transition | DefaultTransition.KeyframesTransition | InertiaRun) & { readonly respectReducedMotion?: boolean; readonly skipAnimations?: boolean }
282
+
283
+ /** An inertia as its legs run it (#435): core's options, `timeConstant` in seconds, with the transition's `velocity` and `delay`. */
284
+ export type InertiaRun = Machine.InertiaValuesOptions & { readonly type: "inertia" }
285
+
286
+ /** Each key's stops past its first two (#429): the Keyframes a tween runs through `keyframesValues`. */
287
+ export type StopsByKey = Readonly<Record<string, ReadonlyArray<number | string>>>
288
+
289
+ /**
290
+ * Whether `key` has Keyframes of more than two stops among `stops`: never a Measured pair (#430). They
291
+ * run through their stops, switching where types mix, as Motion's measures two stops only (#460).
292
+ */
293
+ export const hasManyStops = (stops: StopsByKey | undefined, key: string): boolean => {
294
+ if (Predicate.isUndefined(stops)) return false
295
+ return Object.hasOwn(stops, key)
296
+ }
297
+
298
+ /** Where a Retarget's keys start, and each one's stops, its Keyframes resolved ({@link keyframesFrom}). */
299
+ export interface KeyframesStart {
300
+ readonly from: Values.Values
301
+ readonly stops: StopsByKey | undefined
302
+ }
303
+
304
+ /**
305
+ * Where a target's keys start with its **Keyframes** resolved (#429, Motion's): a first `null` stop is
306
+ * where the key is (`from`), each later one the stop before (`fillWildcards`), and an explicit first
307
+ * stop is where it starts, jumped to. `stops` holds the keys with more than two: a key with two runs
308
+ * as a target does, from its first, so a spring takes it with the key's velocity, as Motion's.
309
+ *
310
+ * @param from each key's start
311
+ * @param to each key's target, its Keyframes' last stop
312
+ * @param keyframes each Keyframes key's stops; only the keys `to` has are read
313
+ */
314
+ export const keyframesFrom = (from: Values.Values, to: Values.Values, keyframes: Readonly<Record<string, Stops.Stops>>): KeyframesStart => {
315
+ const started: Record<string, number | string> = { ...from }
316
+ let many: Record<string, ReadonlyArray<number | string>> | undefined
317
+ Arr.forEach(Rec.keys(keyframes), (key) => {
318
+ if (Bool.not(Object.hasOwn(to, key))) return
319
+ const filled = filledStops(UndefinedOr.getOrThrow(keyframes[key]), UndefinedOr.getOrThrow(from[key]))
320
+ started[key] = UndefinedOr.getOrThrow(filled[0])
321
+ if (filled.length < 3) return
322
+ if (Predicate.isUndefined(many)) many = {}
323
+ many[key] = filled
324
+ })
325
+ return { from: started, stops: many }
326
+ }
327
+
328
+ /**
329
+ * Stops with each `null` filled (#429, Motion's `fillWildcards`): the first with `start`, a later one
330
+ * with the stop before. A sequence's function Segment fills its own from 0 (#433).
331
+ */
332
+ export const filledStops = (stops: Stops.Stops, start: number | string): ReadonlyArray<number | string> => {
333
+ let before = start
334
+ return Arr.map(stops, (stop) => {
335
+ if (Predicate.isNotNull(stop)) before = stop
336
+ return before
337
+ })
338
+ }
339
+
340
+ /**
341
+ * Why Keyframes of more than two stops can't run on a spring (#429): Motion's development error
342
+ * ("Only two keyframes currently supported with spring and inertia animations"), naming each key, its
343
+ * stops and the fix.
344
+ */
345
+ const springStopsError = (stops: StopsByKey, kind = "a spring"): Error =>
346
+ new Error(
347
+ `wardic: ${Arr.map(Rec.toEntries(stops), ([key, list]) => `"${key}" has ${list.length} keyframes`).join(", ")}, and ${kind} takes two, as Motion's does (#429). ` +
348
+ `Run them on a tween: transition: { ${Arr.map(Rec.keys(stops), (key) => `${JSON.stringify(key)}: { type: "tween" }`).join(", ")} }.`,
349
+ )
350
+
351
+ /** Each tween's answer to {@link keyframedOptions}, by its options: one object each, as {@link RUNS}' (#452). */
352
+ // Module state (#460, Q7): a cache held weakly by the object it's for, so it goes with it.
353
+ const KEYFRAMED = new WeakMap<object, boolean>()
354
+
355
+ /**
356
+ * Whether a tween's options need `keyframesValues` (#429): `times`, or an `ease` per Interval, which
357
+ * `animateValues` doesn't take. Worked out once per options object (#452): every tween Retarget asks.
358
+ */
359
+ const keyframedOptions = (options: Machine.KeyframesOptions): boolean => {
360
+ const known = KEYFRAMED.get(options)
361
+ if (Predicate.isNotUndefined(known)) return known
362
+ const keyframed = Bool.or(Predicate.isNotUndefined(options.times), Bool.and(Arr.isArray(options.ease), Bool.not(Easing.isBezier(options.ease as Easing.Definition))))
363
+ KEYFRAMED.set(options, keyframed)
364
+ return keyframed
365
+ }
366
+
367
+ /**
368
+ * The spring fields: one of them, with no `type`, makes a transition a spring, a value's or a layout
369
+ * animation's (ADR-0009 *Amendment (#171)*, ADR-0051); a time-based spring's `bounce` and
370
+ * `visualDuration` among them (#359), where a `duration` alone is a tween's.
371
+ */
372
+ export const SPRING_FIELDS = ["stiffness", "damping", "mass", "velocity", "restDelta", "restSpeed", "bounce", "visualDuration"] as const
373
+
374
+ /** A spring's physics fields: one of them wins over its time (#359, Motion's `physicsKeys`). */
375
+ const PHYSICS_FIELDS = ["stiffness", "damping", "mass"] as const
376
+
377
+ /** A time-based spring's fields (#359): with no physics field, core solves its physics from them. */
378
+ const TIME_FIELDS = ["duration", "bounce", "visualDuration"] as const
379
+
380
+ /**
381
+ * The fields that don't define a transition, beside the orchestration's ({@link motionOf}): Motion's
382
+ * `isTransitionDefined` (at 16c6122) skips `delay`; Wardic's reduced-motion opt-out, `skipAnimations`
383
+ * (#468) and a target's `inherit` aren't a transition's either. `repeat` and its fields do define one, a tween (ADR-0051).
384
+ */
385
+ const NOT_DEFINING: ReadonlySet<string> = new Set(["delay", "respectReducedMotion", "skipAnimations", "inherit"])
386
+
387
+ /** Motion's spring defaults (`springDefaults`): what a spring transition leaves out (ADR-0051). */
388
+ const MOTION_SPRING = { stiffness: 100, damping: 10, mass: 1 } as const
389
+
390
+
391
+ /** A transition that defines nothing: its keys run on their Default transitions. */
392
+ const NOT_DEFINED: unique symbol = Symbol("wardic.notDefined")
393
+
394
+ /** Each transition as its legs run it, by the transition: one object each, so core's decode cache hits (#66). */
395
+ // Module state (#460, Q7): a cache held weakly by the object it's for, so it goes with it.
396
+ const RUNS = new WeakMap<object, Run | typeof NOT_DEFINED>()
397
+
398
+ /** A field a transition gives: set, and not an entry (#301). */
399
+ const isGiven = (value: unknown): boolean => Bool.and(Predicate.isNotUndefined(value), Bool.not(isEntry(value)))
400
+
401
+ /** Whether a field defines a transition. */
402
+ const isDefining = (key: string): boolean => Bool.not(NOT_DEFINING.has(key))
403
+
404
+ /** Whether a transition gives any of `keys`. */
405
+ const givesAny = (fields: Readonly<Record<string, unknown>>, keys: ReadonlyArray<string>): boolean => Arr.some(keys, (key) => Object.hasOwn(fields, key))
406
+
407
+ /** Whether a transition's fields make it a spring: `type: "spring"`, or no `type` and a spring field. */
408
+ // #672: core's lint (`BOOL_OPERANDS`), met before the move: the fields are read only with no `type`.
409
+ const isSpring = (fields: Readonly<Record<string, unknown>>): boolean => {
410
+ if (fields.type === "spring") return true
411
+ if (Predicate.isNotUndefined(fields.type)) return false
412
+ return givesAny(fields, SPRING_FIELDS)
413
+ }
414
+
415
+ /**
416
+ * Whether a spring transition is set by time (#359): a time field and no physics field. Its physics
417
+ * are core's to solve, so it takes none of Motion's defaults, which would win over its time.
418
+ */
419
+ const isTimed = (fields: Readonly<Record<string, unknown>>): boolean => Bool.and(givesAny(fields, TIME_FIELDS), Bool.not(givesAny(fields, PHYSICS_FIELDS)))
420
+
421
+ /** {@link runOf}'s work, once a transition: its given fields, and what they make. */
422
+ const madeRun = (given: Config.WardicTransition): Run | typeof NOT_DEFINED => {
423
+ const fields = Rec.filter(UndefinedOr.getOrThrow(motionOf(given)) as Readonly<Record<string, unknown>>, isGiven)
424
+ if (Bool.not(Arr.some(Rec.keys(fields), isDefining))) return NOT_DEFINED
425
+ // An inertia (#435): its fields as given, Motion's `timeConstant` in milliseconds as core's seconds.
426
+ if (fields.type === "inertia") {
427
+ return { ...fields, ...UndefinedOr.match(fields.timeConstant as number | undefined, { onUndefined: () => ({}), onDefined: (ms) => ({ timeConstant: ms / 1000 }) }) } as Run
428
+ }
429
+ return Bool.match(isSpring(fields), {
430
+ onTrue: (): Run =>
431
+ Bool.match(isTimed(fields), {
432
+ onTrue: (): Run => ({ ...fields, type: "spring" }) as Run,
433
+ onFalse: (): Run => ({ ...MOTION_SPRING, ...fields, type: "spring" }) as Run,
434
+ }),
435
+ onFalse: (): Run => ({ ease: Easing.easeOut, ...fields, type: "tween" }) as Run,
436
+ })
437
+ }
438
+
439
+ /**
440
+ * A transition as its legs run it (ADR-0051, #357), or `undefined` when it isn't defined: none, or
441
+ * one with only orchestration, `delay` and the reduced-motion opt-out (Motion's
442
+ * `isTransitionDefined`). A defined one:
443
+ * - is a spring when it says so, or gives no `type` and a spring field ({@link SPRING_FIELDS});
444
+ * anything else is a tween, as a layout animation's is (ADR-0009 *Amendment (#171)*): `{ duration:
445
+ * 0.5 }` a 0.5 s tween, as Motion's, where `{ stiffness: 300 }` stays a spring;
446
+ * - takes Motion's fields for those it leaves out: a spring's 100 / 10 / 1, a tween's `easeOut`
447
+ * (a tween's 0.3 s is core's too). A spring set by time, a `duration`, `bounce` or
448
+ * `visualDuration` and no stiffness, damping or mass (#359), takes no physics: core solves them.
449
+ *
450
+ * Worked out once per transition object. A field set to `undefined` gives nothing.
451
+ */
452
+ export const runOf = (given: Config.WardicTransition | undefined): Run | undefined => {
453
+ if (Predicate.isUndefined(given)) return undefined
454
+ let run = RUNS.get(given)
455
+ if (Predicate.isUndefined(run)) {
456
+ run = madeRun(given)
457
+ RUNS.set(given, run)
458
+ }
459
+ if (run === NOT_DEFINED) return undefined
460
+ return run
461
+ }
462
+
463
+ /** No keys: a Retarget with no following return. */
464
+ const NO_KEYS: ReadonlyArray<string> = []
465
+
466
+ /** Whether a value map has any key. */
467
+ const hasKeys: Predicate.Predicate<Values.Values> = Predicate.not(Rec.isEmptyRecord)
468
+
469
+ /**
470
+ * A Retarget's legs, in the order the spine starts them. Positional, as the spine calls it once a
471
+ * Retarget per element (#69's PR 2: what a Retarget allocates shows in `bench:solid`'s bytes).
472
+ *
473
+ * @param from each key's start
474
+ * @param to each key's target
475
+ * @param given the transition the legs run on, any stagger delay folded in (ADR-0007); its orchestration
476
+ * fields are left out ({@link motionOf})
477
+ * @param reducedMotion whether reduced motion is on (the provider's, ADR-0029); a transition can still opt out
478
+ * @param skipped whether its animations are skipped (#468, a `WardicConfig`'s `skipAnimations`): every key
479
+ * lands at its end on the first tick; a transition's `skipAnimations: true` does the same for its keys
480
+ * @param positionalKeys which keys are positional: the Environment's (ADR-0036)
481
+ * @param defaults what a key with no transition defined runs on: the Environment's (ADR-0051)
482
+ * @param velocities each key's velocity now (#464): a spring starts from it, unless its transition gives one
483
+ * @param follow the returns that follow a moving Live value (#130), given only when the Retarget returns a key
484
+ * @param stops each key's Keyframes of more than two stops (#429, {@link keyframesFrom}), `from` at their first
485
+ * @param measured each key's Measured pair (#430), measured at the end of the task
486
+ * @param current where every key is now: a Path's axis the target leaves out starts there (#438)
487
+ * @param rests where a Path's axis the target leaves out comes to rest, when a Path in flight was taking
488
+ * it somewhere (#574): it ends there; else where it starts
489
+ */
490
+ /** A Path's two axes (#438). */
491
+ const AXES = ["x", "y"] as const
492
+
493
+ /**
494
+ * A Retarget's keys with both of a Path's axes (#438): a Path couples `x` and `y`, so with either one
495
+ * retargeted, the other goes along it too, to its own target in `target`, though that hasn't changed
496
+ * and a Retarget otherwise keeps an unchanged key's Leg (#325). Without a Path, or neither axis, the
497
+ * keys as they are.
498
+ */
499
+ export const withPathAxes = (fresh: Values.Values, target: Values.Values, transition: Config.WardicTransition | undefined): Values.Values => {
500
+ if (Predicate.isUndefined(UndefinedOr.map(transition, (t) => t.path))) return fresh
501
+ if (Bool.not(Arr.some(AXES, (key) => Object.hasOwn(fresh, key)))) return fresh
502
+ const missing = Arr.filter(AXES, (key) => Bool.and(Bool.not(Object.hasOwn(fresh, key)), Object.hasOwn(target, key)))
503
+ if (missing.length === 0) return fresh
504
+ return { ...fresh, ...Rec.fromEntries(Arr.map(missing, (key) => [key, UndefinedOr.getOrThrow(target[key])] as const)) }
505
+ }
506
+
507
+ /** `key`'s number: from `values`, else from `current`, else its identity, 0; `undefined` for a string. */
508
+ const axisOf = (key: string, values: Values.Values, current: Values.Values | undefined): number | undefined => {
509
+ const given = values[key]
510
+ if (Predicate.isNumber(given)) return given
511
+ if (Predicate.isNotUndefined(given)) return undefined
512
+ const now = UndefinedOr.map(current, (all) => all[key])
513
+ if (Predicate.isNumber(now)) return now
514
+ if (Predicate.isNotUndefined(now)) return undefined
515
+ return 0
516
+ }
517
+
518
+ /**
519
+ * `x` and `y` along a Path (#438, Motion's `path`): one progress, 0 to 1, on the transition `x` runs
520
+ * on, from rest, as Motion's `{ velocity: 0, ...getValueTransition(transition, "x") }`; a spring's over
521
+ * 1000, as a layout animation's, so its rest thresholds read as at that distance (#344). Its frames
522
+ * write both axes, and the path's turn (`pathRotation`) when it has one; its last, the targets and no turn.
523
+ */
524
+ const pathLegOf = (at: (t: number) => Arc.PathPoint, end: Values.Values, transition: Run): Blend => ({
525
+ _tag: "Blend",
526
+ to: end,
527
+ machine: () =>
528
+ Effect.succeed(
529
+ Machine.make({
530
+ settles: Bool.or(transition.type === "spring", Number.isFinite(UndefinedOr.match((transition as Machine.Modifiers).repeat, { onUndefined: () => 0, onDefined: identity }))),
531
+ span: { name: "wardic.path", attributes: { rotates: Object.hasOwn(end, "pathRotation") } },
532
+ start: () => {
533
+ const progress = progressOf(transition)
534
+ const turns = Object.hasOwn(end, "pathRotation")
535
+ return (dt): Frame.Frame<Values.Values> => {
536
+ const frame = progress(dt)
537
+ if (frame.done) return { value: end, done: true }
538
+ const point = at(frame.value)
539
+ if (turns) return { value: { x: point.x, y: point.y, pathRotation: UndefinedOr.match(point.rotate, { onUndefined: () => 0, onDefined: identity }) }, done: false }
540
+ return { value: { x: point.x, y: point.y }, done: false }
541
+ }
542
+ },
543
+ }),
544
+ ),
545
+ })
546
+
547
+ /** A Path's progress, 0 to 1, on `transition`: a spring's from rest over 1000 (#438), a tween's as a Measured pair's. */
548
+ const progressOf = (transition: Run): ((dt: number) => Frame.Frame<number>) => {
549
+ if (transition.type === "spring") {
550
+ // Its one key read by index (#663).
551
+ const spring = Machine.springValues({ progress: 1000 }, { ...(transition as Machine.SpringOptions), velocity: 0 }, { from: { progress: 0 }, records: "value" }).start()
552
+ return (dt) => {
553
+ const frame = spring(dt)
554
+ return { value: frame.positions[0] / 1000, done: frame.done }
555
+ }
556
+ }
557
+ return Machine.keyframes([0, 1], transition as Machine.KeyframesOptions).start()
558
+ }
559
+
560
+ /**
561
+ * A Retarget's Path (#438): when its transition has one and its target has `x` or `y`, their leg along
562
+ * it, from where they are (an axis it leaves out from where it is now, `current`), on the transition `x`
563
+ * runs on; and the target without them. An axis it leaves out ends where it rests (#574): where the Path
564
+ * in flight was taking it, in `rests`, so a toss caught mid-air curves back to its line; else back where
565
+ * it starts, as Motion's `yTo = yRaw ?? yFrom`. `undefined` when there's none to take: no
566
+ * Path or no axis, reduced motion snapping them, a Skipped animation, an inertia, an axis that isn't a
567
+ * number. Keyframes' ends are their first and last stops.
568
+ */
569
+ const pathOf = (
570
+ from: Values.Values,
571
+ to: Values.Values,
572
+ given: Config.WardicTransition | undefined,
573
+ reducedMotion: boolean,
574
+ skipped: boolean,
575
+ defaults: DefaultTransition.DefaultTransition["Service"],
576
+ stops: StopsByKey | undefined,
577
+ current: Values.Values | undefined,
578
+ rests: Values.Values | undefined,
579
+ ): { readonly leg: Blend; readonly rest: Values.Values } | undefined => {
580
+ // Every element's Retarget asks, nearly always with no `path` (#460): guards, nothing built.
581
+ if (Predicate.isUndefined(given)) return undefined
582
+ const path = given.path
583
+ if (Predicate.isUndefined(path)) return undefined
584
+ if (Bool.not(Arr.some(AXES, (key) => Object.hasOwn(to, key)))) return undefined
585
+ if (Bool.or(skipped, UndefinedOr.map(given, (t) => t.skipAnimations) === true)) return undefined
586
+ // `x`'s transition, as a key's: its own entry (#301), else the transition's, else its Default (ADR-0051).
587
+ const runsOn = UndefinedOr.match(entriesOf(given), { onUndefined: () => given, onDefined: (entries) => forKey(entries, "x") })
588
+ const run = UndefinedOr.match(runOf(runsOn), { onUndefined: () => carried(defaultFor(defaults, "x", to, stops), runsOn), onDefined: identity })
589
+ if (run.type === "inertia") return undefined
590
+ // Reduced motion snaps the positional keys, the axes among them (ADR-0029), unless it opts out.
591
+ if (Bool.and(reducedMotion, run.respectReducedMotion !== false)) return undefined
592
+ const startX = axisOf("x", from, current)
593
+ if (Predicate.isUndefined(startX)) return undefined
594
+ const startY = axisOf("y", from, current)
595
+ if (Predicate.isUndefined(startY)) return undefined
596
+ // An axis the target leaves out ends where it rests (#574), else where it starts.
597
+ const resting: Values.Values = { x: startX, y: startY, ...rests }
598
+ const endX = axisOf("x", to, resting)
599
+ if (Predicate.isUndefined(endX)) return undefined
600
+ const endY = axisOf("y", to, resting)
601
+ if (Predicate.isUndefined(endY)) return undefined
602
+ const at = path({ x: startX, y: startY }, { x: endX, y: endY })
603
+ // A path that turns the element says so at its start, as Motion's `interpolate(0).rotate`.
604
+ const end: Values.Values = Bool.match(Predicate.isUndefined(at(0).rotate), {
605
+ onTrue: () => ({ x: endX, y: endY }),
606
+ onFalse: () => ({ x: endX, y: endY, pathRotation: 0 }),
607
+ })
608
+ return { leg: pathLegOf(at, end, run), rest: Rec.filter(to, (_, key) => Bool.not(Arr.contains(AXES, key as "x"))) }
609
+ }
610
+
611
+ export const legsOf = (
612
+ from: Values.Values,
613
+ to: Values.Values,
614
+ given: Config.WardicTransition | undefined,
615
+ reducedMotion: boolean,
616
+ skipped: boolean,
617
+ positionalKeys: ReducedMotion.PositionalKeys["Service"],
618
+ defaults: DefaultTransition.DefaultTransition["Service"],
619
+ velocities: Velocities,
620
+ follow?: Follows | undefined,
621
+ stops?: StopsByKey | undefined,
622
+ measured?: MeasuredPairs | undefined,
623
+ current?: Values.Values | undefined,
624
+ rests?: Values.Values | undefined,
625
+ ): ReadonlyArray<Leg> => {
626
+ // A Path (#438): `x` and `y` along it, on a leg of their own, and every other key as before.
627
+ const pathed = pathOf(from, to, given, reducedMotion, skipped, defaults, stops, current, rests)
628
+ if (Predicate.isNotUndefined(pathed)) {
629
+ return Arr.prepend(legsOf(from, pathed.rest, given, reducedMotion, skipped, positionalKeys, defaults, velocities, follow, stops, measured), pathed.leg)
630
+ }
631
+ // Each key on its own transition (#301): with entries, the keys go by the transition each runs on.
632
+ const entries = entriesOf(given)
633
+ if (Predicate.isUndefined(entries)) return legsOn(from, to, given, reducedMotion, skipped, positionalKeys, defaults, velocities, follow, stops, measured)
634
+ // With no value's entry (`layout` and `default` alone), every key runs on one transition.
635
+ if (Bool.not(entries.byValue)) return legsOn(from, to, forKey(entries, "default"), reducedMotion, skipped, positionalKeys, defaults, velocities, follow, stops, measured)
636
+ const byTransition = new Map<Config.WardicTransition, Record<string, number | string>>()
637
+ Arr.forEach(Rec.keys(to), (key) => {
638
+ const runsOn = forKey(entries, key)
639
+ const keys = byTransition.get(runsOn)
640
+ if (Predicate.isNotUndefined(keys)) {
641
+ keys[key] = to[key] as number | string
642
+ return
643
+ }
644
+ byTransition.set(runsOn, { [key]: to[key] as number | string })
645
+ })
646
+ return Arr.flatMap(Arr.fromIterable(byTransition), ([runsOn, keys]) => legsOn(from, keys, runsOn, reducedMotion, skipped, positionalKeys, defaults, velocities, follow, stops, measured))
647
+ }
648
+
649
+ /** No legs: a Retarget with no key. */
650
+ const NO_LEGS: ReadonlyArray<Leg> = []
651
+
652
+ /** Each key's Measured pair (#430), by its key. */
653
+ export type MeasuredPairs = Readonly<Record<string, CoreMeasuredPairs.Requested>>
654
+
655
+ /** Whether any key of `values` is a Measured pair (#430): per Retarget, so nothing made. */
656
+ const anyMeasured = (values: Values.Values, measured: MeasuredPairs | undefined): boolean => {
657
+ if (Predicate.isUndefined(measured)) return false
658
+ return Rec.some(values, (_, key) => Object.hasOwn(measured, key))
659
+ }
660
+
661
+ /**
662
+ * Measured pairs' leg (#430): their ends in px, read at its first step, which comes a tick after the
663
+ * end-of-task batch that measures them. A tween runs a 0 → 1 progress (`keyframes`' options, so
664
+ * `times`, an `ease` per Interval and the Modifiers apply), a spring the px. Its last frame writes each
665
+ * target as given (`"auto"`, `"50%"`), as Motion's `finalKeyframe`, or each start as given when a turned
666
+ * `repeat` ends it there. A pair its batch couldn't read switches, as a Discrete pair does.
667
+ */
668
+ const measuredLegOf = (pairs: MeasuredPairs, transition: Run): Blend => {
669
+ const to = Rec.map(pairs, (pair) => pair.to)
670
+ return { _tag: "Blend", to, machine: () => Effect.succeed(measuredMachine(pairs, to, transition)) }
671
+ }
672
+
673
+ /** {@link measuredLegOf}'s machine: its step made at the first step, once the pairs are measured. */
674
+ const measuredMachine = (pairs: MeasuredPairs, to: Values.Values, transition: Run): Machine.Machine<Frame.Frame<Values.Values>> =>
675
+ Machine.make({
676
+ settles: Bool.or(transition.type === "spring", Number.isFinite(UndefinedOr.match((transition as Machine.Modifiers).repeat, { onUndefined: () => 0, onDefined: identity }))),
677
+ span: { name: "wardic.measured", attributes: { keys: Rec.keys(pairs).length } },
678
+ start: () => {
679
+ let step: ((dt: number) => Frame.Frame<Values.Values>) | undefined
680
+ return (dt) => {
681
+ if (Predicate.isUndefined(step)) step = measuredStep(pairs, to, transition)
682
+ return step(dt)
683
+ }
684
+ },
685
+ })
686
+
687
+ /** A pair's ends in px, as its Environment measured them (#672): its own read. Built once (#460). */
688
+ const measuredOf = (pair: CoreMeasuredPairs.Requested): Option.Option<CoreMeasuredPairs.Measured> => pair.measured()
689
+
690
+ /** {@link measuredMachine}'s step, its pairs measured, or a switch when its batch couldn't read one. Per frame: one Frame a step. */
691
+ const measuredStep = (pairs: MeasuredPairs, to: Values.Values, transition: Run): ((dt: number) => Frame.Frame<Values.Values>) => {
692
+ const all = Option.all(Rec.map(pairs, measuredOf))
693
+ if (Option.isNone(all)) return () => ({ value: to, done: true })
694
+ const fromPx = Rec.map(all.value, (pair) => pair.fromPx)
695
+ const toPx = Rec.map(all.value, (pair) => pair.toPx)
696
+ if (transition.type === "spring") {
697
+ const spring = Machine.springValues(toPx, transition as Machine.SpringOptions, { from: fromPx }).start()
698
+ return (dt) => {
699
+ const frame = spring(dt)
700
+ if (frame.done) return { value: to, done: true }
701
+ return { value: frame.value, done: false }
702
+ }
703
+ }
704
+ const options = transition as Machine.KeyframesOptions
705
+ const progress = Machine.keyframes([0, 1], options).start()
706
+ // A turned `repeat` can end it at its start (`ReducedMotion.endOf`): the starts as given then.
707
+ const end = Bool.match(ReducedMotion.endOf(false, true, options), { onTrue: () => to, onFalse: () => Rec.map(pairs, (pair) => pair.from) })
708
+ return (dt) => {
709
+ const frame = progress(dt)
710
+ if (frame.done) return { value: end, done: true }
711
+ return { value: Rec.map(fromPx, (start, key) => start + (UndefinedOr.getOrThrow(toPx[key]) - start) * frame.value), done: false }
712
+ }
713
+ }
714
+
715
+ /** No numbers: a spring whose transition gives every key its velocity (#464). */
716
+ const NO_NUMBERS: Record<string, number> = {}
717
+
718
+ /** No values: the failed leg of Keyframes on a spring draws none (#429). */
719
+ const NO_VALUES: Values.Values = {}
720
+
721
+ /** Whether `key` has Keyframes of more than two stops in `stops` (#429): none without any. */
722
+ const hasStops = (stops: StopsByKey | undefined, key: string): boolean => {
723
+ if (Predicate.isUndefined(stops)) return false
724
+ return Object.hasOwn(stops, key)
725
+ }
726
+
727
+ /** Whether any key of `values` has Keyframes of more than two stops (#429): per Retarget, so nothing made. */
728
+ const anyKeyframed = (values: Values.Values, stops: StopsByKey | undefined): boolean => {
729
+ if (Predicate.isUndefined(stops)) return false
730
+ return Rec.some(values, (_, key) => Object.hasOwn(stops, key))
731
+ }
732
+
733
+ /** Each key's stops (#429): its Keyframes', or its start and target. */
734
+ const stopsFor = (from: Values.Values, to: Values.Values, stops: StopsByKey | undefined): StopsByKey =>
735
+ Rec.map(to, (target, key): ReadonlyArray<number | string> => {
736
+ if (hasStops(stops, key)) return (stops as StopsByKey)[key] as ReadonlyArray<number | string>
737
+ return [UndefinedOr.getOrThrow(from[key]), target]
738
+ })
739
+
740
+ /**
741
+ * {@link legsOf} on one transition: as it runs, or, when it defines none, each key on its Default
742
+ * transition (ADR-0051), the keys that share one on one leg's worth.
743
+ */
744
+ const legsOn = (
745
+ from: Values.Values,
746
+ to: Values.Values,
747
+ given: Config.WardicTransition | undefined,
748
+ reducedMotion: boolean,
749
+ skipped: boolean,
750
+ positionalKeys: ReducedMotion.PositionalKeys["Service"],
751
+ defaults: DefaultTransition.DefaultTransition["Service"],
752
+ velocities: Velocities,
753
+ follow: Follows | undefined,
754
+ stops: StopsByKey | undefined,
755
+ measured: MeasuredPairs | undefined,
756
+ ): ReadonlyArray<Leg> => {
757
+ const run = runOf(given)
758
+ if (Predicate.isNotUndefined(run)) {
759
+ if (run.type === "inertia") return inertiaLegsOn(from, to, run as Run & InertiaRun, given, reducedMotion, skipped, positionalKeys, defaults, velocities, follow, stops, measured)
760
+ return legsWith(from, to, run, reducedMotion, skipped, positionalKeys, velocities, follow, stops, measured)
761
+ }
762
+ const keys = Rec.keys(to)
763
+ if (keys.length === 0) return NO_LEGS
764
+ // Nearly always one Default transition for every key (a fade, a move): no grouping.
765
+ const first = defaultFor(defaults, UndefinedOr.getOrThrow(keys[0]), to, stops)
766
+ if (Arr.every(keys, (key) => defaultFor(defaults, key, to, stops) === first)) {
767
+ return legsWith(from, to, carried(first, given), reducedMotion, skipped, positionalKeys, velocities, follow, stops, measured)
768
+ }
769
+ const byDefault = new Map<DefaultTransition.Transition | DefaultTransition.KeyframesTransition, Record<string, number | string>>()
770
+ Arr.forEach(keys, (key) => {
771
+ const runsOn = defaultFor(defaults, key, to, stops)
772
+ const grouped = byDefault.get(runsOn)
773
+ if (Predicate.isNotUndefined(grouped)) {
774
+ grouped[key] = to[key] as number | string
775
+ return
776
+ }
777
+ byDefault.set(runsOn, { [key]: to[key] as number | string })
778
+ })
779
+ return Arr.flatMap(Arr.fromIterable(byDefault), ([runsOn, grouped]) => legsWith(from, grouped, carried(runsOn, given), reducedMotion, skipped, positionalKeys, velocities, follow, stops, measured))
780
+ }
781
+
782
+ /**
783
+ * The Default transition `key` runs on (ADR-0051): its Environment's for it, toward its target, or,
784
+ * through Keyframes of more than two stops, its Environment's keyframes one (#429, Motion's).
785
+ */
786
+ const defaultFor = (
787
+ defaults: DefaultTransition.DefaultTransition["Service"],
788
+ key: string,
789
+ to: Values.Values,
790
+ stops: StopsByKey | undefined,
791
+ ): DefaultTransition.Transition | DefaultTransition.KeyframesTransition => {
792
+ if (hasStops(stops, key)) return defaults.keyframes
793
+ return defaults.transitionFor(key, to[key] as number | string)
794
+ }
795
+
796
+ /**
797
+ * A Default transition with what the transition that defines none still says: its `delay` (a
798
+ * stagger's among it, ADR-0007), its reduced-motion opt-out and its `skipAnimations` (#468). The
799
+ * Default transition itself when it says none, as nearly every element's (it has no transition).
800
+ */
801
+ const carried = (runsOn: DefaultTransition.Transition | DefaultTransition.KeyframesTransition, given: Config.WardicTransition | undefined): Run => {
802
+ if (Predicate.isUndefined(given)) return runsOn
803
+ const { delay, respectReducedMotion, skipAnimations } = given
804
+ // Per Retarget (#460): statements.
805
+ if (Predicate.isUndefined(delay) && Predicate.isUndefined(respectReducedMotion) && Predicate.isUndefined(skipAnimations)) return runsOn
806
+ return { ...runsOn, ...Rec.filter({ delay, respectReducedMotion, skipAnimations }, Predicate.isNotUndefined) } as Run
807
+ }
808
+
809
+ /** The keys reduced motion snaps (ADR-0029), when it applies; else none, every key animating. */
810
+ const reducedSplitOf = (to: Values.Values, applies: boolean, positionalKeys: ReducedMotion.PositionalKeys["Service"]): ReducedMotion.Split => {
811
+ if (applies) return ReducedMotion.split(to, positionalKeys)
812
+ return { positional: {}, rest: to }
813
+ }
814
+
815
+ /** {@link legsOf} on one transition as it runs. */
816
+ const legsWith = (
817
+ from: Values.Values,
818
+ to: Values.Values,
819
+ transition: Run,
820
+ reducedMotion: boolean,
821
+ skipped: boolean,
822
+ positionalKeys: ReducedMotion.PositionalKeys["Service"],
823
+ velocities: Velocities,
824
+ follow: Follows | undefined,
825
+ stops: StopsByKey | undefined,
826
+ measured: MeasuredPairs | undefined,
827
+ ): ReadonlyArray<Leg> => {
828
+ // A **Skipped animation** (#468, Motion's `skipAnimations`): every key lands where its leg would end,
829
+ // on its first tick, with no delay and whatever reduced motion says. Keyframes land on their last
830
+ // stop, a turned `repeat` where it ends, a Measured pair on its target as given, and a return to a
831
+ // moving Live value on where it is now, its follower taking over once it lands.
832
+ // Per Retarget (#460, compose once): statements.
833
+ if (skipped || transition.skipAnimations === true) return [snapLeg(from, to, Rec.map(to, (target, key) => endOfLeg(from, target, key, transition, velocities)), NO_DELAY)]
834
+ // An inertia's numbers (#435): its other keys went to their Default transitions ({@link inertiaLegsOn}).
835
+ if (transition.type === "inertia") return inertiaLegsWith(from, to, transition as InertiaRun, reducedMotion, positionalKeys, velocities, stops)
836
+ const useTween = transition.type === "tween"
837
+ // Reduced motion (ADR-0029): the positional keys snap to where their leg would end, holding
838
+ // through the delay it would hold, and the rest animate as they would. A transition opts out with
839
+ // `respectReducedMotion: false`.
840
+ const respects = transition.respectReducedMotion !== false
841
+ const { positional, rest } = reducedSplitOf(to, respects && reducedMotion, positionalKeys)
842
+ const snapping = hasKeys(positional)
843
+ let followingKeys = NO_KEYS
844
+ if (Predicate.isNotUndefined(follow)) followingKeys = follow.keysOf(rest)
845
+ const following = followingKeys.length > 0
846
+ let fixed = rest
847
+ if (following) fixed = Rec.filter(rest, (_, key) => !Arr.contains(followingKeys, key))
848
+ // Built a leg at a time, once a Retarget (#69's PR 2: a Retarget is per element, so no spreads).
849
+ const legs: Array<Leg> = []
850
+ // Measured pairs (#430): a leg of their own, between their ends in px, on this transition.
851
+ const measuring = anyMeasured(fixed, measured)
852
+ if (measuring) {
853
+ const kept = fixed
854
+ const pairs = Rec.filter(measured as MeasuredPairs, (_, key) => Object.hasOwn(kept, key))
855
+ legs.push(measuredLegOf(pairs, transition))
856
+ fixed = Rec.filter(kept, (_, key) => !Object.hasOwn(pairs, key))
857
+ }
858
+ if (useTween) {
859
+ // Its options as they are: a missing `duration` is core's 0.3 s, and the rest still apply (#107).
860
+ const options = transition as Machine.KeyframesOptions
861
+ // A tween's snap lands where the tween would end: `repeat` and `reverse` can end it at `from`, a
862
+ // Keyframes key's first stop (#429). Its delay alone is read: an `ease` per Interval isn't a tween's.
863
+ if (snapping) {
864
+ legs.push(snapLeg(from, positional, Rec.map(positional, (to, key) => ReducedMotion.endOf(UndefinedOr.getOrThrow(from[key]), to, options)), () => Machine.resolveTween(Rec.filter({ delay: options.delay }, Predicate.isNotUndefined)).delay))
865
+ }
866
+ // A following return eases toward where its Live value is each frame, so it lands on it.
867
+ if (following) Arr.forEach(followingKeys, (key) => {
868
+ const start = from[key] as number
869
+ const target = UndefinedOr.getOrThrow(follow).targetOf(key, start)
870
+ legs.push({
871
+ _tag: "Follow",
872
+ key,
873
+ to: { [key]: UndefinedOr.getOrThrow(rest[key]) },
874
+ machine: () =>
875
+ Machine.map(Machine.animate(0, 1, options as Machine.AnimateOptions), (progress) => ({
876
+ value: start + (target() - start) * progress.value,
877
+ done: progress.done,
878
+ })),
879
+ })
880
+ })
881
+ // With every key snapped, following or measured, there's nothing left to tween.
882
+ if ((!snapping && !following && !measuring) || hasKeys(fixed)) {
883
+ // A key's Keyframes, or `times` or an `ease` per Interval, run every key through `keyframesValues`
884
+ // (#429), on one run, a target as its two stops.
885
+ if (anyKeyframed(fixed, stops) || keyframedOptions(options)) {
886
+ legs.push({ _tag: "Blend", to: fixed, machine: () => Machine.keyframesValues(stopsFor(from, fixed, stops), options) })
887
+ return legs
888
+ }
889
+ legs.push({ _tag: "Blend", to: fixed, machine: () => Machine.animateValues(Values.pick(from, fixed), fixed, options as Machine.AnimateOptions) })
890
+ }
891
+ return legs
892
+ }
893
+ // Spring (default): numeric keys via springValues (velocity-carrying Retarget); any string/colour
894
+ // keys via springBlend, the same spring on a 0→100 progress (ADR-0024, D5).
895
+ const springOpts = transition as Machine.SpringOptions
896
+ // Keyframes of more than two stops on a spring (#429): Motion's error, a leg that fails as it's
897
+ // built, and each such key snapped to its last stop.
898
+ if (anyKeyframed(fixed, stops)) {
899
+ const kept = fixed
900
+ const many = Rec.filter(stops as StopsByKey, (_, key) => Object.hasOwn(kept, key))
901
+ const ends = Rec.filter(kept, (_, key) => Object.hasOwn(many, key))
902
+ legs.push(snapLeg(from, ends, ends, () => Spring.resolve(springOpts).delay))
903
+ legs.push({ _tag: "Blend", to: NO_VALUES, machine: () => Effect.die(springStopsError(many)) })
904
+ fixed = Rec.filter(kept, (_, key) => !Object.hasOwn(many, key))
905
+ }
906
+ const { numbers: numeric, strings } = Values.split(fixed)
907
+ // A spring settles at its target: the snap lands there.
908
+ if (snapping) legs.push(snapLeg(from, positional, positional, () => Spring.resolve(springOpts).delay))
909
+ // A following return chases its Live value, read each step, and settles at rest on it.
910
+ if (following) Arr.forEach(followingKeys, (key) => {
911
+ const start = from[key] as number
912
+ let velocity = springOpts.velocity
913
+ if (Predicate.isUndefined(velocity)) velocity = velocities(key)
914
+ const chase = Machine.chase(UndefinedOr.getOrThrow(follow).targetOf(key, start), { ...springOpts, from: start, velocity })
915
+ legs.push({ _tag: "Follow", key, to: { [key]: UndefinedOr.getOrThrow(rest[key]) }, machine: () => settling(chase) })
916
+ })
917
+ if (hasKeys(numeric)) {
918
+ const fromNumeric: Record<string, number> = Rec.map(numeric, (_, key) => from[key] as number)
919
+ // Each key's own velocity, read now; none when the transition gives one, which every key then starts with.
920
+ let fromVelocity: Record<string, number> = NO_NUMBERS
921
+ if (Predicate.isUndefined(springOpts.velocity)) fromVelocity = Rec.map(numeric, (_, key) => velocities(key))
922
+ legs.push({ _tag: "Numbers", to: numeric, machine: () => Machine.springValues(numeric, springOpts, { from: fromNumeric, velocity: fromVelocity, records: "value" }) })
923
+ }
924
+ if (hasKeys(strings)) {
925
+ const fromStrings: Values.Values = Rec.map(strings, (_, key) => UndefinedOr.getOrThrow(from[key]))
926
+ legs.push({ _tag: "Blend", to: strings, machine: () => Machine.springBlend(fromStrings, strings, springOpts) })
927
+ }
928
+ return legs
929
+ }
930
+
931
+ /** What a leg's machine can be run through: the same Frames, stepped another way. */
932
+ export type MachineMap = <F extends Frame.Frame<unknown>>(machine: Machine.Machine<F>) => Machine.Machine<F>
933
+
934
+ /**
935
+ * `leg` with its machine run through `f`: started partway ({@link startingAt}), or through an
936
+ * **Imperative animation**'s Playhead (#433, `Playback.drive`).
937
+ */
938
+ export const mapMachine = (leg: Leg, f: MachineMap): Leg => mapMachineMatch({ leg, f })
939
+
940
+ /** {@link mapMachine}'s cases, built once at module load: it runs per element at hydration (#69's PR 2). */
941
+ const mapMachineMatch: (input: { readonly leg: Leg; readonly f: MachineMap }) => Leg = Match.type<{ readonly leg: Leg; readonly f: MachineMap }>().pipe(
942
+ Match.when({ leg: { _tag: "Blend" } }, ({ leg, f }): Leg => ({ ...leg, machine: () => Effect.map(leg.machine(), f) })),
943
+ Match.orElse(({ leg, f }): Leg => {
944
+ const plain = leg as Exclude<Leg, Blend>
945
+ return { ...plain, machine: () => f(plain.machine() as Machine.Machine<Frame.Frame<unknown>>) } as Leg
946
+ }),
947
+ )
948
+
949
+ /**
950
+ * `leg`, started `at()` seconds in (`Machine.startAt`): a Handoff's first legs, which pick up an
951
+ * Appear animation where it has got (#48, ADR-0044 decision 6).
952
+ */
953
+ export const startingAt = (leg: Leg, at: LazyArg<number>): Leg => mapMachine(leg, Machine.startAt(at))
954
+
955
+ /**
956
+ * Where `key`'s leg would end (#468): an inertia's where its glide rests (#435, `Inertia.restOf`), from
957
+ * its velocity, whatever its target; any other's at its target, or where a turned `repeat` ends.
958
+ */
959
+ const endOfLeg = (from: Values.Values, target: number | string, key: string, transition: Run, velocities: Velocities): number | string => {
960
+ const start = UndefinedOr.getOrThrow(from[key])
961
+ if (transition.type !== "inertia") return ReducedMotion.endOf(start, target, transition as Machine.Modifiers)
962
+ return Inertia.restOf(start as number, inertiaVelocityOf(transition as InertiaRun, velocities, key), transition as InertiaRun)
963
+ }
964
+
965
+ /** A key's velocity under an inertia (#435): the transition's `velocity`, else its own (#464). */
966
+ const inertiaVelocityOf = (run: InertiaRun, velocities: Velocities, key: string): number =>
967
+ UndefinedOr.match(run.velocity, { onUndefined: () => velocities(key), onDefined: identity })
968
+
969
+ /**
970
+ * {@link legsOf} on an inertia (#435, Q2): the numbers glide on it ({@link inertiaLegsWith}); every
971
+ * other key, and a return following a moving Live value, runs on its Default transition, as if the
972
+ * transition defined none for it, its `delay`, reduced-motion opt-out and `skipAnimations` kept.
973
+ */
974
+ const inertiaLegsOn = (
975
+ from: Values.Values,
976
+ to: Values.Values,
977
+ run: Run & InertiaRun,
978
+ given: Config.WardicTransition | undefined,
979
+ reducedMotion: boolean,
980
+ skipped: boolean,
981
+ positionalKeys: ReducedMotion.PositionalKeys["Service"],
982
+ defaults: DefaultTransition.DefaultTransition["Service"],
983
+ velocities: Velocities,
984
+ follow: Follows | undefined,
985
+ stops: StopsByKey | undefined,
986
+ measured: MeasuredPairs | undefined,
987
+ ): ReadonlyArray<Leg> => {
988
+ let followingKeys = NO_KEYS
989
+ if (Predicate.isNotUndefined(follow)) followingKeys = follow.keysOf(to)
990
+ const glides = (target: number | string, key: string): boolean =>
991
+ Bool.and(Bool.and(Predicate.isNumber(target), Predicate.isNumber(from[key])), Bool.not(Arr.contains(followingKeys, key)))
992
+ const numbers = Rec.filter(to, glides)
993
+ const rest = Rec.filter(to, (target, key) => Bool.not(glides(target, key)))
994
+ const legs: Array<Leg> = []
995
+ if (hasKeys(numbers)) Arr.forEach(legsWith(from, numbers, run, reducedMotion, skipped, positionalKeys, velocities, undefined, stops, undefined), (leg) => legs.push(leg))
996
+ if (hasKeys(rest)) Arr.forEach(legsOn(from, rest, definingNone(given), reducedMotion, skipped, positionalKeys, defaults, velocities, follow, stops, measured), (leg) => legs.push(leg))
997
+ return legs
998
+ }
999
+
1000
+ /** A transition's fields that define none: its `delay`, reduced-motion opt-out and `skipAnimations`, on a Default transition. */
1001
+ const definingNone = (given: Config.WardicTransition | undefined): Config.WardicTransition | undefined =>
1002
+ UndefinedOr.map(given, ({ delay, respectReducedMotion, skipAnimations }) => Rec.filter({ delay, respectReducedMotion, skipAnimations }, Predicate.isNotUndefined) as Config.WardicTransition)
1003
+
1004
+ /**
1005
+ * An inertia's legs over numbers (#435): each glides from where it is at its velocity, on
1006
+ * `Machine.inertiaValues`, whatever its target. Under reduced motion its positional keys land where
1007
+ * their glides rest, after its delay (ADR-0029); Keyframes of more than two stops fail, as a spring's
1008
+ * (#429, Motion's two-keyframe invariant), each such key landing on its last stop.
1009
+ */
1010
+ const inertiaLegsWith = (
1011
+ from: Values.Values,
1012
+ to: Values.Values,
1013
+ run: InertiaRun,
1014
+ reducedMotion: boolean,
1015
+ positionalKeys: ReducedMotion.PositionalKeys["Service"],
1016
+ velocities: Velocities,
1017
+ stops: StopsByKey | undefined,
1018
+ ): ReadonlyArray<Leg> => {
1019
+ const legs: Array<Leg> = []
1020
+ const delay = (): number => UndefinedOr.match(run.delay, { onUndefined: () => 0, onDefined: identity })
1021
+ let fixed = to
1022
+ if (anyKeyframed(fixed, stops)) {
1023
+ const kept = fixed
1024
+ const many = Rec.filter(stops as StopsByKey, (_, key) => Object.hasOwn(kept, key))
1025
+ const ends = Rec.filter(kept, (_, key) => Object.hasOwn(many, key))
1026
+ legs.push(snapLeg(from, ends, ends, delay))
1027
+ legs.push({ _tag: "Blend", to: NO_VALUES, machine: () => Effect.die(springStopsError(many, "an inertia")) })
1028
+ fixed = Rec.filter(kept, (_, key) => !Object.hasOwn(many, key))
1029
+ }
1030
+ if (Bool.and(reducedMotion, (run as Run).respectReducedMotion !== false)) {
1031
+ const { positional, rest } = ReducedMotion.split(fixed, positionalKeys)
1032
+ if (hasKeys(positional)) {
1033
+ legs.push(snapLeg(from, positional, Rec.map(positional, (_, key) => Inertia.restOf(from[key] as number, inertiaVelocityOf(run, velocities, key), run)), delay))
1034
+ }
1035
+ fixed = rest
1036
+ }
1037
+ if (hasKeys(fixed)) {
1038
+ const starts: Record<string, number> = Rec.map(fixed, (_, key) => from[key] as number)
1039
+ // Each key's own velocity, read now (#464); none when the transition gives one, which every key then starts with.
1040
+ const own: Record<string, number> = Bool.match(Predicate.isUndefined(run.velocity), {
1041
+ onTrue: () => Rec.map(fixed, (_, key) => velocities(key)),
1042
+ onFalse: () => NO_NUMBERS,
1043
+ })
1044
+ legs.push({ _tag: "Numbers", to: fixed, machine: () => Machine.inertiaValues(starts, run, { velocity: own }) })
1045
+ }
1046
+ return legs
1047
+ }
1048
+
1049
+ /** No delay: a Skipped animation's snap (#468). */
1050
+ const NO_DELAY = (): number => 0
1051
+
1052
+ /** The snap's leg: the positional keys, from where they are to `to`, after `delay()`. */
1053
+ const snapLeg = (from: Values.Values, positional: Values.Values, to: Values.Values, delay: () => number): Snap => ({
1054
+ _tag: "Snap",
1055
+ keys: Rec.keys(positional),
1056
+ to: positional,
1057
+ machine: () => ReducedMotion.snap(Values.pick(from, positional), to, { delay: delay() }),
1058
+ })
1059
+
1060
+ /** `chase`, ending at its first Frame at rest on its target: a return to a moving Live value (#130). */
1061
+ const settling = <F extends Frame.Frame<unknown>>(chase: Machine.Machine<F>): Machine.Machine<F> =>
1062
+ Machine.make({ start: chase.start, settles: true, span: chase.span })