@wardic/core 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.
Files changed (76) 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 +40 -10
  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 +150 -0
  34. package/dist/unstable/BatchCalls.d.ts.map +1 -0
  35. package/dist/unstable/BatchCalls.js +319 -0
  36. package/dist/unstable/BatchCalls.js.map +1 -0
  37. package/dist/unstable/Config.d.ts +11 -0
  38. package/dist/unstable/Config.d.ts.map +1 -1
  39. package/dist/unstable/Config.js.map +1 -1
  40. package/dist/unstable/FrameEffects.d.ts +59 -0
  41. package/dist/unstable/FrameEffects.d.ts.map +1 -0
  42. package/dist/unstable/FrameEffects.js +142 -0
  43. package/dist/unstable/FrameEffects.js.map +1 -0
  44. package/dist/unstable/FrameTime.d.ts +1 -4
  45. package/dist/unstable/FrameTime.d.ts.map +1 -1
  46. package/dist/unstable/FrameTime.js +1 -4
  47. package/dist/unstable/FrameTime.js.map +1 -1
  48. package/dist/unstable/Imperative.d.ts +292 -0
  49. package/dist/unstable/Imperative.d.ts.map +1 -0
  50. package/dist/unstable/Imperative.js +922 -0
  51. package/dist/unstable/Imperative.js.map +1 -0
  52. package/dist/unstable/RetargetLegs.d.ts +2 -1
  53. package/dist/unstable/RetargetLegs.d.ts.map +1 -1
  54. package/dist/unstable/RetargetLegs.js +23 -15
  55. package/dist/unstable/RetargetLegs.js.map +1 -1
  56. package/dist/unstable/Spine.d.ts +17 -14
  57. package/dist/unstable/Spine.d.ts.map +1 -1
  58. package/dist/unstable/Spine.js +33 -16
  59. package/dist/unstable/Spine.js.map +1 -1
  60. package/package.json +1 -1
  61. package/src/BaseValue.ts +2 -0
  62. package/src/Batch.ts +62 -9
  63. package/src/DefaultTransition.ts +53 -2
  64. package/src/FrameLoop.ts +6 -2
  65. package/src/Machine.ts +7 -3
  66. package/src/Spring.ts +16 -0
  67. package/src/UnitScale.ts +56 -0
  68. package/src/index.ts +1 -0
  69. package/src/internal/frameLoop.ts +5 -5
  70. package/src/unstable/BatchCalls.ts +419 -0
  71. package/src/unstable/Config.ts +17 -0
  72. package/src/unstable/FrameEffects.ts +172 -0
  73. package/src/unstable/FrameTime.ts +1 -5
  74. package/src/unstable/Imperative.ts +1232 -0
  75. package/src/unstable/RetargetLegs.ts +20 -11
  76. package/src/unstable/Spine.ts +48 -21
@@ -0,0 +1,419 @@
1
+ /**
2
+ * What an Imperative animation's call of a Batch turns into, for every Environment: an `animate` call's
3
+ * targets for each member (a number, two stops, or a function of a member's index and the count), each
4
+ * key's transition for the change (its own, its Default transition held by its delay, reduced motion's
5
+ * Snap, `skipAnimations`' landing at once), a `stagger()` counting the members it moves, and a sequence's
6
+ * Segment of the Batch, each member's key through its own stops. An Environment's binding names its
7
+ * members and its errors; this works out the rest over core's `Batch`.
8
+ *
9
+ * Unstable, for Wardic's own packages: public, with no semver promise.
10
+ *
11
+ * @module
12
+ */
13
+ // Unstable: ADR-0071, decision 5. #882 (ADR-0073, *Amendment (#882)*, PR 3): dom's `BatchMembers`, its
14
+ // environment-agnostic part moved here, so `@wardic/object`'s Batch runs the DOM's calls; #665's rules
15
+ // (ADR-0069, *Amendment (#665)*; ADR-0070, *Amendment (#665)*).
16
+ import type * as Batch from "../Batch.ts"
17
+ import type * as Machine from "../Machine.ts"
18
+ import type * as Playback from "../Playback.ts"
19
+ import * as ReducedMotion from "../ReducedMotion.ts"
20
+ import type * as Sequence from "../Sequence.ts"
21
+ import type * as Config from "./Config.ts"
22
+ import type * as Imperative from "./Imperative.ts"
23
+ import * as RetargetLegs from "./RetargetLegs.ts"
24
+ import * as Arr from "effect/Array"
25
+ import * as Bool from "effect/Boolean"
26
+ import * as Option from "effect/Option"
27
+ import * as Predicate from "effect/Predicate"
28
+ import * as Rec from "effect/Record"
29
+ import * as UndefinedOr from "effect/UndefinedOr"
30
+
31
+ /** How an Environment reports a Batch call's error: it throws, naming what it got. */
32
+ export type Fail = (message: string) => never
33
+
34
+ /** One change that lands every key at once: `skipAnimations`'. */
35
+ export const INSTANT: Batch.Transition = { type: "tween", duration: 0 }
36
+
37
+ /** A sequence's run that lands a key at once after `delay`: `skipAnimations`', and reduced motion's Snap of a positional key. */
38
+ // Module state (#460, Q7): a cache built once, keyed by what it caches.
39
+ const LANDINGS = new Map<number, Machine.KeyframesOptions>()
40
+
41
+ /** A run of keyframes that lands at once after `delay`, one object each. */
42
+ export const landingAfter = (delay: number): Machine.KeyframesOptions => {
43
+ const known = LANDINGS.get(delay)
44
+ if (Predicate.isNotUndefined(known)) return known
45
+ const made: Machine.KeyframesOptions = { duration: 0, delay }
46
+ LANDINGS.set(delay, made)
47
+ return made
48
+ }
49
+
50
+ /** A Batch key's stop in a sequence, as core's Batch takes it: a number, `NaN` for `null`. */
51
+ export const stopNumber = (stop: Sequence.Stop): number => {
52
+ if (Predicate.isNumber(stop)) return stop
53
+ return Number.NaN
54
+ }
55
+
56
+ /** A key's last stop that's a number, `NaN` (where it is) for none: what its `null`s after it hold. */
57
+ export const lastNumber = (stops: ReadonlyArray<number>): number =>
58
+ Option.getOrElse(Arr.findLast(stops, (stop) => !Number.isNaN(stop)), () => Number.NaN)
59
+
60
+ /** Whether `value` is a Batch's key's first stop: a number, or `null` for where it is. */
61
+ export const isFirstStop: Predicate.Predicate<unknown> = /*#__PURE__*/ Predicate.or(Predicate.isNumber, Predicate.isNull)
62
+
63
+ /** Whether `value` is two stops. */
64
+ export const isPair = (value: unknown): value is readonly [unknown, unknown] => {
65
+ if (!Arr.isArray(value)) return false
66
+ return value.length === 2
67
+ }
68
+
69
+ /** Whether `value` is a Batch key's value in a sequence: a number, `null`, or stops of them. */
70
+ const isSegmentStops = (value: unknown): boolean => {
71
+ if (isFirstStop(value)) return true
72
+ if (!Arr.isArray(value)) return false
73
+ return Arr.every(value, isFirstStop)
74
+ }
75
+
76
+ /** A Batch key's value in a sequence (Q38): a number, `null` or stops of them; else an error naming the key, and the member a function gave it. */
77
+ export const segmentValueOf = (key: string, value: unknown, memberName: string | undefined, fail: Fail): Sequence.Stop | ReadonlyArray<Sequence.Stop> => {
78
+ if (isSegmentStops(value)) return value as Sequence.Stop | ReadonlyArray<Sequence.Stop>
79
+ const whose = UndefinedOr.match(memberName, { onUndefined: () => "", onDefined: (name) => `${name}'s ` })
80
+ return fail(`a sequence gives ${whose}"${key}" as ${JSON.stringify(value)}: a Batch's key takes a number, \`null\`, or stops of them`)
81
+ }
82
+
83
+ /** Reduced motion's Snap after `delay`: a 0 s tween, kept by its delay so its keys share one. */
84
+ // Module state (#460, Q7): a cache built once, keyed by what it caches.
85
+ const SNAPS = new Map<number, Batch.Transition>()
86
+
87
+ const snapAfter = (delay: number): Batch.Transition => {
88
+ const known = SNAPS.get(delay)
89
+ if (Predicate.isNotUndefined(known)) return known
90
+ const made: Batch.Transition = { type: "tween", duration: 0, delay }
91
+ SNAPS.set(delay, made)
92
+ return made
93
+ }
94
+
95
+ /**
96
+ * A Default transition held by a key's own `delay`, as a Wardic element's is when its transition gives
97
+ * only a delay (ADR-0051): one object for each transition and delay, so the members on it share it.
98
+ */
99
+ // Module state (#460, Q7): a cache held weakly by the object it's for, so it goes with it.
100
+ const DELAYED = new WeakMap<object, Map<number, Batch.Transition>>()
101
+
102
+ export const delayedBy = (transition: Batch.Transition, delay: number): Batch.Transition => {
103
+ if (delay === 0) return transition
104
+ let byDelay = DELAYED.get(transition)
105
+ if (Predicate.isUndefined(byDelay)) {
106
+ byDelay = new Map()
107
+ DELAYED.set(transition, byDelay)
108
+ }
109
+ const known = byDelay.get(delay)
110
+ if (Predicate.isNotUndefined(known)) return known
111
+ const made = { ...transition, delay } as Batch.Transition
112
+ byDelay.set(delay, made)
113
+ return made
114
+ }
115
+
116
+ /**
117
+ * A transition without a `stagger()` delay, which a change gives each member by its place: one object
118
+ * each. A `delay` in seconds stays, held by the keys the transition's own fields reach, as a Wardic
119
+ * element's top-level delay is.
120
+ */
121
+ // Module state (#460, Q7): a cache held weakly by the object it's for, so it goes with it.
122
+ const UNSTAGGERED = new WeakMap<object, Config.WardicTransition>()
123
+
124
+ export const unstaggered = (given: { readonly delay?: unknown }): Config.WardicTransition => {
125
+ if (!Predicate.isFunction(given.delay)) return given as Config.WardicTransition
126
+ const known = UNSTAGGERED.get(given)
127
+ if (Predicate.isNotUndefined(known)) return known
128
+ const made = { ...given, delay: undefined } as unknown as Config.WardicTransition
129
+ UNSTAGGERED.set(given, made)
130
+ return made
131
+ }
132
+
133
+ /** A change's `stagger()` delay, for the members it moves; `undefined` for none. */
134
+ export const staggerOf = (given: Config.WardicTransition | undefined): ((rank: number, n: number) => number) | undefined => {
135
+ if (Predicate.isUndefined(given)) return undefined
136
+ const delay: unknown = given.delay
137
+ if (Predicate.isFunction(delay)) return delay as (rank: number, n: number) => number
138
+ return undefined
139
+ }
140
+
141
+ /** A key's transition as a Batch runs it: its run, which can't be an inertia or repeat. */
142
+ const batchRunOf = (run: RetargetLegs.Run, key: string, fail: Fail): Batch.Transition => {
143
+ if (run.type === "inertia") fail(`"${key}" has an inertia transition, which a Batch can't run: give it a spring or a tween`)
144
+ if (Predicate.hasProperty(run, "repeat")) fail(`"${key}"'s transition repeats, which a Batch can't run`)
145
+ return run as Batch.Transition
146
+ }
147
+
148
+ /** A change's plan for one key: its own transition, or `undefined` for its Default transition held by `delay`. */
149
+ export interface KeyPlan {
150
+ readonly own: Batch.Transition | undefined
151
+ readonly delay: number
152
+ }
153
+
154
+ /**
155
+ * Each key's plan for a change, by its index, as a Wardic element's keys run (#301): its entry, else
156
+ * `default`, else the transition's own fields; reduced motion's Snap for a positional key that doesn't
157
+ * opt out; its Default transition, held by its own `delay`, for a key whose transition isn't defined.
158
+ */
159
+ // Once a change, per key.
160
+ export const plannedOf = (positional: ReducedMotion.PositionalKeys["Service"], keys: ReadonlyArray<string>, given: Config.WardicTransition | undefined, reduced: boolean, fail: Fail): ReadonlyArray<KeyPlan> =>
161
+ Arr.map(keys, (key): KeyPlan => {
162
+ const transition = RetargetLegs.transitionForKey(given, key)
163
+ let delay = 0
164
+ let respects = true
165
+ if (Predicate.isNotUndefined(transition)) {
166
+ if (Predicate.isNumber(transition.delay)) delay = transition.delay
167
+ respects = transition.respectReducedMotion !== false
168
+ }
169
+ if (reduced && respects && positional.isPositional(key)) return { own: snapAfter(delay), delay }
170
+ const run = RetargetLegs.runOf(transition)
171
+ if (Predicate.isUndefined(run)) return { own: undefined, delay }
172
+ return { own: batchRunOf(run, key, fail), delay }
173
+ })
174
+
175
+ /**
176
+ * A member's transitions on `keys` for a change planned as `planned`: each key's own, else its Default
177
+ * transition (`defaultFor`) toward its target there, `targetAt(k)`; every key at once when it's skipped.
178
+ */
179
+ export const memberTransitionsOf = (
180
+ keys: ReadonlyArray<string>,
181
+ planned: ReadonlyArray<KeyPlan>,
182
+ defaultFor: (key: string, target: number) => Batch.Transition,
183
+ targetAt: (k: number) => number,
184
+ skipped: boolean,
185
+ ): ReadonlyArray<Batch.Transition> =>
186
+ Arr.map(keys, (key, k) => {
187
+ if (skipped) return INSTANT
188
+ const plan = planned[k] as KeyPlan
189
+ if (Predicate.isNotUndefined(plan.own)) return plan.own
190
+ return delayedBy(defaultFor(key, targetAt(k)), plan.delay)
191
+ })
192
+
193
+ /** What a binding tells these of its Batch: its keys, its Environment's Positional keys and Default transitions, and its errors. */
194
+ export interface Planning {
195
+ readonly keys: ReadonlyArray<string>
196
+ readonly positionalKeys: ReducedMotion.PositionalKeys["Service"]
197
+ /** A key's Default transition toward `target`, by the key's index. */
198
+ readonly defaultFor: (k: number, target: number) => Batch.Transition
199
+ readonly fail: Fail
200
+ }
201
+
202
+ /** A change's call: its transition, its scope's settings, its Playhead and its landing. */
203
+ export interface ChangeCall {
204
+ readonly transition: Config.WardicTransition | undefined
205
+ readonly reducedMotion: boolean
206
+ readonly skipAnimations: boolean
207
+ readonly head: Playback.Playhead
208
+ readonly settled: () => void
209
+ /** It ended with a key a later change took, never landing (#951). */
210
+ readonly taken?: (() => void) | undefined
211
+ readonly onMemberLanded?: ((slot: number) => void) | undefined
212
+ }
213
+
214
+ /**
215
+ * A Batch change's options `O`, `Batch.animate`'s or `Batch.keyframes`', with `onTaken`: called once
216
+ * the change ends with a key a later change took while it moved it, which it then never lands.
217
+ */
218
+ // #951: Motion's never resolves then; the scope it was started in hears it end. Here, in an unstable
219
+ // module, not on Batch's own options: Batch reads it at a change's end (`checkLanding`'s TakenHook).
220
+ export type Taken<O> = O & { readonly onTaken?: (() => void) | undefined }
221
+
222
+ /** A sequence's call's options for `Batch.keyframes`: its Playhead, its landing, and its `onTaken`. */
223
+ export const keyframesOptions = (call: { readonly head: Playback.Playhead; readonly settled: () => void; readonly taken: () => void }): Taken<Batch.KeyframesOptions> => ({
224
+ head: call.head,
225
+ onLanded: call.settled,
226
+ onTaken: call.taken,
227
+ })
228
+
229
+ /**
230
+ * A driven change's options for core's `Batch.animate`, toward `targetOf`, from `fromOf`'s first stops
231
+ * when it gives them, on its call's transitions: each key's own, else its Default transition toward the
232
+ * member's target, held by the key's delay; every key at once when the call skips; its `stagger()`
233
+ * counting the members it moves.
234
+ */
235
+ export const animateOptions = (
236
+ planning: Planning,
237
+ call: ChangeCall,
238
+ targetOf: (slot: number, k: number) => number,
239
+ fromOf: ((slot: number, k: number) => number) | undefined,
240
+ ): Taken<Batch.AnimateOptions> => {
241
+ const transition = Bool.match(call.skipAnimations, {
242
+ onTrue: () => (): Batch.Transition => INSTANT,
243
+ onFalse: () => {
244
+ const planned = plannedOf(planning.positionalKeys, planning.keys, UndefinedOr.map(call.transition, unstaggered), call.reducedMotion, planning.fail)
245
+ return (slot: number, k: number): Batch.Transition => {
246
+ const plan = planned[k] as KeyPlan
247
+ if (Predicate.isNotUndefined(plan.own)) return plan.own
248
+ return delayedBy(planning.defaultFor(k, targetOf(slot, k)), plan.delay)
249
+ }
250
+ },
251
+ })
252
+ const options: { -readonly [K in keyof Taken<Batch.AnimateOptions>]: Taken<Batch.AnimateOptions>[K] } = { head: call.head, transition, onLanded: call.settled }
253
+ if (Predicate.isNotUndefined(fromOf)) options.from = fromOf
254
+ if (Predicate.isNotUndefined(call.taken)) options.onTaken = call.taken
255
+ if (Predicate.isNotUndefined(call.onMemberLanded)) options.onMemberLanded = call.onMemberLanded
256
+ const delay = Bool.match(call.skipAnimations, { onTrue: () => undefined, onFalse: () => staggerOf(call.transition) })
257
+ if (Predicate.isNotUndefined(delay)) options.delay = delay
258
+ return options
259
+ }
260
+
261
+ /**
262
+ * How a binding names its members for a call, by the number it passes for each (its slot in the Batch
263
+ * for an `animate` call, the binding's own number for a Segment's): their place in its list, their count,
264
+ * and what an error calls them.
265
+ */
266
+ export interface Members {
267
+ /** A member's index in its list: what a function of the index is given. */
268
+ readonly indexOf: (id: number) => number
269
+ /** How many members the Batch has: what a function of the index is given as the count. */
270
+ readonly count: () => number
271
+ /** What an error calls the member. */
272
+ readonly nameOf: (id: number) => string
273
+ }
274
+
275
+ /** An `animate` call's targets for each member's key, and its first stops when it gives any: `NaN` for none. */
276
+ export interface CallTargets {
277
+ readonly toOf: (slot: number, k: number) => number
278
+ readonly fromOf: ((slot: number, k: number) => number) | undefined
279
+ }
280
+
281
+ /**
282
+ * An `animate` call's `given` targets for `slots`' members, worked out once: each key one of the Batch's
283
+ * (`keyIndex`), its value a number, two stops (its first and its target), or a function of a member's
284
+ * index and the count that gives one; else an error naming it.
285
+ */
286
+ // Per member per key at a call (#665): statements.
287
+ export const callTargets = (planning: Planning, keyIndex: ReadonlyMap<string, number>, members: Members, slots: ReadonlyArray<number>, given: Readonly<Record<string, unknown>>): CallTargets => {
288
+ const { keys, fail } = planning
289
+ const stride = keys.length
290
+ const top = Arr.reduce(slots, 0, (highest, slot) => Math.max(highest, slot))
291
+ const tos = new Float64Array((top + 1) * stride).fill(Number.NaN)
292
+ const froms = new Float64Array((top + 1) * stride).fill(Number.NaN)
293
+ let firsts = false
294
+ /** One stop's value for the member in `slot`: a number, or a function's of its index and the count. */
295
+ const stopAt = (key: string, stop: unknown, slot: number): number => {
296
+ let value = stop
297
+ if (Predicate.isFunction(stop)) value = stop(members.indexOf(slot), members.count())
298
+ if (Predicate.isNumber(value)) return value
299
+ return fail(`an animate call's "${key}" gives ${members.nameOf(slot)} ${JSON.stringify(value)}: a Batch takes numbers`)
300
+ }
301
+ Arr.forEach(Rec.keys(given), (key) => {
302
+ const k = keyIndex.get(key)
303
+ if (Predicate.isUndefined(k)) return fail(`an animate call gives "${key}", which isn't one of the Batch's keys (${keys.join(", ")})`)
304
+ const value = given[key]
305
+ Arr.forEach(slots, (slot) => {
306
+ const at = slot * stride + k
307
+ let stops = value
308
+ if (Predicate.isFunction(value)) stops = value(members.indexOf(slot), members.count())
309
+ if (isPair(stops)) {
310
+ froms[at] = stopAt(key, stops[0], slot)
311
+ tos[at] = stopAt(key, stops[1], slot)
312
+ firsts = true
313
+ return
314
+ }
315
+ if (Predicate.isNumber(stops)) {
316
+ tos[at] = stops
317
+ return
318
+ }
319
+ return fail(`an animate call's "${key}" is ${JSON.stringify(stops)}: a Batch takes a number or two, its first and its target, or a function of a member's index that gives them`)
320
+ })
321
+ })
322
+ const toOf = (slot: number, k: number): number => tos[slot * stride + k] as number
323
+ const fromOf = (slot: number, k: number): number => froms[slot * stride + k] as number
324
+ return { toOf, fromOf: Bool.match(firsts, { onTrue: () => fromOf, onFalse: () => undefined }) }
325
+ }
326
+
327
+ /**
328
+ * A sequence's Segment of a Batch's values (Q38, Q39), for the members moving there, in order: each key
329
+ * one of the Batch's (`hasKey`), its value a number, `null` or stops, or a function of a member's index
330
+ * and the count that gives them, called for each member as core's Sequence compiles it.
331
+ */
332
+ export const segmentValues = (
333
+ planning: Planning,
334
+ hasKey: (key: string) => boolean,
335
+ members: Members,
336
+ moving: ReadonlyArray<number>,
337
+ target: Readonly<Record<string, unknown>>,
338
+ ): Readonly<Record<string, Sequence.Value>> => {
339
+ const { keys, fail } = planning
340
+ const values: Record<string, Sequence.Value> = {}
341
+ Arr.forEach(Rec.keys(target), (key) => {
342
+ const value = target[key]
343
+ if (Predicate.isUndefined(value)) return
344
+ if (!hasKey(key)) return fail(`a sequence's Segment of a Batch gives "${key}", which isn't one of its keys (${keys.join(", ")})`)
345
+ if (Predicate.isFunction(value)) {
346
+ values[key] = (index: number) => segmentValueOf(key, value(members.indexOf(moving[index] as number), members.count()), members.nameOf(moving[index] as number), fail)
347
+ return
348
+ }
349
+ values[key] = segmentValueOf(key, value, undefined, fail)
350
+ })
351
+ return values
352
+ }
353
+
354
+ /** A sequence's call of a Batch's members: its scope's settings. */
355
+ export interface SequenceCall {
356
+ readonly reducedMotion: boolean
357
+ readonly skipAnimations: boolean
358
+ }
359
+
360
+ /**
361
+ * A sequence's keyframes for each member's key (#665, Q36), from the animation core's Sequence compiled
362
+ * for the member in `slot` (`animationAt`): its stops and tween; reduced motion's Snap of a positional
363
+ * key, or `skipAnimations`, landing it at once where its run would end.
364
+ */
365
+ // Per member per key, once at its first play (#665): statements.
366
+ export const keyframesFor = (planning: Planning, call: SequenceCall, animationAt: (slot: number) => Sequence.Animation) =>
367
+ (slot: number, k: number): Batch.Keyframes | undefined => {
368
+ const key = planning.keys[k] as string
369
+ const animation = animationAt(slot)
370
+ const given = animation.keyframes[key]
371
+ if (Predicate.isUndefined(given)) return undefined
372
+ const transition = UndefinedOr.getOrThrow(animation.transition[key])
373
+ const stops = Arr.map(given, stopNumber)
374
+ const snaps = call.reducedMotion && planning.positionalKeys.isPositional(key)
375
+ if (!call.skipAnimations && !snaps) return { stops, transition }
376
+ // Where its run would end, from where it is: after its delay for reduced motion's Snap, at once when
377
+ // skipped. Its last stop is its last number: a sequence ends a key with a `null` when its last Segment ends first.
378
+ const end = ReducedMotion.endOf(stops[0] as number, lastNumber(stops), transition)
379
+ let delay = 0
380
+ if (!call.skipAnimations && Predicate.isNotUndefined(transition.delay)) delay = transition.delay
381
+ return { stops: [Number.NaN, end], transition: landingAfter(delay) }
382
+ }
383
+
384
+ /** Whether a sequence's subject is a Batch member's entry: a binding and its member's number. */
385
+ export const isMember: Predicate.Refinement<unknown, Imperative.BatchMember> = /*#__PURE__*/ Predicate.and(
386
+ /*#__PURE__*/ Predicate.hasProperty("binding"),
387
+ /*#__PURE__*/ Predicate.hasProperty("member"),
388
+ ) as Predicate.Refinement<unknown, Imperative.BatchMember>
389
+
390
+ /**
391
+ * A compiled sequence's parts (Q40): each Batch's members as one part, in the order they first appear,
392
+ * with their animations; every other subject as it is. `restOf` gives what of a member's animation its
393
+ * Subject takes itself (the DOM's member element's keys the Batch doesn't draw), when it takes any.
394
+ */
395
+ export const sequencePartsOf = <X, S>(
396
+ compiled: ReadonlyArray<readonly [X | Imperative.BatchMember, Sequence.Animation]>,
397
+ restOf?: (member: Imperative.BatchMember, animation: Sequence.Animation) => readonly [S, Sequence.Animation] | undefined,
398
+ ): { readonly batches: ReadonlyArray<Imperative.SequencePart>; readonly others: ReadonlyArray<readonly [X | S, Sequence.Animation]> } => {
399
+ const byBinding = new Map<Imperative.BatchCalls, { readonly members: Array<number>; readonly animations: Array<Sequence.Animation> }>()
400
+ const others: Array<readonly [X | S, Sequence.Animation]> = []
401
+ Arr.forEach(compiled, ([subject, animation]) => {
402
+ if (!isMember(subject)) {
403
+ others.push([subject as X, animation])
404
+ return
405
+ }
406
+ let part = byBinding.get(subject.binding)
407
+ if (Predicate.isUndefined(part)) {
408
+ part = { members: [], animations: [] }
409
+ byBinding.set(subject.binding, part)
410
+ }
411
+ part.members.push(subject.member)
412
+ part.animations.push(animation)
413
+ if (Predicate.isUndefined(restOf)) return
414
+ const rest = restOf(subject, animation)
415
+ if (Predicate.isNotUndefined(rest)) others.push(rest)
416
+ })
417
+ return { batches: Arr.map(Arr.fromIterable(byBinding), ([binding, part]): Imperative.SequencePart => ({ binding, ...part })), others }
418
+ }
419
+
@@ -208,6 +208,23 @@ export type WardicTransitionEntries = WardicValueEntries<WardicValueKey> & { rea
208
208
  /** Entries for the values `K`, and `default` for the rest (#301). */
209
209
  export type WardicValueEntries<K extends string> = { readonly default?: WardicValueTransition } & { readonly [P in K]?: WardicValueTransition }
210
210
 
211
+ /** Each member's keys, as one union: a union's own `keyof` is only the keys its members share. */
212
+ type KeysOfEach<T> = T extends unknown ? keyof T : never
213
+
214
+ /** A transition's own fields' names, on any arm, and its `layout` entry's. */
215
+ type TransitionFieldName = KeysOfEach<WardicTransitionWith<unknown>> | "layout"
216
+
217
+ /**
218
+ * A transition for a Subject whose keys are `K`: an entry under each of `K`, and `default`; no
219
+ * `layout`. A key named like one of the transition's own fields (`duration`, `type`, `delay`…) has
220
+ * no entry, since that name is the field's: it runs on `default` or the transition's own fields.
221
+ */
222
+ // #952: an Environment whose keys depend on its Subject (`@wardic/object`'s, `@wardic/three`'s) types
223
+ // its transitions so; one whose keys are global, `ValueKeys`' (`@wardic/dom`'s), `WardicTransition`.
224
+ // A name holds the field or the entry, never both, and the runtime reads any object under it as an
225
+ // entry (RetargetLegs.entriesOf): a field's name is left out of the entries, so it stays the field's.
226
+ export type WardicTransitionFor<K extends string> = WardicTransitionWith<WardicValueEntries<Exclude<K, TransitionFieldName>>>
227
+
211
228
  /**
212
229
  * A variant's own transition, or a target's: it runs the animation that variant starts, in place of
213
230
  * the element's `transition`, unless `inherit: true` lays it over the element's, its own fields winning.
@@ -0,0 +1,172 @@
1
+ /**
2
+ * An Environment's **Frame effects** (CONTEXT.md): an app's own code, run at the end of each frame the
3
+ * Environment draws, after Wardic's writes for it, in the order the effects were added. A scene runs
4
+ * them in its Host loop before it renders; the DOM before paint. The Environment calls {@link
5
+ * FrameEffects.run} at its frame's end, and gives `make` its way to ask for a frame, so an effect whose
6
+ * inputs changed is run on a frame nothing else asked for.
7
+ *
8
+ * @example
9
+ * import * as FrameEffects from "@wardic/core/unstable/FrameEffects"
10
+ *
11
+ * const effects = FrameEffects.make({ requestFrame: () => host.wantFrame(), report: console.error })
12
+ * const remove = effects.add((time) => controls.update())
13
+ * effects.run(time) // the Environment's, at its frame's end
14
+ *
15
+ * Unstable, for Wardic's own packages: public, with no semver promise.
16
+ *
17
+ * @module
18
+ */
19
+ // Unstable: ADR-0071, decision 5. #882 (ADR-0073, *Amendment (#882)*, Q3): the slot for decision 19's Frame
20
+ // effects, one for every Environment. Not a phase of the Frame loop or of the gate: the loop ticks only
21
+ // while an animation runs, and the gate flushes only what was written, so a frame where an effect's only
22
+ // input moved (`createTime()`, an every-frame `controls.update()`) has neither.
23
+ import * as Effect from "effect/Effect"
24
+ import type * as Scope from "effect/Scope"
25
+ import * as Clock from "../Clock.ts"
26
+ import * as FrameLoop from "../FrameLoop.ts"
27
+ import * as RefreshFrameSource from "../RefreshFrameSource.ts"
28
+
29
+ /** What an Environment gives its Frame effects. */
30
+ export interface FrameEffectsOptions {
31
+ /** Asks the Environment for a frame, whose end runs the effects. Called once a request, until the run. */
32
+ readonly requestFrame: () => void
33
+ /** What an effect that throws reports: the rest of the frame's effects still run. */
34
+ readonly report: (defect: unknown) => void
35
+ }
36
+
37
+ /** An Environment's Frame effects: an ordered list it runs at each frame's end. */
38
+ export interface FrameEffects {
39
+ /** Run `effect` at the end of each frame from now on, after those added before it. Returns its remover. */
40
+ readonly add: (effect: (time: number) => void) => () => void
41
+ /** Ask for a frame whose end runs the effects, though nothing else asks for one: an input of one changed. */
42
+ readonly request: () => void
43
+ /** Whether a frame is asked for: a `request()` since the last `run`. */
44
+ readonly requested: () => boolean
45
+ /** The Environment's call at its frame's end, `time` in ms: every effect added before it, in order. */
46
+ readonly run: (time: number) => void
47
+ }
48
+
49
+ /** An effect in the list, and whether it's still in it. */
50
+ interface Entry {
51
+ readonly effect: (time: number) => void
52
+ live: boolean
53
+ }
54
+
55
+ /**
56
+ * An Environment's Frame effects, asking it for frames through `options.requestFrame`. An effect added
57
+ * while they run waits for the next frame's run, as a Refresh frame's callbacks do; one removed while
58
+ * they run, before its turn, isn't run.
59
+ */
60
+ export const make = (options: FrameEffectsOptions): FrameEffects => {
61
+ const { requestFrame, report } = options
62
+ // In order: the per-frame path, a plain array and loops, nothing allocated a frame.
63
+ const entries: Array<Entry> = []
64
+ let running = false
65
+ let removedInRun = 0
66
+ let asked = false
67
+
68
+ /** The entries no longer live taken out, in place, keeping the rest's order. */
69
+ const compact = (): void => {
70
+ let kept = 0
71
+ for (let i = 0; i < entries.length; i++) {
72
+ const entry = entries[i]
73
+ if (entry.live) entries[kept++] = entry
74
+ }
75
+ entries.length = kept
76
+ }
77
+
78
+ const add: FrameEffects["add"] = (effect) => {
79
+ const entry: Entry = { effect, live: true }
80
+ entries.push(entry)
81
+ return () => {
82
+ if (!entry.live) return
83
+ entry.live = false
84
+ if (running) {
85
+ removedInRun++
86
+ return
87
+ }
88
+ compact()
89
+ }
90
+ }
91
+
92
+ const request: FrameEffects["request"] = () => {
93
+ if (asked) return
94
+ asked = true
95
+ requestFrame()
96
+ }
97
+
98
+ const run: FrameEffects["run"] = (time) => {
99
+ asked = false
100
+ running = true
101
+ // Those added before the run: one added in it waits for the next frame.
102
+ const count = entries.length
103
+ try {
104
+ for (let i = 0; i < count; i++) {
105
+ const entry = entries[i]
106
+ if (!entry.live) continue
107
+ try {
108
+ entry.effect(time)
109
+ } catch (defect) {
110
+ report(defect)
111
+ }
112
+ }
113
+ } finally {
114
+ running = false
115
+ if (removedInRun > 0) {
116
+ removedInRun = 0
117
+ compact()
118
+ }
119
+ }
120
+ }
121
+
122
+ return { add, request, requested: () => asked, run }
123
+ }
124
+
125
+ /**
126
+ * Frame effects for an Environment on core's Frame loop and Refresh frames, the DOM's: run at the end
127
+ * of each tick, after the tick's hooks added before them (the Flush gate's flush, so after Wardic's
128
+ * writes for the frame), and, on a frame with no tick, on a Refresh frame of their own that `request()`
129
+ * asks for, which a tick withdraws. For as long as the Scope is open.
130
+ *
131
+ * @example
132
+ * const effects = yield* FrameEffects.onFrameLoop((defect) => console.error(defect))
133
+ * effects.add(() => camera.lookAt(target))
134
+ */
135
+ // #884's PR 1 (ADR-0073 decision 19, *Amendment (#882)*'s Q3): the DOM's slot, as `@wardic/object`'s
136
+ // `frame(t)` runs its own. The tick's hook as the gate's `flushTicked` is: its own frame withdrawn, run now.
137
+ export const onFrameLoop = (report: (defect: unknown) => void): Effect.Effect<FrameEffects, never, FrameLoop.FrameLoop | RefreshFrameSource.RefreshFrameSource | Clock.Clock | Scope.Scope> =>
138
+ Effect.gen(function* () {
139
+ const loop = yield* FrameLoop.FrameLoop
140
+ const { requestFrame, cancelFrame } = yield* RefreshFrameSource.RefreshFrameSource
141
+ const clock = yield* Clock.Clock
142
+ // The Refresh frame a request asked for, while it's pending.
143
+ let pending = false
144
+ let frame: unknown = undefined
145
+ const effects: FrameEffects = make({
146
+ requestFrame: () => {
147
+ pending = true
148
+ frame = requestFrame((time) => {
149
+ pending = false
150
+ effects.run(time)
151
+ })
152
+ },
153
+ report,
154
+ })
155
+ const ticked = (): undefined => {
156
+ if (pending) {
157
+ cancelFrame(frame)
158
+ pending = false
159
+ }
160
+ effects.run(clock.frameAt())
161
+ return undefined
162
+ }
163
+ yield* loop.afterTick(ticked)
164
+ yield* Effect.addFinalizer(() =>
165
+ Effect.sync(() => {
166
+ if (pending) cancelFrame(frame)
167
+ pending = false
168
+ })
169
+ )
170
+ return effects
171
+ })
172
+
@@ -17,14 +17,10 @@ import type * as WardicServices from "./WardicServices.ts"
17
17
 
18
18
  /**
19
19
  * How long a key's velocity holds once nothing has moved it, in ms (Motion's `MAX_VELOCITY_DELTA`):
20
- * past it, the key is at rest. A velocity worked out from two frames further apart takes this as their
21
- * time apart.
20
+ * past it, the key is at rest. A velocity worked out over a longer step takes this as the step's time.
22
21
  */
23
22
  export const MAX_VELOCITY_DELTA = 30
24
23
 
25
- /** A frame at 60 Hz, in ms: the time a leg's first frame is read over, from where it started (Motion's first-frame delta). */
26
- export const NOMINAL_FRAME = 1000 / 60
27
-
28
24
  // #672: declared here, as core's `Clock.ts` declares it, since core builds with no DOM in its lib.
29
25
  declare const performance: { readonly now: () => number }
30
26