@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,745 @@
1
+ import * as InterpolatorRegistry from "../InterpolatorRegistry.js";
2
+ import * as Machine from "../Machine.js";
3
+ import * as Playback from "../Playback.js";
4
+ import * as ReducedMotion from "../ReducedMotion.js";
5
+ import * as Sequence from "../Sequence.js";
6
+ import * as Report from "./Report.js";
7
+ import * as RetargetLegs from "./RetargetLegs.js";
8
+ import * as Spine from "./Spine.js";
9
+ import * as VariantTarget from "./VariantTarget.js";
10
+ import * as VariantTree from "./VariantTree.js";
11
+ import * as Arr from "effect/Array";
12
+ import * as Bool from "effect/Boolean";
13
+ import * as Cause from "effect/Cause";
14
+ import * as Effect from "effect/Effect";
15
+ import * as Exit from "effect/Exit";
16
+ import { constVoid, identity } from "effect/Function";
17
+ import * as Predicate from "effect/Predicate";
18
+ import * as Rec from "effect/Record";
19
+ import * as UndefinedOr from "effect/UndefinedOr";
20
+ /** Each mounted Wardic element's spine (Motion's `visualElementStore`), by its Subject. */
21
+ // Module state (#460, Q7): each Wardic element's animatable, held weakly by its Subject.
22
+ const wardicElements = new WeakMap();
23
+ /**
24
+ * Register a mounted Wardic element's spine for the Imperative animations of its Subject (#433): until
25
+ * the returned function, which its unmount calls.
26
+ */
27
+ export const registerAnimatable = (subject, spine) => {
28
+ wardicElements.set(subject, spine);
29
+ return () => {
30
+ if (wardicElements.get(subject) === spine)
31
+ wardicElements.delete(subject);
32
+ };
33
+ };
34
+ /** An Environment with no Batches. */
35
+ export const noBatches = {
36
+ entryOf: () => undefined,
37
+ hasMembers: () => false,
38
+ callPartsOf: (subjects, target) => ({ members: [], subjects: Arr.map(subjects, (subject, index) => ({ subject, index, target })) }),
39
+ segmentSubjectsOf: identity,
40
+ sequencePartsOf: (compiled) => ({ batches: [], others: compiled }),
41
+ };
42
+ /** Each gate's plain Subjects: a provider's own, kept while the Subject is. */
43
+ // Module state (#460, Q7): each gate's plain Subjects, held weakly by the gate.
44
+ const plainByGate = new WeakMap();
45
+ /** The plain Subjects' gate ids, counted. */
46
+ // Module state (#460, Q7): an id counter, unique across every gate.
47
+ let plainIds = 0;
48
+ /** No config: a plain Subject's. */
49
+ const NO_CONFIG = {};
50
+ /** `subject`'s plain spine under `env`'s gate, made at its first animation. */
51
+ const plainOf = (env, subjects, subject) => {
52
+ let bySubject = plainByGate.get(env.gate);
53
+ if (Predicate.isUndefined(bySubject)) {
54
+ bySubject = new WeakMap();
55
+ plainByGate.set(env.gate, bySubject);
56
+ }
57
+ const known = bySubject.get(subject);
58
+ if (Predicate.isNotUndefined(known))
59
+ return known;
60
+ const id = `wardic-animate-${plainIds++}`;
61
+ const snapshot = Spine.emptySnapshotOf({});
62
+ const spine = Spine.makeElementSpine({
63
+ runtime: env.runtime,
64
+ gate: env.gate,
65
+ id,
66
+ element: subject,
67
+ tag: undefined,
68
+ config: () => NO_CONFIG,
69
+ parent: undefined,
70
+ canStart: undefined,
71
+ extraDelay: undefined,
72
+ onFrame: undefined,
73
+ reducedMotion: env.reducedMotion,
74
+ positionalKeys: env.positionalKeys,
75
+ defaultTransition: env.defaultTransition,
76
+ ownValues: env.ownValues,
77
+ measuredPairs: env.measuredPairs,
78
+ variableValues: env.variableValues,
79
+ start: { initialValues: {}, initialLink: {}, startedLink: {}, quiet: false },
80
+ snapshot,
81
+ reuse: Spine.makeReuse(),
82
+ links: subjects.startLinksOf(subject),
83
+ styleNow: undefined,
84
+ live: undefined,
85
+ presence: undefined,
86
+ projected: false,
87
+ dragAxis: undefined,
88
+ handoff: undefined,
89
+ });
90
+ const plain = { spine, snapshot, id, running: 0, unregister: constVoid };
91
+ bySubject.set(subject, plain);
92
+ return plain;
93
+ };
94
+ /**
95
+ * `transition` with `skipAnimations` when its scope's animations are skipped (#468, Motion's
96
+ * `useAnimate`, which hands its config's to each animation): a Wardic element's own config can skip it
97
+ * too, and a plain Subject has none.
98
+ */
99
+ const skippedIn = (env, transition) => {
100
+ if (Bool.not(env.skipAnimations()))
101
+ return transition;
102
+ return { ...transition, skipAnimations: true };
103
+ };
104
+ /**
105
+ * The resolution an **Imperative animation**'s legs run under (#433): none of the Override stack's,
106
+ * so a Retarget that takes a key back never carries one as its own Keyframes or names.
107
+ */
108
+ const IMPERATIVE = {
109
+ resolved: {},
110
+ base: {},
111
+ dragging: false,
112
+ variant: undefined,
113
+ active: { inView: false, focused: false, hovered: false, pressed: false, dragged: false, dragging: false },
114
+ transition: undefined,
115
+ layers: [],
116
+ names: VariantTree.NO_GESTURE_NAMES,
117
+ layersOn: VariantTree.NO_GESTURE_STATES,
118
+ ends: undefined,
119
+ keyframes: undefined,
120
+ change: undefined,
121
+ };
122
+ /**
123
+ * An **Imperative animation** of a Subject (#433), through its spine's `host`: it takes `target`'s
124
+ * keys from whatever runs them, each noted with the target the Override stack has for it now, so a
125
+ * Retarget leaves it where the animation leaves it until that target changes (Motion's latest-wins).
126
+ * Its legs start where the keys are drawn, with their velocity, on `given` (a key with none of its own
127
+ * on its Default transition), reduced motion as the provider says, and run through `head` once
128
+ * {@link Spine.ImperativeTrack.run} is called.
129
+ */
130
+ // #746 (ADR-0067, *Amendment (#746)*, decision 10): here, not in the spine, so an app that never animates
131
+ // imperatively ships none of it; the spine hands over what it takes (`SpineHost`).
132
+ const imperativeTrackOf = (host, target, given, head, hooks) => {
133
+ 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;
134
+ /** A leg of an Imperative animation, forked as a Retarget's are; it lands on its track. */
135
+ // Data-first: a pipe's curried forms are two closures more for every leg (#618, H1).
136
+ const runImperative = (running, program) => {
137
+ running.fiber = runtime.runFork(Effect.asVoid(Effect.onExit(program, legEnded(running))));
138
+ };
139
+ const to = target.values;
140
+ const before = UndefinedOr.match(host.lastResolution(), { onUndefined: () => Spine.NO_VALUES, onDefined: (last) => last.resolved });
141
+ const started = {};
142
+ let measuring;
143
+ // Each key taken from whatever runs it, noted with its target now, and started where it's drawn.
144
+ // Its velocity read now (#464), as its legs are built.
145
+ const takenNow = host.taking();
146
+ // Where a Path's axis this target leaves out rests (#574), before its keys are taken below.
147
+ const rests = Spine.restsOf(owners, to);
148
+ Arr.forEach(Rec.keys(to), (key) => {
149
+ takenNow.set(key, before[key]);
150
+ host.returning().delete(key);
151
+ // Its Timeline value stops while the animation draws the key (#240).
152
+ const timelineKeys = host.timelineKeys();
153
+ if (Predicate.isNotUndefined(timelineKeys))
154
+ timelineKeys.taken(key);
155
+ const owner = owners.get(key);
156
+ if (Predicate.isNotUndefined(owner))
157
+ giveUp(key, owner);
158
+ if (!Object.hasOwn(initialValues, key))
159
+ ownValue(key);
160
+ const like = UndefinedOr.getOrThrow(to[key]);
161
+ startKey(key, like, started);
162
+ if (measuredPairs.needs(key, UndefinedOr.getOrThrow(snapshot.values[key]), like)) {
163
+ if (Predicate.isUndefined(measuring))
164
+ measuring = [];
165
+ measuring.push(key);
166
+ }
167
+ });
168
+ keepTheRest();
169
+ let from = Rec.map(to, (_, key) => UndefinedOr.getOrThrow(snapshot.values[key]));
170
+ let stops;
171
+ if (Predicate.isNotUndefined(target.keyframes)) {
172
+ const begun = RetargetLegs.keyframesFrom(from, to, target.keyframes);
173
+ from = begun.from;
174
+ stops = begun.stops;
175
+ }
176
+ const reduce = host.reducedMotion();
177
+ const skipped = host.skipAnimations();
178
+ let measured;
179
+ if (Bool.and(Bool.not(Bool.or(reduce, skipped)), Predicate.isNotUndefined(measuring)))
180
+ measured = Spine.measuredOf(measuredPairs, element, UndefinedOr.getOrThrow(measuring), from, to, snapshot.values, stops);
181
+ // Built once: a seek or a replay runs the same legs, from the same start, with the same velocities.
182
+ const built = RetargetLegs.legsOf(from, to, given, reduce, skipped, positionalKeys, defaultTransition, readVelocity, undefined, stops, measured, snapshot.values, rests, unitScale);
183
+ const variables = Spine.holdsVariable(variableValues, from, to, stops);
184
+ const legs = Arr.map(built, (leg) => RetargetLegs.mapMachine(leg, Playback.drive(head)));
185
+ let runnings = Spine.NO_RUNNING;
186
+ let left = 0;
187
+ const landing = {
188
+ report: constVoid,
189
+ settled: () => {
190
+ left--;
191
+ if (left === 0)
192
+ gate.afterFlush(hooks.settled);
193
+ },
194
+ failed: hooks.failed,
195
+ };
196
+ // Its legs ended where they are: the keys they draw are drawn by none.
197
+ const end = () => Arr.forEach(runnings, (running) => {
198
+ forget(running);
199
+ if (Bool.not(running.done))
200
+ endLeg(running);
201
+ });
202
+ const run = () => {
203
+ end();
204
+ left = legs.length;
205
+ Spine.tellStarted(live, legs);
206
+ runnings = Arr.map(legs, (leg) => {
207
+ const running = Spine.runningOf(leg.to, IMPERATIVE, landing, leg._tag);
208
+ own(running);
209
+ runImperative(running, legProgram(leg, running, variables));
210
+ return running;
211
+ });
212
+ // A target with no key lands at once.
213
+ if (left === 0)
214
+ gate.afterFlush(hooks.settled);
215
+ };
216
+ const cancel = () => {
217
+ end();
218
+ turnBack();
219
+ snapshot.values = { ...snapshot.values, ...from };
220
+ snapshot.velocities = { ...snapshot.velocities, ...Rec.map(from, () => 0) };
221
+ // Put back at once: at rest, newer than the legs that let them go (#464).
222
+ const now = snapshot.now();
223
+ Arr.forEach(Rec.keys(from), (key) => {
224
+ snapshot.drawnAt[key] = now;
225
+ });
226
+ gate.write(id, from);
227
+ recordFrame(from);
228
+ };
229
+ // Each leg's machine, run from its start to rest, apart from the Playhead, which it would move: a
230
+ // blend's built with the Subject's Key rules.
231
+ const duration = () => Arr.reduce(built, 0, (longest, leg) => Math.max(longest, Machine.durationOf(machineOf(leg))));
232
+ const machineOf = (leg) => {
233
+ if (leg._tag === "Blend")
234
+ return runtime.runSync(Effect.suspend(leg.machine).pipe(InterpolatorRegistry.withKeyRules(elementRules)));
235
+ return leg.machine();
236
+ };
237
+ const stop = () => {
238
+ end();
239
+ turnBack();
240
+ };
241
+ return { run, stop, cancel, duration };
242
+ };
243
+ /**
244
+ * A Subject's animation of `target`: through its spine when it's a Wardic element's, else through its
245
+ * plain spine, in the gate while any of its animations runs.
246
+ */
247
+ const trackOf = (env, subjects, subject, target, given, head, settled) => {
248
+ const resolved = VariantTarget.resolveTarget(target, undefined, undefined, VariantTarget.NO_VARIANT_STATE);
249
+ const own = wardicElements.get(subject);
250
+ const hooks = { settled, failed: constVoid };
251
+ const transition = skippedIn(env, given);
252
+ if (Predicate.isNotUndefined(own))
253
+ return imperativeTrackOf(own.host(), resolved, transition, head, hooks);
254
+ const plain = plainOf(env, subjects, subject);
255
+ // In the gate while it runs; out once its last animation is done, after the flush of its last frame.
256
+ let live = false;
257
+ const enter = () => {
258
+ if (live)
259
+ return;
260
+ live = true;
261
+ // Back in the gate with every value it holds, so a transform it draws keeps the keys it isn't animating.
262
+ if (plain.running === 0) {
263
+ plain.unregister = env.gate.register(plain.id, { target: subject });
264
+ if (Bool.not(Rec.isEmptyRecord(plain.snapshot.values)))
265
+ env.gate.write(plain.id, plain.snapshot.values);
266
+ }
267
+ plain.running++;
268
+ };
269
+ const leave = () => {
270
+ if (Bool.not(live))
271
+ return;
272
+ live = false;
273
+ plain.running--;
274
+ if (plain.running === 0)
275
+ env.gate.afterFlush(() => {
276
+ if (plain.running === 0)
277
+ plain.unregister();
278
+ });
279
+ };
280
+ const track = imperativeTrackOf(plain.spine.host(), resolved, transition, head, {
281
+ settled: () => {
282
+ leave();
283
+ settled();
284
+ },
285
+ failed: () => leave(),
286
+ });
287
+ return {
288
+ run: () => {
289
+ enter();
290
+ track.run();
291
+ },
292
+ stop: () => {
293
+ track.stop();
294
+ leave();
295
+ },
296
+ cancel: () => {
297
+ enter();
298
+ track.cancel();
299
+ leave();
300
+ },
301
+ duration: track.duration,
302
+ };
303
+ };
304
+ /** A call's options without its `onComplete`: its transition. */
305
+ const withoutComplete = (given) => {
306
+ const { onComplete: _onComplete, ...rest } = given;
307
+ return rest;
308
+ };
309
+ /** Each Subject's transition: its `delay` worked out for it (Motion's `delay(i, n)`). */
310
+ const transitionFor = (options, index, count) => UndefinedOr.map(options, (given) => {
311
+ const { delay, ...rest } = withoutComplete(given);
312
+ if (Predicate.isFunction(delay))
313
+ return { ...rest, delay: delay(index, count) };
314
+ if (Predicate.isUndefined(delay))
315
+ return rest;
316
+ return { ...rest, delay };
317
+ });
318
+ /** A Batch call's transition (#665): the options without `onComplete`, a `stagger()` delay kept for the Batch to count its movers. */
319
+ const batchTransitionOf = (options) => UndefinedOr.map(options, (given) => withoutComplete(given));
320
+ /** A Batch call's track over `members` (every member when left out), driven by `head`: the call's options its transition. */
321
+ const batchTrackOf = (env, binding, target, members, options, head, settled) => binding.track({
322
+ target,
323
+ transition: batchTransitionOf(options),
324
+ reducedMotion: env.reducedMotion(),
325
+ skipAnimations: skipsBatchCall(env, options),
326
+ head,
327
+ settled,
328
+ members,
329
+ });
330
+ /** Whether a Batch call lands at once: its scope's animations are skipped, or its own `skipAnimations` (#468). */
331
+ const skipsBatchCall = (env, options) => {
332
+ if (env.skipAnimations())
333
+ return true;
334
+ return UndefinedOr.match(options, { onUndefined: () => false, onDefined: (given) => given.skipAnimations === true });
335
+ };
336
+ /** Playback controls over `tracks`, all run through `head`, started now. */
337
+ const controlsOf = (tracks, head, watch, onComplete) => {
338
+ let state = "running";
339
+ let stopped = false;
340
+ let landed = 0;
341
+ let resolve;
342
+ let finished;
343
+ let isResolved = false;
344
+ let duration;
345
+ const durationNow = () => {
346
+ if (Predicate.isUndefined(duration))
347
+ duration = Arr.reduce(tracks, 0, (longest, track) => Math.max(longest, track.duration()));
348
+ return duration;
349
+ };
350
+ const runAll = () => {
351
+ landed = 0;
352
+ Arr.forEach(tracks, (track) => track.run());
353
+ };
354
+ const fresh = () => {
355
+ finished = undefined;
356
+ resolve = undefined;
357
+ isResolved = false;
358
+ };
359
+ const end = (how, landedNow) => {
360
+ const was = state;
361
+ state = how;
362
+ if (Bool.or(was === "running", was === "paused"))
363
+ watch.ended(controls, landedNow);
364
+ };
365
+ const restart = () => {
366
+ const was = state;
367
+ state = "running";
368
+ if (Bool.or(was === "finished", was === "idle"))
369
+ watch.started(controls);
370
+ };
371
+ const controls = {
372
+ get time() {
373
+ return head.time;
374
+ },
375
+ set time(at) {
376
+ Playback.seek(head, at);
377
+ // A seek of one that isn't running holds where it goes, as Motion's.
378
+ if (state !== "running") {
379
+ Playback.pause(head);
380
+ if (Bool.or(state === "finished", state === "idle")) {
381
+ fresh();
382
+ watch.started(controls);
383
+ }
384
+ state = "paused";
385
+ }
386
+ runAll();
387
+ },
388
+ get speed() {
389
+ return head.speed;
390
+ },
391
+ set speed(speed) {
392
+ Playback.setSpeed(head, speed);
393
+ },
394
+ get duration() {
395
+ return durationNow();
396
+ },
397
+ get state() {
398
+ return state;
399
+ },
400
+ get finished() {
401
+ if (Predicate.isUndefined(finished)) {
402
+ finished = Bool.match(isResolved, {
403
+ onTrue: () => Promise.resolve(),
404
+ onFalse: () => new Promise((done) => {
405
+ resolve = done;
406
+ }),
407
+ });
408
+ }
409
+ return finished;
410
+ },
411
+ then: (onResolve, onReject) => controls.finished.then(onResolve, onReject),
412
+ play: () => {
413
+ if (stopped)
414
+ return;
415
+ if (state === "paused") {
416
+ Playback.play(head);
417
+ state = "running";
418
+ return;
419
+ }
420
+ if (state === "running")
421
+ return;
422
+ // Again from its start: its end when it plays backwards.
423
+ fresh();
424
+ Playback.play(head);
425
+ Playback.seek(head, Bool.match(head.speed < 0, { onTrue: durationNow, onFalse: () => 0 }));
426
+ restart();
427
+ runAll();
428
+ },
429
+ pause: () => {
430
+ if (stopped)
431
+ return;
432
+ Playback.pause(head);
433
+ if (state === "running")
434
+ state = "paused";
435
+ },
436
+ stop: () => {
437
+ stopped = true;
438
+ Arr.forEach(tracks, (track) => track.stop());
439
+ end("idle", false);
440
+ },
441
+ cancel: () => {
442
+ Arr.forEach(tracks, (track) => track.cancel());
443
+ Playback.seek(head, 0);
444
+ end("idle", false);
445
+ },
446
+ complete: () => {
447
+ if (stopped)
448
+ return;
449
+ if (state !== "running")
450
+ restart();
451
+ Playback.play(head);
452
+ Playback.seek(head, durationNow());
453
+ runAll();
454
+ },
455
+ };
456
+ // Each Subject's legs landed: the last lands the animation.
457
+ const settledOne = () => {
458
+ landed++;
459
+ if (landed < tracks.length)
460
+ return;
461
+ isResolved = true;
462
+ UndefinedOr.map(resolve, (done) => done());
463
+ UndefinedOr.map(onComplete, (complete) => complete());
464
+ end("finished", true);
465
+ };
466
+ return { controls, settledOne };
467
+ };
468
+ /** An animation of no Subject: finished at once (a server's, or a subject that matched none). */
469
+ export const finishedControls = () => {
470
+ const done = Promise.resolve();
471
+ return {
472
+ time: 0,
473
+ speed: 1,
474
+ duration: 0,
475
+ state: "finished",
476
+ finished: done,
477
+ then: (onResolve, onReject) => done.then(onResolve, onReject),
478
+ play: constVoid,
479
+ pause: constVoid,
480
+ stop: constVoid,
481
+ cancel: constVoid,
482
+ complete: constVoid,
483
+ };
484
+ };
485
+ /**
486
+ * An animation of `count` tracks started (#433): its controls over them, through one Playhead, told
487
+ * to `watch`, each track run. Finished at once with none.
488
+ */
489
+ const started = (watch, count, onComplete, tracksOf) => {
490
+ if (count === 0)
491
+ return finishedControls();
492
+ const head = Playback.make();
493
+ let settledOne = constVoid;
494
+ const tracks = tracksOf(head, () => settledOne());
495
+ const made = controlsOf(tracks, head, watch, onComplete);
496
+ settledOne = made.settledOne;
497
+ watch.started(made.controls);
498
+ Arr.forEach(tracks, (track) => track.run());
499
+ return made.controls;
500
+ };
501
+ /**
502
+ * An **Animation scope**'s `animate` (#433), over an Environment's {@link Ports}: `animate(subject,
503
+ * target, options?)`, a Batch's `animate(batch, target, options?)` and `animate(sequence, options?)`,
504
+ * each returning its Playback controls. `scope()` is handed to the Environment's {@link Subjects.resolve}
505
+ * (the DOM's selectors are looked up inside it); each animation is told to `watch` as it starts and
506
+ * ends. Every Subject's legs start in the call, on the loop by the end of its task. An Environment
507
+ * types its own overloads over it.
508
+ */
509
+ export const make = (env, ports, scope, watch) => (first, second, third) => {
510
+ if (isSequence(first))
511
+ return sequenceOf(env, ports, scope(), watch, first, second);
512
+ // A Batch, or a member's handle (#665): one track over its members, on the Batch's own run.
513
+ const batch = ports.batches.entryOf(first);
514
+ if (Predicate.isNotUndefined(batch)) {
515
+ const members = batch.binding.namedOf(batch);
516
+ return started(watch, 1, UndefinedOr.map(third, (given) => given.onComplete), (head, settled) => [
517
+ batchTrackOf(env, batch.binding, second, members, third, head, settled),
518
+ ]);
519
+ }
520
+ const subjects = ports.subjects.resolve(first, scope());
521
+ const target = second;
522
+ const onComplete = UndefinedOr.map(third, (given) => given.onComplete);
523
+ // No member's Subject among them: each Subject's track, building no parts (bench:solid --batch's
524
+ // per-element page, a call per element: 8.2 -> 8.5 ms at 1,000 with the parts built for every call; #665).
525
+ if (Bool.not(ports.batches.hasMembers(subjects))) {
526
+ return started(watch, subjects.length, onComplete, (head, settled) => Arr.map(subjects, (subject, index) => trackOf(env, ports.subjects, subject, target, transitionFor(third, index, subjects.length), head, settled)));
527
+ }
528
+ // 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).
529
+ const parts = ports.batches.callPartsOf(subjects, target);
530
+ return started(watch, parts.members.length + parts.subjects.length, onComplete, (head, settled) => [
531
+ ...Arr.map(parts.members, (part) => batchTrackOf(env, part.binding, part.target, part.members, third, head, settled)),
532
+ ...Arr.map(parts.subjects, (part) => trackOf(env, ports.subjects, part.subject, part.target, transitionFor(third, part.index, subjects.length), head, settled)),
533
+ ]);
534
+ };
535
+ // --- Sequences (#433's PR 2) ------------------------------------------------------------------
536
+ /** 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). */
537
+ export const isSequence = (given) => Bool.match(Arr.isArray(given), { onTrue: () => Arr.some(given, Arr.isArray), onFalse: () => false });
538
+ /** Whether a sequence's subject is a function Segment's value. */
539
+ const isCallback = (subject) => Predicate.hasProperty(subject, "call");
540
+ /** The key a function Segment's value animates under. */
541
+ const VALUE = "value";
542
+ /** A function Segment's stops with none given (Motion's). */
543
+ const ZERO_TO_ONE = [0, 1];
544
+ /** No fields. */
545
+ const NO_FIELDS = {};
546
+ /**
547
+ * What a Segment's transition doesn't take from the sequence's `defaultTransition` (Motion's): its
548
+ * delay, times and repeat, which are each Segment's own, and a value's own transitions.
549
+ */
550
+ const PLACING = new Set(["delay", "times", "repeat", "repeatType", "repeatDelay", "reverse", "at"]);
551
+ /** A Segment's default transition (Motion's): a 0.3 s `easeOut` tween. */
552
+ const SEGMENT_TWEEN = { type: "tween" };
553
+ /** The fields of a sequence's options laid over each key's animation: `duration`, `delay` and the repeat. */
554
+ const WHOLE = ["duration", "delay", "repeat", "repeatType", "repeatDelay"];
555
+ /**
556
+ * The fields of a sequence's `defaultTransition` laid over each key's animation, under its own
557
+ * options' (Motion's): its delay and repeat. Its `duration` is a Segment's, never the sequence's.
558
+ */
559
+ const WHOLE_DEFAULTS = ["delay", "repeat", "repeatType", "repeatDelay"];
560
+ /** `fields`' `keys`, those it has. */
561
+ const picked = (fields, keys) => Rec.filter(fields, (value, key) => Bool.and(Arr.contains(keys, key), Predicate.isNotUndefined(value)));
562
+ /**
563
+ * `key`'s transition in a Segment (Motion's `getValueTransition` for sequences): the Segment's,
564
+ * the value's own laid over it, over the sequence's `defaultTransition` less its placing; a spring
565
+ * or a tween as Wardic's transitions are (ADR-0051), Motion's 0.3 s `easeOut` tween when it defines
566
+ * neither; its `delay` kept as given, each Subject's when it's a function.
567
+ */
568
+ const segmentTransitionOf = (options, key, defaults) => {
569
+ const own = UndefinedOr.match(options, {
570
+ onUndefined: () => NO_FIELDS,
571
+ onDefined: (given) => ({ ...given, ...UndefinedOr.match(given[key], { onUndefined: () => NO_FIELDS, onDefined: (entry) => Bool.match(Predicate.isObject(entry), { onTrue: () => entry, onFalse: () => NO_FIELDS }) }) }),
572
+ });
573
+ const base = UndefinedOr.match(defaults, {
574
+ onUndefined: () => NO_FIELDS,
575
+ onDefined: (given) => Rec.filter(given, (_, field) => Bool.not(PLACING.has(field))),
576
+ });
577
+ const { delay, at: _at, ...fields } = own;
578
+ // An inertia (#435) isn't a sequence's: a Segment's time is placed on its timeline, and a glide has none to place.
579
+ const run = UndefinedOr.match(RetargetLegs.runOf({ ...base, ...fields }), {
580
+ onUndefined: () => SEGMENT_TWEEN,
581
+ onDefined: (made) => Bool.match(made.type === "inertia", { onTrue: () => SEGMENT_TWEEN, onFalse: () => made }),
582
+ });
583
+ return Bool.match(Predicate.isUndefined(delay), { onTrue: () => run, onFalse: () => ({ ...run, delay }) });
584
+ };
585
+ /** Whether a Segment's value is one: a number, a string, `null` or Keyframes. */
586
+ const isSegmentValue = /*#__PURE__*/ Predicate.or(/*#__PURE__*/ Predicate.or(Predicate.isNumber, Predicate.isString), /*#__PURE__*/ Predicate.or(Predicate.isNull, Arr.isArray));
587
+ /** A Segment's values: those that are a value, `null` or Keyframes. */
588
+ const segmentValuesOf = (target) => Rec.filter(target, isSegmentValue);
589
+ /** Each of `values`' keys' transition in a Segment. */
590
+ const segmentTransitionsOf = (values, options, defaults) => Rec.map(values, (_, key) => segmentTransitionOf(options, key, defaults));
591
+ /** A Segment's `at`, when it gives one. */
592
+ const atOf = (options) => UndefinedOr.map(options, (given) => given.at);
593
+ /**
594
+ * A Segment's subjects (#665, Q40): each Subject, a member's as its member's entry, so its Batch keys
595
+ * run in its Batch, as one subject with the member a Segment of the Batch names.
596
+ */
597
+ const subjectsIn = (batches, subjects, target) => {
598
+ if (Bool.not(batches.hasMembers(subjects)))
599
+ return subjects;
600
+ return batches.segmentSubjectsOf(subjects, target);
601
+ };
602
+ /**
603
+ * A sequence's steps for core (#433): labels as they are; a Segment of Subjects' Subjects (a string
604
+ * the Environment resolves, a DOM selector, looked up once a sequence, inside `scope`), values and each
605
+ * value's transition; a function Segment's own value, from 0 to 1 unless it gives its stops.
606
+ */
607
+ const stepsOf = (ports, sequence, scope, defaults) => {
608
+ const named = new Map();
609
+ const subjectsOf = (subject) => {
610
+ if (Bool.not(Predicate.isString(subject)))
611
+ return ports.subjects.resolve(subject, scope);
612
+ const name = subject;
613
+ const known = named.get(name);
614
+ if (Predicate.isNotUndefined(known))
615
+ return known;
616
+ const found = ports.subjects.resolve(name, scope);
617
+ named.set(name, found);
618
+ return found;
619
+ };
620
+ return Arr.map(sequence, (segment) => {
621
+ if (Predicate.isString(segment))
622
+ return segment;
623
+ if (Bool.not(Arr.isArray(segment)))
624
+ return segment;
625
+ const parts = segment;
626
+ // A Batch, or a member's handle (#665, Q38, Q39): its members, each through its own stops in the Batch.
627
+ const batch = ports.batches.entryOf(parts[0]);
628
+ if (Predicate.isNotUndefined(batch)) {
629
+ const options = parts[2];
630
+ const { subjects, values } = batch.binding.segmentOf(batch.binding.namedOf(batch), parts[1]);
631
+ return { subjects, target: values, transitions: segmentTransitionsOf(values, options, defaults), at: atOf(options) };
632
+ }
633
+ if (Predicate.isFunction(parts[0])) {
634
+ const call = parts[0];
635
+ const three = parts.length === 3;
636
+ const given = Bool.match(three, { onTrue: () => parts[1], onFalse: () => ZERO_TO_ONE });
637
+ const options = Bool.match(three, { onTrue: () => parts[2], onFalse: () => parts[1] });
638
+ const target = { [VALUE]: given };
639
+ return { subjects: [{ call }], target, transitions: segmentTransitionsOf(target, options, defaults), at: atOf(options) };
640
+ }
641
+ const [subject, values, options] = segment;
642
+ const target = segmentValuesOf(values);
643
+ return { subjects: subjectsIn(ports.batches, subjectsOf(subject), target), target, transitions: segmentTransitionsOf(target, options, defaults), at: atOf(options) };
644
+ });
645
+ };
646
+ /**
647
+ * Whether a Segment animates anything under `scope` (#798): a function Segment does, and a Batch's; a
648
+ * Segment of Subjects when its subject names one; a label (a string, or `{ name, at }`) never. What a
649
+ * binding asks of a sequence before it plays it, since one that animates nothing lands at once.
650
+ */
651
+ export const segmentAnimates = (ports, segment, scope) => {
652
+ if (Predicate.isString(segment))
653
+ return false;
654
+ if (Bool.not(Arr.isArray(segment)))
655
+ return false;
656
+ const parts = segment;
657
+ if (Predicate.isNotUndefined(ports.batches.entryOf(parts[0])))
658
+ return true;
659
+ if (Predicate.isFunction(parts[0]))
660
+ return true;
661
+ return ports.subjects.resolve(parts[0], scope).length > 0;
662
+ };
663
+ /**
664
+ * A function Segment's value animated (#433): its stops, a first `null` 0, through the
665
+ * Interpolators on its tween over the sequence, each frame told to its callback. Cancelled, the
666
+ * callback hears its first stop again, as Motion's motion value is set back.
667
+ */
668
+ const callbackTrackOf = (env, callback, animation, head, settled) => {
669
+ const stops = RetargetLegs.filledStops(UndefinedOr.getOrThrow(animation.keyframes[VALUE]), 0);
670
+ const options = UndefinedOr.getOrThrow(animation.transition[VALUE]);
671
+ // Skipped (#468): its callback told the value it would end on, on the first tick.
672
+ const machine = Bool.match(env.skipAnimations(), {
673
+ onTrue: () => Effect.succeed(ReducedMotion.snap({ [VALUE]: UndefinedOr.getOrThrow(stops[0]) }, { [VALUE]: ReducedMotion.endOf(UndefinedOr.getOrThrow(stops[0]), UndefinedOr.getOrThrow(stops[stops.length - 1]), options) })),
674
+ onFalse: () => Machine.keyframesValues({ [VALUE]: stops }, options),
675
+ });
676
+ let fiber;
677
+ const end = () => {
678
+ if (Predicate.isUndefined(fiber))
679
+ return;
680
+ const running = fiber;
681
+ fiber = undefined;
682
+ // Nothing waits on its end: interrupted here, not by a fiber forked for it (#618, L2).
683
+ if (Predicate.isUndefined(running.pollUnsafe()))
684
+ running.interruptUnsafe();
685
+ };
686
+ const landed = (exit) => Exit.match(exit, {
687
+ onSuccess: () => Effect.sync(settled),
688
+ onFailure: (cause) => Bool.match(Cause.hasInterruptsOnly(cause), { onTrue: () => Effect.void, onFalse: () => Report.failure("wardic.animate: a function Segment failed", cause) }),
689
+ });
690
+ const run = () => {
691
+ end();
692
+ fiber = env.runtime.runFork(machine.pipe(Effect.map(Playback.drive(head)), Effect.flatMap(Machine.run((frame) => {
693
+ callback.call(UndefinedOr.getOrThrow(frame.value[VALUE]));
694
+ return undefined;
695
+ })), Effect.onExit(landed)));
696
+ };
697
+ return {
698
+ run,
699
+ stop: end,
700
+ cancel: () => {
701
+ end();
702
+ callback.call(UndefinedOr.getOrThrow(stops[0]));
703
+ },
704
+ duration: () => Machine.durationOf(env.runtime.runSync(machine)),
705
+ };
706
+ };
707
+ /**
708
+ * A sequence started (#433's PR 2, Motion's): compiled by core's `Sequence`, each Subject animated
709
+ * through its Keyframes on its spine or its plain one, as a call animates it, and each function
710
+ * Segment's value told to its callback; one Playhead for all, so it seeks, pauses and awaits as one.
711
+ */
712
+ const sequenceOf = (env, ports, scope, watch, sequence, options) => {
713
+ const defaults = UndefinedOr.map(options, (given) => given.defaultTransition);
714
+ // The sequence's own options over its `defaultTransition`'s, as Motion's.
715
+ const whole = {
716
+ ...picked(UndefinedOr.match(defaults, { onUndefined: () => NO_FIELDS, onDefined: identity }), WHOLE_DEFAULTS),
717
+ ...picked(UndefinedOr.match(options, { onUndefined: () => NO_FIELDS, onDefined: identity }), WHOLE),
718
+ };
719
+ const compiled = Arr.fromIterable(Sequence.compile(stepsOf(ports, sequence, scope, defaults), whole));
720
+ // Each Batch's members as one track, their other keys their Subjects' (#665, Q40).
721
+ const parts = ports.batches.sequencePartsOf(compiled);
722
+ return started(watch, compiled.length, UndefinedOr.map(options, (given) => given.onComplete), (head, settled) => [
723
+ ...Arr.map(parts.others, ([subject, animation]) => {
724
+ if (isCallback(subject))
725
+ return callbackTrackOf(env, subject, animation, head, settled);
726
+ return trackOf(env, ports.subjects, subject, animation.keyframes, animation.transition, head, settled);
727
+ }),
728
+ ...Arr.map(parts.batches, (part) => part.binding.sequenceTrack({ members: part.members, animations: part.animations, reducedMotion: env.reducedMotion(), skipAnimations: env.skipAnimations(), head, settled })),
729
+ ]);
730
+ };
731
+ /** `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). */
732
+ export const alsoTold = (watch, also) => UndefinedOr.match(also, {
733
+ onUndefined: () => watch,
734
+ onDefined: (more) => ({
735
+ started: (controls) => {
736
+ watch.started(controls);
737
+ more.started(controls);
738
+ },
739
+ ended: (controls, landed) => {
740
+ watch.ended(controls, landed);
741
+ more.ended(controls, landed);
742
+ },
743
+ }),
744
+ });
745
+ //# sourceMappingURL=Imperative.js.map