@wardic/dom 1.2.0 → 1.3.1

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