@link-foundation/ui-animation 0.0.0-stage → 0.1.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 (51) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +454 -2
  3. package/package.json +77 -4
  4. package/src/backgrounds/README.md +131 -0
  5. package/src/backgrounds/beams.d.ts +21 -0
  6. package/src/backgrounds/beams.js +140 -0
  7. package/src/backgrounds/common.d.ts +23 -0
  8. package/src/backgrounds/common.js +322 -0
  9. package/src/backgrounds/grid.d.ts +16 -0
  10. package/src/backgrounds/grid.js +122 -0
  11. package/src/backgrounds/nebula.d.ts +9 -0
  12. package/src/backgrounds/nebula.js +57 -0
  13. package/src/backgrounds/rain-cleanup.js +77 -0
  14. package/src/backgrounds/rain.d.ts +33 -0
  15. package/src/backgrounds/rain.js +238 -0
  16. package/src/backgrounds/shader.d.ts +14 -0
  17. package/src/backgrounds/shader.js +151 -0
  18. package/src/backgrounds/sprites.js +72 -0
  19. package/src/backgrounds/starfield.d.ts +38 -0
  20. package/src/backgrounds/starfield.js +168 -0
  21. package/src/clock.js +98 -0
  22. package/src/compile-waapi.js +147 -0
  23. package/src/diagnostics.js +51 -0
  24. package/src/easing.js +327 -0
  25. package/src/effects/decipher.js +83 -0
  26. package/src/effects.js +44 -0
  27. package/src/index.d.ts +581 -0
  28. package/src/index.js +74 -0
  29. package/src/layers.js +88 -0
  30. package/src/model.js +636 -0
  31. package/src/player.js +267 -0
  32. package/src/random.js +62 -0
  33. package/src/recorder/buffer.js +40 -0
  34. package/src/recorder/clock.js +2 -0
  35. package/src/recorder/format.js +125 -0
  36. package/src/recorder/input.js +53 -0
  37. package/src/recorder/recorder.js +183 -0
  38. package/src/recorder/redact.js +43 -0
  39. package/src/recorder/replay.js +115 -0
  40. package/src/recorder/state-at.js +62 -0
  41. package/src/recorder/store.js +92 -0
  42. package/src/recorder/to-playwright.js +113 -0
  43. package/src/recorder/verify.js +49 -0
  44. package/src/run.js +283 -0
  45. package/src/sample.js +160 -0
  46. package/src/timeline.js +115 -0
  47. package/src/timing.js +172 -0
  48. package/src/tokens.js +32 -0
  49. package/src/types.js +130 -0
  50. package/src/validate.js +218 -0
  51. package/src/values.js +331 -0
package/src/run.js ADDED
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Runs of the player: one animation on one element, and the control over a
3
+ * set of runs that start together.
4
+ *
5
+ * Every function takes the player context:
6
+ * `{ clock, animate, isCss, resolveToken, apply, seed, elementFor, motionOf }`.
7
+ */
8
+
9
+ import { toWaapi } from './compile-waapi.js';
10
+ import { sampleLayers } from './layers.js';
11
+ import { sampleTyped } from './sample.js';
12
+ import { endTime, reducedMotionVariant } from './timing.js';
13
+ import { outputValue } from './values.js';
14
+
15
+ /** Write a non-CSS value on an element. */
16
+ export function defaultApply(element, property, value) {
17
+ if (property === 'text') {
18
+ element.textContent = String(value);
19
+ return;
20
+ }
21
+ if (property === 'value' && 'value' in element) {
22
+ element.value = value;
23
+ return;
24
+ }
25
+ element.setAttribute(property, String(value));
26
+ }
27
+
28
+ function readOriginal(element, property) {
29
+ if (property === 'text') {
30
+ return element.textContent;
31
+ }
32
+ if (property === 'value' && 'value' in element) {
33
+ return element.value;
34
+ }
35
+ return element.getAttribute(property);
36
+ }
37
+
38
+ function restoreOriginal(element, property, original) {
39
+ if (property !== 'text' && property !== 'value' && original === null) {
40
+ element.removeAttribute(property);
41
+ return;
42
+ }
43
+ defaultApply(element, property, original);
44
+ }
45
+
46
+ function restoreAll(run) {
47
+ for (const [property, original] of run.originals) {
48
+ restoreOriginal(run.element, property, original);
49
+ }
50
+ run.originals.clear();
51
+ }
52
+
53
+ function abortError() {
54
+ const message = 'The animation was cancelled';
55
+ if (typeof globalThis.DOMException === 'function') {
56
+ return new globalThis.DOMException(message, 'AbortError');
57
+ }
58
+ const error = new Error(message);
59
+ error.name = 'AbortError';
60
+ return error;
61
+ }
62
+
63
+ /** The variant of an animation that plays on an element. */
64
+ export function variantFor(context, animation, element) {
65
+ return context.motionOf(element) === 'reduced'
66
+ ? reducedMotionVariant(animation)
67
+ : animation;
68
+ }
69
+
70
+ /** Start the CSS tracks of a run on the Web Animations API. */
71
+ function startWaapi(context, variant, element, start) {
72
+ const { keyframes, options: timing } = toWaapi(variant, {
73
+ resolveToken: context.resolveToken,
74
+ isCssProperty: context.isCss,
75
+ });
76
+ const delay = (timing.delay ?? 0) + start;
77
+ if (delay !== 0) {
78
+ timing.delay = delay;
79
+ }
80
+ const waapi = context.animate(element, keyframes, timing) ?? null;
81
+ waapi?.finished?.catch?.(() => {});
82
+ return waapi;
83
+ }
84
+
85
+ /**
86
+ * One animation on one element, starting `start` ms after the play.
87
+ * @param {object} context
88
+ * @param {import('./types.js').Animation} animation
89
+ * @param {Element|null} element
90
+ * @param {number} start
91
+ * @param {import('./types.js').PlayOptions} playOptions
92
+ */
93
+ export function startRun(context, animation, element, start, playOptions) {
94
+ const variant = variantFor(context, animation, element);
95
+ const frameTracks = variant.tracks.filter((t) => !context.isCss(t.property));
96
+ const hasCss = frameTracks.length < variant.tracks.length;
97
+ const hasFrames =
98
+ element !== null && (frameTracks.length > 0 || Boolean(variant.effect));
99
+ let input = playOptions.input;
100
+ if (hasFrames && input === undefined && variant.effect) {
101
+ input = variant.effect.params.text ?? readOriginal(element, 'text');
102
+ }
103
+ return {
104
+ animation: variant,
105
+ frameAnimation: { ...variant, tracks: frameTracks },
106
+ element,
107
+ start,
108
+ end: start + endTime(variant, context.resolveToken),
109
+ waapi:
110
+ element && hasCss ? startWaapi(context, variant, element, start) : null,
111
+ hasFrames,
112
+ originals: new Map(),
113
+ seed: playOptions.seed ?? context.seed,
114
+ input,
115
+ };
116
+ }
117
+
118
+ /** Write the frame-loop values of a run at play time `t`. */
119
+ export function applyFrame(context, run, t) {
120
+ if (!run.hasFrames) {
121
+ return;
122
+ }
123
+ const { values, effects } = sampleTyped(run.frameAnimation, t - run.start, {
124
+ resolveToken: context.resolveToken,
125
+ seed: run.seed,
126
+ input: run.input,
127
+ });
128
+ const written = { ...effects };
129
+ for (const [property, value] of values) {
130
+ written[property] = outputValue(value);
131
+ }
132
+ for (const [property, value] of Object.entries(written)) {
133
+ if (!run.originals.has(property)) {
134
+ run.originals.set(property, readOriginal(run.element, property));
135
+ }
136
+ context.apply(run.element, property, value);
137
+ }
138
+ // Without fill, a frame property goes back to its own value when the
139
+ // run has no effect (before its delay or after its end).
140
+ for (const [property, original] of run.originals) {
141
+ if (!Object.hasOwn(written, property)) {
142
+ restoreOriginal(run.element, property, original);
143
+ run.originals.delete(property);
144
+ }
145
+ }
146
+ }
147
+
148
+ function deferred() {
149
+ const out = {};
150
+ out.promise = new Promise((resolve, reject) => {
151
+ out.resolve = resolve;
152
+ out.reject = reject;
153
+ });
154
+ return out;
155
+ }
156
+
157
+ /**
158
+ * The control over a set of runs that start together.
159
+ * @param {object} context
160
+ * @param {object[]} runs
161
+ * @returns {import('./index.js').PlayControl}
162
+ */
163
+ export function createControl(context, runs) {
164
+ const { clock } = context;
165
+ const state = { startedAt: clock.now(), pausedAt: null, frame: null };
166
+ let settled = false;
167
+ let cancelled = false;
168
+ const done = deferred();
169
+ const end = Math.max(0, ...runs.map((r) => r.end));
170
+ const elapsed = () =>
171
+ state.pausedAt !== null ? state.pausedAt : clock.now() - state.startedAt;
172
+ const stopFrames = () => {
173
+ if (state.frame !== null) {
174
+ clock.cancelFrame(state.frame);
175
+ state.frame = null;
176
+ }
177
+ };
178
+
179
+ const tick = () => {
180
+ state.frame = null;
181
+ if (settled || state.pausedAt !== null) {
182
+ return;
183
+ }
184
+ const t = elapsed();
185
+ for (const run of runs) {
186
+ applyFrame(context, run, Math.min(t, run.end));
187
+ }
188
+ if (t >= end) {
189
+ settled = true;
190
+ done.resolve();
191
+ return;
192
+ }
193
+ state.frame = clock.requestFrame(tick);
194
+ };
195
+
196
+ const finished = done.promise
197
+ .then(() => Promise.all(runs.map((r) => r.waapi?.finished).filter(Boolean)))
198
+ .then(() => undefined);
199
+ finished.catch(() => {});
200
+
201
+ const control = {
202
+ finished,
203
+ get currentTime() {
204
+ return elapsed();
205
+ },
206
+ get runs() {
207
+ return runs.map((r) => ({
208
+ id: r.animation.id,
209
+ element: r.element,
210
+ start: r.start,
211
+ end: r.end,
212
+ }));
213
+ },
214
+ pause() {
215
+ if (state.pausedAt !== null || settled) {
216
+ return;
217
+ }
218
+ state.pausedAt = elapsed();
219
+ runs.forEach((r) => r.waapi?.pause?.());
220
+ stopFrames();
221
+ },
222
+ play() {
223
+ if (state.pausedAt === null || settled) {
224
+ return;
225
+ }
226
+ state.startedAt = clock.now() - state.pausedAt;
227
+ state.pausedAt = null;
228
+ runs.forEach((r) => r.waapi?.play?.());
229
+ tick();
230
+ },
231
+ seek(ms) {
232
+ if (settled) {
233
+ return;
234
+ }
235
+ const t = Math.max(0, ms);
236
+ if (state.pausedAt !== null) {
237
+ state.pausedAt = t;
238
+ } else {
239
+ state.startedAt = clock.now() - t;
240
+ }
241
+ for (const run of runs) {
242
+ if (run.waapi) {
243
+ run.waapi.currentTime = t;
244
+ }
245
+ applyFrame(context, run, Math.min(t, run.end));
246
+ }
247
+ },
248
+ cancel() {
249
+ if (cancelled) {
250
+ return;
251
+ }
252
+ cancelled = true;
253
+ settled = true;
254
+ stopFrames();
255
+ for (const run of runs) {
256
+ run.waapi?.cancel?.();
257
+ restoreAll(run);
258
+ }
259
+ done.reject(abortError());
260
+ },
261
+ /**
262
+ * The sampled values at the current time on `target` (default: the
263
+ * target of the first run), all runs on it combined.
264
+ */
265
+ values(target) {
266
+ const element =
267
+ target === undefined ? runs[0]?.element : context.elementFor(target);
268
+ const layers = runs
269
+ .filter((r) => r.element === element)
270
+ .map((r) => ({
271
+ animation: r.animation,
272
+ start: r.start,
273
+ seed: r.seed,
274
+ input: r.input,
275
+ }));
276
+ return sampleLayers(layers, elapsed(), {
277
+ resolveToken: context.resolveToken,
278
+ });
279
+ },
280
+ };
281
+ tick();
282
+ return control;
283
+ }
package/src/sample.js ADDED
@@ -0,0 +1,160 @@
1
+ /**
2
+ * `sample(animation, tMs, options)`: the values of an animation at a time.
3
+ * Pure and deterministic: the same animation, time and seed always give the
4
+ * same values (effects use the seed, never the platform random generator).
5
+ */
6
+
7
+ import { easingFunction } from './easing.js';
8
+ import { getEffect } from './effects.js';
9
+ import { resolveTiming, timingAt } from './timing.js';
10
+ import { interpolate, outputValue, resolveValue } from './values.js';
11
+
12
+ /** The neutral value of an additive animation of `property`. */
13
+ function neutral(property, value) {
14
+ const identity = property === 'scale' ? 1 : 0;
15
+ if (value.type === 'number') {
16
+ return { type: 'number', value: identity };
17
+ }
18
+ if (value.type === 'text') {
19
+ return {
20
+ type: 'text',
21
+ parts: value.parts.map((part) =>
22
+ typeof part === 'object' ? { value: identity, unit: part.unit } : part
23
+ ),
24
+ };
25
+ }
26
+ return value;
27
+ }
28
+
29
+ /**
30
+ * The value of one track at directed iteration progress `p`: the segment of the keys
31
+ * around `p`, with its first key easing or the animation easing as default.
32
+ * Easing changes interpolation within a segment, never the key offsets.
33
+ */
34
+ function trackValue(track, p, resolveToken, defaultEasing) {
35
+ const keys = track.keys;
36
+ if (keys.length === 1) {
37
+ return resolveValue(keys[0].value, resolveToken);
38
+ }
39
+ let i = 0;
40
+ while (i < keys.length - 2 && p >= keys[i + 1].offset) {
41
+ i++;
42
+ }
43
+ const from = keys[i];
44
+ const to = keys[i + 1];
45
+ const first = keys[0];
46
+ const last = keys[keys.length - 1];
47
+ // Before the first key (or after the last) that is not at 0 (or 1) the
48
+ // value holds; there is no underlying value to blend from.
49
+ if (p < first.offset && first.offset > 0) {
50
+ return resolveValue(first.value, resolveToken);
51
+ }
52
+ if (p > last.offset && last.offset < 1) {
53
+ return resolveValue(last.value, resolveToken);
54
+ }
55
+ const span = to.offset - from.offset;
56
+ if (span <= 0) {
57
+ return resolveValue(p < to.offset ? from.value : to.value, resolveToken);
58
+ }
59
+ const local = (p - from.offset) / span;
60
+ const inside = local >= 0 && local <= 1;
61
+ const eased = inside
62
+ ? easingFunction(from.easing ?? defaultEasing, resolveToken)(local)
63
+ : local;
64
+ return interpolate(
65
+ resolveValue(from.value, resolveToken),
66
+ resolveValue(to.value, resolveToken),
67
+ eased
68
+ );
69
+ }
70
+
71
+ /**
72
+ * The weight of an envelope at iteration progress `p` (0..1): `bell` is
73
+ * sin²(πp); `sustain` rises with a smoothstep over the attack, holds 1 and
74
+ * falls over the release (default 20% of the duration each).
75
+ */
76
+ export function envelopeWeight(envelope, p, duration) {
77
+ if (!envelope) {
78
+ return 1;
79
+ }
80
+ if (envelope.type === 'bell') {
81
+ return Math.sin(Math.PI * p) ** 2;
82
+ }
83
+ const fraction = (ms) =>
84
+ ms === undefined || !(duration > 0) ? 0.2 : Math.min(1, ms / duration);
85
+ const smooth = (x) => {
86
+ const c = Math.min(1, Math.max(0, x));
87
+ return c * c * (3 - 2 * c);
88
+ };
89
+ const attack = fraction(envelope.attack);
90
+ const release = fraction(envelope.release);
91
+ const rise = attack > 0 ? smooth(p / attack) : 1;
92
+ const fall = release > 0 ? smooth((1 - p) / release) : 1;
93
+ return Math.min(rise, fall);
94
+ }
95
+
96
+ /**
97
+ * The typed values of an animation at `tMs` (used by `sample`,
98
+ * `sampleLayers` and the validators).
99
+ * @param {import('./types.js').Animation} animation
100
+ * @param {number} tMs
101
+ * @param {import('./types.js').SampleOptions} [options]
102
+ */
103
+ export function sampleTyped(animation, tMs, options = {}) {
104
+ const { resolveToken } = options;
105
+ const timing = resolveTiming(animation, resolveToken);
106
+ const at = timingAt(timing, tMs);
107
+ const result = { active: at !== null, values: new Map(), effects: {} };
108
+ if (at === null) {
109
+ return result;
110
+ }
111
+ const weight = envelopeWeight(
112
+ animation.envelope,
113
+ at.progress,
114
+ timing.duration
115
+ );
116
+ const additive = animation.composite && animation.composite !== 'replace';
117
+ for (const track of animation.tracks) {
118
+ if (track.keys.length === 0) {
119
+ continue;
120
+ }
121
+ let value = trackValue(track, at.progress, resolveToken, animation.easing);
122
+ if (weight !== 1) {
123
+ const rest = additive
124
+ ? neutral(track.property, value)
125
+ : resolveValue(track.keys[0].value, resolveToken);
126
+ value = interpolate(rest, value, weight);
127
+ }
128
+ result.values.set(track.property, value);
129
+ }
130
+ if (animation.effect) {
131
+ const entry = getEffect(animation.effect.name);
132
+ if (entry) {
133
+ const { params } = animation.effect;
134
+ const seed = params.seed ?? options.seed ?? 0;
135
+ const input = options.input ?? params.text ?? '';
136
+ result.effects[entry.property] = entry.fn(input, at.eased, seed, params);
137
+ }
138
+ }
139
+ return result;
140
+ }
141
+
142
+ /**
143
+ * The values of an animation at `tMs` ms after it starts (its delay
144
+ * included): `{ scale: 0.96 }`, `{ translate: '0 4px' }`, `{ text: '...' }`.
145
+ * Numbers are numbers, every other value is CSS text, effect outputs are
146
+ * under their property. Empty when the animation has no effect at `tMs`
147
+ * (before or after it without fill).
148
+ * @param {import('./types.js').Animation} animation
149
+ * @param {number} tMs
150
+ * @param {import('./types.js').SampleOptions} [options]
151
+ * @returns {Record<string, number|string|unknown>}
152
+ */
153
+ export function sample(animation, tMs, options = {}) {
154
+ const { values, effects } = sampleTyped(animation, tMs, options);
155
+ const out = {};
156
+ for (const [property, value] of values) {
157
+ out[property] = outputValue(value);
158
+ }
159
+ return Object.assign(out, effects);
160
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * `flattenTimeline(model, id)`: a timeline as a flat schedule of plays,
3
+ * `[{ start, id, target }]`, sorted by start time.
4
+ *
5
+ * - the items of a timeline (and of `at` and `parallel`) start together;
6
+ * - `(at TIME ITEM...)` starts its items TIME after its parent;
7
+ * - `(sequence ITEM...)` starts each item when the one before ends;
8
+ * - `(stagger STEP ITEM... (targets A B C))` starts the i-th target (or,
9
+ * without targets, the i-th item) i * STEP after its parent;
10
+ * - `(play ID)` of a timeline plays it nested.
11
+ * An item ends when its last animation ends (delay + duration * iterations).
12
+ */
13
+
14
+ import { endTime, resolveTime } from './timing.js';
15
+
16
+ /**
17
+ * @param {import('./types.js').AnimationModel} model
18
+ * @param {string} id a timeline or an animation id
19
+ * @param {{ resolveToken?: (path: string) => unknown,
20
+ * variant?: (a: import('./types.js').Animation) => import('./types.js').Animation,
21
+ * target?: string|null }} [options]
22
+ * @returns {{ start: number, id: string, target: string|null }[]}
23
+ */
24
+ export function flattenTimeline(model, id, options = {}) {
25
+ const out = [];
26
+ const context = {
27
+ model,
28
+ resolveToken: options.resolveToken,
29
+ variant: options.variant ?? ((a) => a),
30
+ out,
31
+ stack: [],
32
+ };
33
+ play(context, { type: 'play', id, target: options.target ?? null }, 0, null);
34
+ return out.sort((a, b) => a.start - b.start);
35
+ }
36
+
37
+ /** Schedule one item at `start`; returns when it ends. */
38
+ function schedule(context, item, start, target) {
39
+ switch (item.type) {
40
+ case 'play':
41
+ return play(context, item, start, target);
42
+ case 'at':
43
+ return parallel(
44
+ context,
45
+ item.items,
46
+ start + (resolveTime(item.time, context.resolveToken) ?? 0),
47
+ target
48
+ );
49
+ case 'parallel':
50
+ return parallel(context, item.items, start, target);
51
+ case 'sequence': {
52
+ let cursor = start;
53
+ for (const child of item.items) {
54
+ cursor = schedule(context, child, cursor, target);
55
+ }
56
+ return cursor;
57
+ }
58
+ case 'stagger':
59
+ return stagger(context, item, start, target);
60
+ default:
61
+ return start;
62
+ }
63
+ }
64
+
65
+ function parallel(context, items, start, target) {
66
+ let end = start;
67
+ for (const item of items) {
68
+ end = Math.max(end, schedule(context, item, start, target));
69
+ }
70
+ return end;
71
+ }
72
+
73
+ function stagger(context, item, start, target) {
74
+ const step = resolveTime(item.step, context.resolveToken) ?? 0;
75
+ let end = start;
76
+ if (item.targets && item.targets.length > 0) {
77
+ item.targets.forEach((each, i) => {
78
+ for (const child of item.items) {
79
+ end = Math.max(end, schedule(context, child, start + i * step, each));
80
+ }
81
+ });
82
+ return end;
83
+ }
84
+ item.items.forEach((child, i) => {
85
+ end = Math.max(end, schedule(context, child, start + i * step, target));
86
+ });
87
+ return end;
88
+ }
89
+
90
+ function play(context, item, start, inherited) {
91
+ const { model } = context;
92
+ const targets =
93
+ item.targets && item.targets.length > 0
94
+ ? item.targets
95
+ : [item.target ?? inherited];
96
+ const timeline = model.timelines.get(item.id);
97
+ if (timeline) {
98
+ if (context.stack.includes(item.id)) {
99
+ return start;
100
+ }
101
+ context.stack.push(item.id);
102
+ const end = parallel(context, timeline.items, start, targets[0] ?? null);
103
+ context.stack.pop();
104
+ return end;
105
+ }
106
+ const animation = model.animations.get(item.id);
107
+ if (!animation) {
108
+ return start;
109
+ }
110
+ const length = endTime(context.variant(animation), context.resolveToken);
111
+ for (const target of targets) {
112
+ context.out.push({ start, id: item.id, target: target ?? null });
113
+ }
114
+ return start + length;
115
+ }