@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/player.js ADDED
@@ -0,0 +1,267 @@
1
+ /**
2
+ * `createPlayer(handle, options)`: plays animations and timelines on the
3
+ * elements of a ui-dom render handle.
4
+ *
5
+ * - CSS tracks run on the Web Animations API (`options.animate`, default
6
+ * `element.animate(keyframes, options)`);
7
+ * - effects (`decipher`, ...) and non-CSS tracks (`text`, ...) run in a
8
+ * frame loop driven by `options.clock`, which also decides when
9
+ * `finished` resolves, so a manual clock makes playback deterministic;
10
+ * - under reduced motion the `(reduced-motion ...)` variant plays (or, when
11
+ * there is none, only the opacity tracks, with duration 0). The default
12
+ * `motion` is `reduced` when the closest `[data-motion]` ancestor of the
13
+ * element says `reduced` or the user agent prefers reduced motion.
14
+ */
15
+
16
+ import { systemClock } from './clock.js';
17
+ import { isCssProperty as defaultIsCss } from './compile-waapi.js';
18
+ import { loadAnimations, ANIMATION_STATES } from './model.js';
19
+ import { createControl, defaultApply, startRun, variantFor } from './run.js';
20
+ import { flattenTimeline } from './timeline.js';
21
+
22
+ /**
23
+ * The default motion preference of an element: `reduced` when its closest
24
+ * `[data-motion]` boundary says `reduced` or the user agent prefers reduced
25
+ * motion; an explicit `data-motion="full"` does not override the user
26
+ * agent preference (the safe default).
27
+ * @param {Element|null} element
28
+ * @returns {'full'|'reduced'}
29
+ */
30
+ export function defaultMotion(element) {
31
+ const boundary = element?.closest?.('[data-motion]');
32
+ if (boundary?.getAttribute('data-motion') === 'reduced') {
33
+ return 'reduced';
34
+ }
35
+ const query = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)');
36
+ return query?.matches ? 'reduced' : 'full';
37
+ }
38
+
39
+ /** How a player finds the element of an id. */
40
+ function elementLookup(handle) {
41
+ return (id) => {
42
+ if (id === null || id === undefined) {
43
+ return null;
44
+ }
45
+ if (typeof handle === 'function') {
46
+ return handle(id) ?? null;
47
+ }
48
+ if (handle && typeof handle.nodeFor === 'function') {
49
+ return handle.nodeFor(id) ?? null;
50
+ }
51
+ return globalThis.document?.getElementById(id) ?? null;
52
+ };
53
+ }
54
+
55
+ function emptyModel() {
56
+ return {
57
+ animations: new Map(),
58
+ timelines: new Map(),
59
+ triggers: [],
60
+ diagnostics: [],
61
+ };
62
+ }
63
+
64
+ /** Merge animations (Links Notation text or a loaded model) into `model`. */
65
+ function loadInto(model, source) {
66
+ const loaded = typeof source === 'string' ? loadAnimations(source) : source;
67
+ for (const [id, a] of loaded.animations) {
68
+ model.animations.set(id, a);
69
+ }
70
+ for (const [id, t] of loaded.timelines) {
71
+ model.timelines.set(id, t);
72
+ }
73
+ model.triggers.push(...(loaded.triggers ?? []));
74
+ model.diagnostics.push(...(loaded.diagnostics ?? []));
75
+ return loaded;
76
+ }
77
+
78
+ /** Play an animation or a timeline. */
79
+ function playId(context, id, playOptions = {}) {
80
+ const { model } = context;
81
+ if (!model.animations.has(id) && !model.timelines.has(id)) {
82
+ throw new RangeError(`unknown animation or timeline "${id}"`);
83
+ }
84
+ const targetOf = (entry, animation) =>
85
+ context.elementFor(entry.target ?? animation.target);
86
+ const schedule = flattenTimeline(model, id, {
87
+ resolveToken: context.resolveToken,
88
+ variant: (animation) =>
89
+ variantFor(
90
+ context,
91
+ animation,
92
+ context.elementFor(playOptions.target ?? animation.target)
93
+ ),
94
+ target: playOptions.target ?? null,
95
+ });
96
+ const runs = schedule.map((entry) => {
97
+ const animation = model.animations.get(entry.id);
98
+ const element = targetOf(entry, animation);
99
+ return startRun(context, animation, element, entry.start, playOptions);
100
+ });
101
+ const control = createControl(context, runs);
102
+ const run = ++context.nextRun;
103
+ const recordedOptions = {
104
+ ...playOptions,
105
+ seed: playOptions.seed ?? context.seed ?? 0,
106
+ };
107
+ context.emit({ kind: 'play', id, run, options: recordedOptions });
108
+ const cancel = control.cancel;
109
+ let cancelled = false;
110
+ control.cancel = () => {
111
+ if (!cancelled) {
112
+ cancelled = true;
113
+ context.emit({ kind: 'cancel', id, run, options: recordedOptions });
114
+ }
115
+ cancel();
116
+ };
117
+ return control;
118
+ }
119
+
120
+ const isOn = (values) =>
121
+ Array.isArray(values) && values.length > 0 && values[0] !== 'false';
122
+
123
+ /** `(on STATE (play ID [(target ID)]))` properties of a store element. */
124
+ function storeTriggers(store, id, state) {
125
+ const out = [];
126
+ for (const property of store.get(id)?.properties ?? []) {
127
+ const [name, playLink] = property.values;
128
+ const plays =
129
+ property.name === 'on' &&
130
+ name === state &&
131
+ Array.isArray(playLink) &&
132
+ playLink[0] === 'play';
133
+ if (!plays) {
134
+ continue;
135
+ }
136
+ const targetLink = playLink
137
+ .slice(2)
138
+ .find((v) => Array.isArray(v) && v[0] === 'target');
139
+ out.push({
140
+ state,
141
+ element: id,
142
+ animation: playLink[1],
143
+ target: targetLink?.[1] ?? id,
144
+ });
145
+ }
146
+ return out;
147
+ }
148
+
149
+ /**
150
+ * The plays that fire when element `id` enters `state`: the model triggers
151
+ * of that element (an animation's own `(on STATE)` fires on its target) and
152
+ * the `(on STATE (play ...))` properties of the element in the store.
153
+ * @returns {{ animation: string, target: string }[]}
154
+ */
155
+ export function triggersFor(model, store, id, state) {
156
+ const found = [
157
+ ...model.triggers.filter((t) => t.state === state && t.element === id),
158
+ ...storeTriggers(store, id, state),
159
+ ];
160
+ const seen = new Set();
161
+ const out = [];
162
+ for (const t of found) {
163
+ const play = { animation: t.animation, target: t.target ?? t.element };
164
+ const key = `${play.animation}@${play.target}`;
165
+ if (!seen.has(key)) {
166
+ seen.add(key);
167
+ out.push(play);
168
+ }
169
+ }
170
+ return out;
171
+ }
172
+
173
+ /** The state of an update event that just turned on, or `null`. */
174
+ function enteredState(event) {
175
+ const entered =
176
+ event.origin !== 'replay' &&
177
+ event.type === 'update' &&
178
+ ANIMATION_STATES.includes(event.prop) &&
179
+ isOn(event.after) &&
180
+ !isOn(event.before);
181
+ return entered ? event.prop : null;
182
+ }
183
+
184
+ function bindStore(context, store) {
185
+ const { model } = context;
186
+ const running = new Map();
187
+ return store.subscribe((events) => {
188
+ for (const event of events) {
189
+ const state = enteredState(event);
190
+ if (state === null) {
191
+ continue;
192
+ }
193
+ for (const trigger of triggersFor(model, store, event.id, state)) {
194
+ const known =
195
+ model.animations.has(trigger.animation) ||
196
+ model.timelines.has(trigger.animation);
197
+ if (!known) {
198
+ continue;
199
+ }
200
+ const key = `${trigger.animation}@${trigger.target}`;
201
+ running.get(key)?.cancel();
202
+ const run = playId(context, trigger.animation, {
203
+ target: trigger.target,
204
+ });
205
+ running.set(key, run);
206
+ run.finished
207
+ .then(() => running.get(key) === run && running.delete(key))
208
+ .catch(() => {});
209
+ }
210
+ }
211
+ });
212
+ }
213
+
214
+ /**
215
+ * @param {import('./types.js').ElementSource} handle
216
+ * @param {import('./types.js').PlayerOptions} [options]
217
+ * @returns {import('./types.js').Player}
218
+ */
219
+ export function createPlayer(handle, options = {}) {
220
+ const model = emptyModel();
221
+ const motion = options.motion ?? defaultMotion;
222
+ const listeners = new Set();
223
+ const context = {
224
+ nextRun: 0,
225
+ emit: (event) => {
226
+ for (const listener of listeners) {
227
+ listener(event);
228
+ }
229
+ },
230
+ model,
231
+ clock: options.clock ?? systemClock(),
232
+ animate:
233
+ options.animate ??
234
+ ((element, keyframes, timing) => element.animate(keyframes, timing)),
235
+ isCss: options.isCssProperty ?? defaultIsCss,
236
+ resolveToken: options.resolveToken,
237
+ apply: options.apply ?? defaultApply,
238
+ seed: options.seed,
239
+ elementFor: elementLookup(handle),
240
+ motionOf: (element) =>
241
+ typeof motion === 'function' ? motion(element) : motion,
242
+ };
243
+ if (options.animations !== undefined) {
244
+ loadInto(model, options.animations);
245
+ }
246
+ return {
247
+ model,
248
+ subscribe(listener) {
249
+ listeners.add(listener);
250
+ return () => listeners.delete(listener);
251
+ },
252
+ /** Merge animations (Links Notation text or a loaded model). */
253
+ load: (source) => loadInto(model, source),
254
+ /** Play an animation or a timeline. */
255
+ play: (id, playOptions) => playId(context, id, playOptions),
256
+ /**
257
+ * Play the triggers of element states: when the store sets the
258
+ * property named after a state (`pressed`, `hover`, `focus`,
259
+ * `disabled`) to a value other than `false`, the animations of
260
+ * `(on STATE ...)` play. A trigger that fires again cancels its
261
+ * previous run first. Returns the unsubscribe function.
262
+ */
263
+ bindTriggers: (store) => bindStore(context, store),
264
+ /** Whether an element plays the reduced-motion variants. */
265
+ motion: (id) => context.motionOf(context.elementFor(id)),
266
+ };
267
+ }
package/src/random.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Seeded pseudo-random numbers. Every random choice of ui-animation goes
3
+ * through {@link seededRandom}, so a sample at a time and a seed is always the
4
+ * same value: the package never calls the platform random generator.
5
+ */
6
+
7
+ /**
8
+ * A 32-bit unsigned seed from a number or a string. Numbers are truncated to
9
+ * 32 bits; strings are hashed with FNV-1a.
10
+ * @param {number|string} seed
11
+ * @returns {number}
12
+ */
13
+ export function seedNumber(seed) {
14
+ if (typeof seed === 'number' && Number.isFinite(seed)) {
15
+ return Math.trunc(seed) >>> 0;
16
+ }
17
+ return hashString(String(seed));
18
+ }
19
+
20
+ /** FNV-1a over the UTF-16 code units of `text`, 32-bit unsigned. */
21
+ export function hashString(text) {
22
+ let hash = 0x811c9dc5;
23
+ for (let i = 0; i < text.length; i++) {
24
+ hash ^= text.charCodeAt(i);
25
+ hash = Math.imul(hash, 0x01000193) >>> 0;
26
+ }
27
+ return hash >>> 0;
28
+ }
29
+
30
+ /**
31
+ * Mix several 32-bit integers into one (a small avalanche hash), for
32
+ * per-frame randomness that depends only on its inputs.
33
+ * @param {...number} parts
34
+ * @returns {number}
35
+ */
36
+ export function mix(...parts) {
37
+ let h = 0x9e3779b9;
38
+ for (const part of parts) {
39
+ h = Math.imul(h ^ (part >>> 0), 0x85ebca6b) >>> 0;
40
+ h ^= h >>> 13;
41
+ h = Math.imul(h, 0xc2b2ae35) >>> 0;
42
+ h ^= h >>> 16;
43
+ }
44
+ return h >>> 0;
45
+ }
46
+
47
+ /**
48
+ * A deterministic generator of numbers in [0, 1) (mulberry32): the same seed
49
+ * always gives the same sequence.
50
+ * @param {number|string} seed
51
+ * @returns {() => number}
52
+ */
53
+ export function seededRandom(seed) {
54
+ let state = seedNumber(seed);
55
+ return () => {
56
+ state = (state + 0x6d2b79f5) >>> 0;
57
+ let t = state;
58
+ t = Math.imul(t ^ (t >>> 15), t | 1);
59
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
60
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
61
+ };
62
+ }
@@ -0,0 +1,40 @@
1
+ /** Fixed-capacity ring; replacing adjacent field edits never reorders other events. */
2
+ export function createEventBuffer(capacity) {
3
+ if (!Number.isSafeInteger(capacity) || capacity < 1) {
4
+ throw new RangeError('maxEvents must be a positive integer');
5
+ }
6
+ const events = [];
7
+ let offset = 0;
8
+ let count = 0;
9
+ let truncated = false;
10
+ return {
11
+ append(event) {
12
+ const previous = count ? events[(offset + count - 1) % capacity] : null;
13
+ if (
14
+ event.kind === 'input' &&
15
+ event.args[0] === 'text' &&
16
+ previous?.kind === 'input' &&
17
+ previous.args[0] === 'text' &&
18
+ previous.args[1] === event.args[1]
19
+ ) {
20
+ events[(offset + count - 1) % capacity] = event;
21
+ return;
22
+ }
23
+ if (count === capacity) {
24
+ offset = (offset + 1) % capacity;
25
+ truncated = true;
26
+ count--;
27
+ }
28
+ events[(offset + count) % capacity] = event;
29
+ count++;
30
+ },
31
+ get size() {
32
+ return count;
33
+ },
34
+ get truncated() {
35
+ return truncated;
36
+ },
37
+ values: () =>
38
+ Array.from({ length: count }, (_, i) => events[(offset + i) % capacity]),
39
+ };
40
+ }
@@ -0,0 +1,2 @@
1
+ /** Recorder and player share one injectable clock. */
2
+ export { createManualClock, systemClock } from '../clock.js';
@@ -0,0 +1,125 @@
1
+ /** Recording links, read by the official parser through ui-core. */
2
+ import { formatLinks, parseLinks } from '@link-foundation/ui-core';
3
+
4
+ export const EVENT_KINDS = [
5
+ 'set',
6
+ 'insert',
7
+ 'remove',
8
+ 'move',
9
+ 'input',
10
+ 'play',
11
+ 'cancel',
12
+ 'mark',
13
+ ];
14
+ const HEADERS = [
15
+ 'started',
16
+ 'seed',
17
+ 'viewport',
18
+ 'document',
19
+ 'snapshot',
20
+ 'redacted',
21
+ 'truncated',
22
+ ];
23
+ function headerValue(name, args) {
24
+ if (name === 'snapshot') {
25
+ return formatLinks(args);
26
+ }
27
+ if (name === 'viewport') {
28
+ const size = args.map(Number);
29
+ if (
30
+ size.length !== 2 ||
31
+ size.some((n) => !Number.isSafeInteger(n) || n < 0)
32
+ ) {
33
+ throw new TypeError('Invalid viewport');
34
+ }
35
+ return size;
36
+ }
37
+ if (args.length !== 1 || typeof args[0] !== 'string') {
38
+ throw new TypeError(`Invalid ${name}`);
39
+ }
40
+ if (name === 'seed') {
41
+ const seed = Number(args[0]);
42
+ if (!Number.isSafeInteger(seed)) {
43
+ throw new TypeError('Invalid seed');
44
+ }
45
+ return seed;
46
+ }
47
+ if (['redacted', 'truncated'].includes(name)) {
48
+ if (!['true', 'false'].includes(args[0])) {
49
+ throw new TypeError(`Invalid ${name}`);
50
+ }
51
+ return args[0] === 'true';
52
+ }
53
+ return args[0];
54
+ }
55
+ function decodeEvent(args, previous) {
56
+ const [stamp, payload] = args;
57
+ const time =
58
+ typeof stamp === 'string' && stamp.endsWith('ms')
59
+ ? Number(stamp.slice(0, -2))
60
+ : NaN;
61
+ if (
62
+ args.length !== 2 ||
63
+ !Number.isSafeInteger(time) ||
64
+ time < previous ||
65
+ !Array.isArray(payload) ||
66
+ !EVENT_KINDS.includes(payload[0])
67
+ ) {
68
+ throw new TypeError('Invalid event or non-monotonic timestamp');
69
+ }
70
+ return { time, kind: payload[0], args: payload.slice(1) };
71
+ }
72
+ export function parseRecording(text) {
73
+ const roots = parseLinks(text);
74
+ const root = roots.find(
75
+ (link) => (link?.values ?? link)?.[0] === 'recording'
76
+ );
77
+ const values = root?.values ?? root;
78
+ if (!values) {
79
+ throw new TypeError('Expected a recording link');
80
+ }
81
+ const recording = { id: root.id ?? 'recording-1', events: [], headers: [] };
82
+ let previous = 0;
83
+ for (const field of values.slice(1)) {
84
+ if (!Array.isArray(field)) {
85
+ throw new TypeError('Expected a recording field');
86
+ }
87
+ const [name, ...args] = field;
88
+ if (name !== 'event') {
89
+ if (!HEADERS.includes(name) || recording.headers.includes(name)) {
90
+ throw new TypeError(`Unknown or duplicate header ${name}`);
91
+ }
92
+ recording.headers.push(name);
93
+ recording[name] = headerValue(name, args);
94
+ } else {
95
+ const event = decodeEvent(args, previous);
96
+ previous = event.time;
97
+ recording.events.push(event);
98
+ }
99
+ }
100
+ return recording;
101
+ }
102
+ export function serializeRecording(recording) {
103
+ const headers =
104
+ recording.headers ?? HEADERS.filter((key) => recording[key] !== undefined);
105
+ const fields = headers.map((key) => [
106
+ key,
107
+ ...(key === 'snapshot'
108
+ ? parseLinks(recording[key])
109
+ : key === 'viewport'
110
+ ? recording[key].map(String)
111
+ : [String(recording[key])]),
112
+ ]);
113
+ let previous = 0;
114
+ for (const event of recording.events) {
115
+ const raw = [`${event.time}ms`, [event.kind, ...event.args]];
116
+ decodeEvent(raw, previous);
117
+ previous = event.time;
118
+ fields.push(['event', ...raw]);
119
+ }
120
+ return formatLinks([
121
+ { id: recording.id ?? 'recording-1', values: ['recording', ...fields] },
122
+ ]);
123
+ }
124
+ export const asRecording = (source) =>
125
+ typeof source === 'string' ? parseRecording(source) : source;
@@ -0,0 +1,53 @@
1
+ import { sensitiveTarget } from './redact.js';
2
+
3
+ export const INPUT_EVENTS = [
4
+ 'pointerdown',
5
+ 'pointerup',
6
+ 'pointermove',
7
+ 'pointercancel',
8
+ 'keydown',
9
+ 'keyup',
10
+ 'wheel',
11
+ 'input',
12
+ 'focusin',
13
+ 'focusout',
14
+ ];
15
+ const textOf = (target) => String(target.value ?? target.textContent ?? '');
16
+ const keyOf = (event, hidden) =>
17
+ hidden && event.key.length === 1 ? '***' : event.key;
18
+ export function inputEvent(event, { handle, redact, isSensitive }, time) {
19
+ const id = handle?.idFor(event.target);
20
+ if (!id) {
21
+ return null;
22
+ }
23
+ const type = event.type;
24
+ let args;
25
+ if (type.startsWith('pointer')) {
26
+ const box = event.target.getBoundingClientRect();
27
+ args = [
28
+ 'pointer',
29
+ type.slice(7),
30
+ id,
31
+ ['at', String(event.clientX - box.left), String(event.clientY - box.top)],
32
+ ['button', String(event.button ?? 0)],
33
+ ['pointer', String(event.pointerId ?? 1)],
34
+ ];
35
+ } else if (type.startsWith('key')) {
36
+ const key = keyOf(event, redact && isSensitive(id));
37
+ args = ['key', type.slice(3), key, ['target', id]];
38
+ } else if (type === 'wheel') {
39
+ args = [
40
+ 'wheel',
41
+ id,
42
+ String(event.deltaX),
43
+ String(event.deltaY),
44
+ String(event.deltaMode ?? 0),
45
+ ];
46
+ } else if (type === 'input') {
47
+ const hidden = redact && (sensitiveTarget(event.target) || isSensitive(id));
48
+ args = ['text', id, hidden ? '***' : textOf(event.target)];
49
+ } else {
50
+ args = ['focus', type === 'focusin' ? 'in' : 'out', id];
51
+ }
52
+ return { time, kind: 'input', args };
53
+ }