@wardic/core 1.2.0 → 1.3.0

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