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