@mizchi/vlmkit-animation-eval 0.23.0 → 0.23.2
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.
- package/README.md +9 -1
- package/dist/animation-eval.d.mts +71 -2
- package/dist/animation-eval.mjs +155 -19
- package/dist/index.d.mts +3 -2
- package/dist/index.mjs +3 -2
- package/dist/virtual-clock.d.mts +48 -0
- package/dist/virtual-clock.mjs +192 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -19,9 +19,17 @@ import { runAnimationEval, formatAnimationEvalReport } from "@mizchi/vlmkit-anim
|
|
|
19
19
|
|
|
20
20
|
const report = await runAnimationEval({ source: "page.html", samples: 4 });
|
|
21
21
|
console.log(formatAnimationEvalReport(report));
|
|
22
|
-
report.issues; // [{ kind: "no-visible-effect" | "infinite-animation" | "reduced-motion-ignored" | "long-settle" | "uncontrolled-motion", severity, message, selector? }]
|
|
22
|
+
report.issues; // [{ kind: "no-visible-effect" | "infinite-animation" | "reduced-motion-ignored" | "long-settle" | "uncontrolled-motion" | "seek-ineffective" | "clock-motion-unsettled", severity, message, selector? }]
|
|
23
23
|
```
|
|
24
24
|
|
|
25
|
+
`virtualTime: true` (`--virtual-time` on the gate) holds the page clock —
|
|
26
|
+
`requestAnimationFrame`, `performance.now`, `Date`, `setTimeout`,
|
|
27
|
+
`setInterval` — from document start and advances it from the evaluator, so
|
|
28
|
+
script-driven motion is sampled as `report.clockMotion` instead of being
|
|
29
|
+
reported as uncontrolled. A page that renders from an explicit time can listen
|
|
30
|
+
for `vlmkit:seek` (`detail.timeMs`, `detail.waitUntil(promise)`). The clock is
|
|
31
|
+
exported on its own as `VIRTUAL_CLOCK_SCRIPT` (`virtual-clock.ts`).
|
|
32
|
+
|
|
25
33
|
`playwright` is a required peer: the whole job is driving a browser. Depends
|
|
26
34
|
on `@mizchi/vlmkit-core` for page loading, browser launch and PNG utilities,
|
|
27
35
|
and on nothing else in the workspace.
|
|
@@ -73,13 +73,68 @@ interface EvaluatedAnimation extends AnimationTimingSample {
|
|
|
73
73
|
} | null;
|
|
74
74
|
totalChangedPixels: number;
|
|
75
75
|
maxFrameRatio: number;
|
|
76
|
+
/**
|
|
77
|
+
* Why the frames above cannot be trusted as a function of the seeked time, when they cannot.
|
|
78
|
+
* Absent when every seek took and replaying the first sample reproduced its pixels.
|
|
79
|
+
*/
|
|
80
|
+
seekIneffective?: SeekIneffective;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Evidence that seeking this animation did not control what was captured. Two independent
|
|
84
|
+
* kinds, because each misses what the other sees:
|
|
85
|
+
*
|
|
86
|
+
* - `readback`: after a seek the Animation was no longer live, had gone `idle`, or did not
|
|
87
|
+
* report the time it was set to — the page cancelled or replaced it, so the gate was moving
|
|
88
|
+
* an object nothing renders.
|
|
89
|
+
* - `replay`: seeking back to the first sample time and capturing again did not reproduce that
|
|
90
|
+
* frame inside the motion region — something other than this animation's time drives those
|
|
91
|
+
* pixels (a script restarting it, a ticker drawing over it).
|
|
92
|
+
*
|
|
93
|
+
* The case that made this a rule: a page restarting its animation every 100ms
|
|
94
|
+
* (`style.animation = "none"; reflow; style.animation = ""`) came back with six `visible`
|
|
95
|
+
* animations and "No animation issues detected" — every pixel the gate credited to its seeks
|
|
96
|
+
* was the page's own restart. HyperFrames' `sweep_static` guards the same thing from the other
|
|
97
|
+
* side: a sweep whose seeks did nothing makes every other green meaningless.
|
|
98
|
+
*/
|
|
99
|
+
interface SeekIneffective {
|
|
100
|
+
reason: "readback" | "replay";
|
|
101
|
+
/** Readback: what the Animation reported instead. Replay: pixels that differed inside the motion region. */
|
|
102
|
+
detail: string;
|
|
76
103
|
}
|
|
104
|
+
/**
|
|
105
|
+
* Motion driven by the page's own script — rAF loops, timers, a canvas — sampled by advancing
|
|
106
|
+
* the virtual clock (`virtual-clock.ts`) with every WAAPI animation held at rest.
|
|
107
|
+
*/
|
|
108
|
+
interface ClockMotion {
|
|
109
|
+
/** Virtual-time span sampled, from document start. */
|
|
110
|
+
windowMs: number;
|
|
111
|
+
/** The instant of each sample, in ms of virtual time. */
|
|
112
|
+
times: number[];
|
|
113
|
+
/** Delta from the previous sample (the first from the t=0 baseline). */
|
|
114
|
+
frames: FrameDeltaStat[];
|
|
115
|
+
motionBbox: {
|
|
116
|
+
x: number;
|
|
117
|
+
y: number;
|
|
118
|
+
width: number;
|
|
119
|
+
height: number;
|
|
120
|
+
} | null;
|
|
121
|
+
visible: boolean;
|
|
122
|
+
/**
|
|
123
|
+
* The last sampled instant whose interval moved pixels; `null` when the final interval still
|
|
124
|
+
* moved, i.e. the motion had not stopped by the end of the window.
|
|
125
|
+
*/
|
|
126
|
+
settledAtMs: number | null;
|
|
127
|
+
/** Exceptions thrown by page callbacks while the clock advanced (they do not stop it). */
|
|
128
|
+
errors: string[];
|
|
129
|
+
}
|
|
130
|
+
/** Pure: the settle instant of a clock sweep — null when its last interval still moved. */
|
|
131
|
+
declare function clockSettledAt(times: number[], frames: FrameDeltaStat[], minChangedPixels: number): number | null;
|
|
77
132
|
interface ReducedMotionRemaining {
|
|
78
133
|
selector: string;
|
|
79
134
|
name: string;
|
|
80
135
|
durationMs: number;
|
|
81
136
|
}
|
|
82
|
-
type AnimationEvalIssueKind = "no-visible-effect" | "infinite-animation" | "reduced-motion-ignored" | "long-settle" | "uncontrolled-motion";
|
|
137
|
+
type AnimationEvalIssueKind = "no-visible-effect" | "infinite-animation" | "reduced-motion-ignored" | "long-settle" | "uncontrolled-motion" | "seek-ineffective" | "clock-motion-unsettled";
|
|
83
138
|
interface AnimationEvalIssue {
|
|
84
139
|
kind: AnimationEvalIssueKind;
|
|
85
140
|
severity: "warn" | "suspect";
|
|
@@ -112,6 +167,10 @@ interface AnimationEvalReport {
|
|
|
112
167
|
* video, or GIF — is moving the page on its own.
|
|
113
168
|
*/
|
|
114
169
|
uncontrolledMotion?: FrameDeltaStat;
|
|
170
|
+
/** True when the page clock was held (`--virtual-time`); `uncontrolledMotion` then excludes script-driven motion. */
|
|
171
|
+
virtualTime?: boolean;
|
|
172
|
+
/** Script-driven motion sampled on the virtual clock. Present only with `--virtual-time`. */
|
|
173
|
+
clockMotion?: ClockMotion;
|
|
115
174
|
issues: AnimationEvalIssue[];
|
|
116
175
|
/** Written sample frames (when --frames was passed). */
|
|
117
176
|
framePaths?: string[];
|
|
@@ -151,6 +210,14 @@ interface AnimationEvalOptions extends PageLoadOptions {
|
|
|
151
210
|
reducedMotionDurationFloorMs?: number;
|
|
152
211
|
/** Skip the reduced-motion emulation pass. */
|
|
153
212
|
skipReducedMotion?: boolean;
|
|
213
|
+
/**
|
|
214
|
+
* Hold the page clock (rAF, `performance.now`, `Date`, timers) from document start and drive
|
|
215
|
+
* it from the evaluator, so script-driven motion is sampled instead of reported as
|
|
216
|
+
* uncontrolled. See `virtual-clock.ts`.
|
|
217
|
+
*/
|
|
218
|
+
virtualTime?: boolean;
|
|
219
|
+
/** Virtual-time span to sample script-driven motion over (default 2000ms). */
|
|
220
|
+
clockWindowMs?: number;
|
|
154
221
|
/** Write each sampled frame PNG into this directory. */
|
|
155
222
|
framesDir?: string;
|
|
156
223
|
/**
|
|
@@ -231,6 +298,8 @@ interface DeriveIssuesInput {
|
|
|
231
298
|
remaining: ReducedMotionRemaining[];
|
|
232
299
|
};
|
|
233
300
|
uncontrolledMotion?: FrameDeltaStat;
|
|
301
|
+
virtualTime?: boolean;
|
|
302
|
+
clockMotion?: ClockMotion;
|
|
234
303
|
}
|
|
235
304
|
declare function deriveAnimationIssues(input: DeriveIssuesInput, options?: {
|
|
236
305
|
settleThresholdMs?: number;
|
|
@@ -239,4 +308,4 @@ declare function deriveAnimationIssues(input: DeriveIssuesInput, options?: {
|
|
|
239
308
|
declare function runAnimationEval(options: AnimationEvalOptions): Promise<AnimationEvalReport>;
|
|
240
309
|
declare function formatAnimationEvalReport(report: AnimationEvalReport, rules?: RuleView): string;
|
|
241
310
|
//#endregion
|
|
242
|
-
export { AnimationEvalIssue, AnimationEvalIssueKind, AnimationEvalOptions, AnimationEvalReport, AnimationFrameStat, AnimationTimingSample, DeriveIssuesInput, EvaluatedAnimation, FrameDeltaStat, OscillationInfo, ReducedMotionRemaining, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox };
|
|
311
|
+
export { AnimationEvalIssue, AnimationEvalIssueKind, AnimationEvalOptions, AnimationEvalReport, AnimationFrameStat, AnimationTimingSample, ClockMotion, DeriveIssuesInput, EvaluatedAnimation, FrameDeltaStat, OscillationInfo, ReducedMotionRemaining, SeekIneffective, clockSettledAt, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox };
|
package/dist/animation-eval.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { VIRTUAL_CLOCK_SCRIPT } from "./virtual-clock.mjs";
|
|
2
3
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
4
|
import { STABLE_SELECTOR_JS } from "@mizchi/vlmkit-core/stable-selector.ts";
|
|
4
5
|
import { dirname, join, resolve } from "node:path";
|
|
@@ -12,7 +13,7 @@ import { composeFilmstrip, scalePngData } from "@mizchi/vlmkit-core/filmstrip.ts
|
|
|
12
13
|
import { encodeApng } from "@mizchi/vlmkit-core/apng.ts";
|
|
13
14
|
import { cropRegion, encodePng } from "@mizchi/vlmkit-core/png-utils.ts";
|
|
14
15
|
import { encodeWebp, imageFormatForPath } from "@mizchi/vlmkit-core/webp.ts";
|
|
15
|
-
import { sourceToUrl } from "@mizchi/vlmkit-core/page-open.ts";
|
|
16
|
+
import { applyHar, settlePage, sourceToUrl } from "@mizchi/vlmkit-core/page-open.ts";
|
|
16
17
|
//#region src/animation-eval.ts
|
|
17
18
|
/**
|
|
18
19
|
* Frame-sampled animation evaluator.
|
|
@@ -69,6 +70,15 @@ function computeOscillation(t) {
|
|
|
69
70
|
legMs: t.durationMs
|
|
70
71
|
};
|
|
71
72
|
}
|
|
73
|
+
/** Pure: the settle instant of a clock sweep — null when its last interval still moved. */
|
|
74
|
+
function clockSettledAt(times, frames, minChangedPixels) {
|
|
75
|
+
let settled = 0;
|
|
76
|
+
for (let i = 0; i < frames.length; i++) if (frames[i].changedPixels >= minChangedPixels) {
|
|
77
|
+
if (i === frames.length - 1) return null;
|
|
78
|
+
settled = times[i];
|
|
79
|
+
}
|
|
80
|
+
return settled;
|
|
81
|
+
}
|
|
72
82
|
/**
|
|
73
83
|
* Pixel delta between two same-size RGBA frames: count, ratio, and the
|
|
74
84
|
* bounding box of every pixel whose any channel moved more than tolerance.
|
|
@@ -134,18 +144,43 @@ function deriveAnimationIssues(input, options = {}) {
|
|
|
134
144
|
const settleThreshold = options.settleThresholdMs ?? 3e3;
|
|
135
145
|
const durationFloor = options.reducedMotionDurationFloorMs ?? 100;
|
|
136
146
|
const issues = [];
|
|
137
|
-
for (const anim of input.evaluated)
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
147
|
+
for (const anim of input.evaluated) {
|
|
148
|
+
if (anim.seekIneffective) {
|
|
149
|
+
const why = anim.seekIneffective.reason === "readback" ? `after a seek the animation ${anim.seekIneffective.detail} — the page cancelled or replaced it, so the gate was moving an object nothing renders` : `seeking back to its first sample did not reproduce that frame (${anim.seekIneffective.detail}) — something other than this animation's time drives those pixels`;
|
|
150
|
+
issues.push({
|
|
151
|
+
kind: "seek-ineffective",
|
|
152
|
+
severity: "suspect",
|
|
153
|
+
selector: anim.selector,
|
|
154
|
+
message: `${anim.selector} animation \`${anim.name}\`: ${why}. Its frame deltas are not measurements of the animation, so it is reported neither visible nor dead. Look for script that restarts or re-creates it (toggling \`animation\` / a class on a timer, a framework re-render), or a rAF / canvas ticker painting the same region.`
|
|
155
|
+
});
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (!anim.visible) issues.push({
|
|
159
|
+
kind: "no-visible-effect",
|
|
160
|
+
severity: "suspect",
|
|
161
|
+
selector: anim.selector,
|
|
162
|
+
message: `${anim.selector} animation \`${anim.name}\` (${anim.durationMs}ms) produced no visible pixel change at any sampled frame — dead animation or animated property has no rendered effect.`
|
|
163
|
+
});
|
|
164
|
+
}
|
|
143
165
|
for (const anim of input.infinite) issues.push({
|
|
144
166
|
kind: "infinite-animation",
|
|
145
167
|
severity: "warn",
|
|
146
168
|
selector: anim.selector,
|
|
147
169
|
message: `${anim.selector} animation \`${anim.name}\` runs forever — the page never settles. To fix the page, give it a bounded \`animation-iteration-count\` (or stop it once its work is done). If it is meant to run forever, the capture side has to absorb it instead: mask it with \`vlmkit snapshot <url> --mask "${anim.selector}"\` (that flag belongs to \`snapshot\` / \`diff html\`, not to this gate) or pause animations before screenshots.`
|
|
148
170
|
});
|
|
171
|
+
const clock = input.clockMotion;
|
|
172
|
+
if (clock?.visible && clock.settledAtMs === null) {
|
|
173
|
+
const b = clock.motionBbox;
|
|
174
|
+
issues.push({
|
|
175
|
+
kind: "clock-motion-unsettled",
|
|
176
|
+
severity: "warn",
|
|
177
|
+
message: `Script-driven motion at (${b.x},${b.y}) ${b.width}x${b.height} is still changing at ${clock.windowMs}ms of virtual time — a requestAnimationFrame / timer loop that never stops, so the page never settles. Stop the loop once its work is done, and check \`matchMedia("(prefers-reduced-motion: reduce)")\` in the script; if it is meant to run forever, mask the region in captures.`
|
|
178
|
+
});
|
|
179
|
+
} else if (clock?.visible && clock.settledAtMs !== null && clock.settledAtMs > settleThreshold) issues.push({
|
|
180
|
+
kind: "long-settle",
|
|
181
|
+
severity: "warn",
|
|
182
|
+
message: `Script-driven motion keeps going until ${Math.round(clock.settledAtMs)}ms of virtual time (threshold ${settleThreshold}ms) — captures inside this window are nondeterministic.`
|
|
183
|
+
});
|
|
149
184
|
if (input.settleMs !== null && input.settleMs > settleThreshold) issues.push({
|
|
150
185
|
kind: "long-settle",
|
|
151
186
|
severity: "warn",
|
|
@@ -157,7 +192,7 @@ function deriveAnimationIssues(input, options = {}) {
|
|
|
157
192
|
issues.push({
|
|
158
193
|
kind: "uncontrolled-motion",
|
|
159
194
|
severity: "warn",
|
|
160
|
-
message: `The page moved between two back-to-back captures with every WAAPI animation held still (${m.changedPixels}px${where}) — a rAF/JS-driven animation, video, or GIF the Web Animations API cannot enumerate or pause. Per-animation frame deltas overlapping this region may be contaminated (a dead animation can read as visible), the page never settles for VRT, and reduced-motion emulation does not affect it.
|
|
195
|
+
message: input.virtualTime ? `The page moved between two back-to-back captures with every WAAPI animation AND the page clock held (${m.changedPixels}px${where}) — video, an animated image, a worker, or something else no page clock drives. Per-animation frame deltas overlapping this region may be contaminated, and the page never settles for VRT. Mask the region for capture.` : `The page moved between two back-to-back captures with every WAAPI animation held still (${m.changedPixels}px${where}) — a rAF/JS-driven animation, video, or GIF the Web Animations API cannot enumerate or pause. Per-animation frame deltas overlapping this region may be contaminated (a dead animation can read as visible), the page never settles for VRT, and reduced-motion emulation does not affect it. Re-run with \`--virtual-time\` to hold rAF / timer-driven motion and measure it; mask what still moves.`
|
|
161
196
|
});
|
|
162
197
|
}
|
|
163
198
|
if (input.reducedMotion && input.reducedMotion.remainingCount > 0) {
|
|
@@ -166,7 +201,7 @@ function deriveAnimationIssues(input, options = {}) {
|
|
|
166
201
|
kind: "reduced-motion-ignored",
|
|
167
202
|
severity: "suspect",
|
|
168
203
|
...sample ? { selector: sample.selector } : {},
|
|
169
|
-
message: `${input.reducedMotion.remainingCount} animation(s) still run under \`prefers-reduced-motion: reduce\` emulation: ${input.reducedMotion.remaining.slice(0, 4).map((r) => `${r.selector} \`${r.name}\` ${Math.round(r.durationMs)}ms`).join(", ")}${input.reducedMotion.remaining.length > 4 ? `, and ${input.reducedMotion.remaining.length - 4} more` : ""} — motion is not reduced for users who requested it. Add \`@media (prefers-reduced-motion: reduce)\` and either set \`animation: none\` on them or shorten each duration below ${durationFloor}ms.`
|
|
204
|
+
message: `${input.reducedMotion.remainingCount} animation(s) still run under \`prefers-reduced-motion: reduce\` emulation: ${input.reducedMotion.remaining.slice(0, 4).map((r) => `${r.selector} \`${r.name}\` ${Math.round(r.durationMs)}ms`).join(", ")}${input.reducedMotion.remaining.length > 4 ? `, and ${input.reducedMotion.remaining.length - 4} more` : ""} — motion is not reduced for users who requested it. Add \`@media (prefers-reduced-motion: reduce)\` and either set \`animation: none\` on them or shorten each duration below ${durationFloor}ms.` + (input.reducedMotion.remaining.some((r) => r.selector.startsWith("(script-driven")) ? ` For the script-driven motion, read \`matchMedia("(prefers-reduced-motion: reduce)")\` and skip or shorten the loop.` : "")
|
|
170
205
|
});
|
|
171
206
|
}
|
|
172
207
|
return issues;
|
|
@@ -362,6 +397,37 @@ async function collectAnimations(page) {
|
|
|
362
397
|
}
|
|
363
398
|
return [...live, ...finished];
|
|
364
399
|
}
|
|
400
|
+
async function advanceClock(page, timeMs) {
|
|
401
|
+
await page.evaluate((t) => window.__vlmkitClock.advanceTo(t), timeMs);
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Advance the held clock across `windowMs` in `count` steps, capturing after each, starting
|
|
405
|
+
* from `baseline` (the page at virtual 0). Every WAAPI animation must already be held.
|
|
406
|
+
*/
|
|
407
|
+
async function sampleClock(page, baseline, shot, windowMs, count, tolerance, minChangedPixels, label) {
|
|
408
|
+
const times = Array.from({ length: count }, (_, i) => Math.round(windowMs * (i + 1) / count));
|
|
409
|
+
const frames = [];
|
|
410
|
+
let previous = baseline;
|
|
411
|
+
let motionBbox = null;
|
|
412
|
+
for (const t of times) {
|
|
413
|
+
await advanceClock(page, t);
|
|
414
|
+
const frame = await shot(`${label}-${t}ms`);
|
|
415
|
+
const delta = frameDelta(previous, frame, tolerance);
|
|
416
|
+
frames.push(delta);
|
|
417
|
+
if (delta.changedPixels >= minChangedPixels) motionBbox = unionBbox(motionBbox, delta.bbox);
|
|
418
|
+
previous = frame;
|
|
419
|
+
}
|
|
420
|
+
const errors = await page.evaluate(() => [...window.__vlmkitClock.errors]);
|
|
421
|
+
return {
|
|
422
|
+
windowMs,
|
|
423
|
+
times,
|
|
424
|
+
frames,
|
|
425
|
+
motionBbox,
|
|
426
|
+
visible: frames.some((f) => f.changedPixels >= minChangedPixels),
|
|
427
|
+
settledAtMs: clockSettledAt(times, frames, minChangedPixels),
|
|
428
|
+
errors: errors.slice(0, 5)
|
|
429
|
+
};
|
|
430
|
+
}
|
|
365
431
|
async function runAnimationEval(options) {
|
|
366
432
|
const viewport = options.viewport ?? {
|
|
367
433
|
width: 1280,
|
|
@@ -373,9 +439,15 @@ async function runAnimationEval(options) {
|
|
|
373
439
|
const minChangedPixels = options.minChangedPixels ?? 12;
|
|
374
440
|
const pageUrl = options.html !== void 0 ? void 0 : sourceToUrl(options.source);
|
|
375
441
|
const loadPage = async (p) => {
|
|
442
|
+
if (options.virtualTime) await p.addInitScript(VIRTUAL_CLOCK_SCRIPT);
|
|
376
443
|
await p.addInitScript(RECORD_ANIMATION_STARTS_SCRIPT);
|
|
377
444
|
if (options.html !== void 0) await p.setContent(options.html, navigationOptions(options));
|
|
378
|
-
else
|
|
445
|
+
else if (options.virtualTime) {
|
|
446
|
+
await applyHar(p, options.har);
|
|
447
|
+
await p.goto(pageUrl, navigationOptions(options));
|
|
448
|
+
await settlePage(p, 0, 0);
|
|
449
|
+
} else await navigatePage(p, pageUrl, options);
|
|
450
|
+
if (options.virtualTime) await advanceClock(p, 0);
|
|
379
451
|
};
|
|
380
452
|
return await withBrowser(async (browser) => {
|
|
381
453
|
const page = await browser.newPage({ viewport });
|
|
@@ -388,9 +460,15 @@ async function runAnimationEval(options) {
|
|
|
388
460
|
name: t.name
|
|
389
461
|
}));
|
|
390
462
|
const seek = async (index, timeMs) => {
|
|
391
|
-
await page.evaluate(([i, t]) => {
|
|
463
|
+
return await page.evaluate(([i, t]) => {
|
|
392
464
|
const anim = window.__vlmkitAnims?.[i];
|
|
393
|
-
if (anim)
|
|
465
|
+
if (!anim) return "was gone";
|
|
466
|
+
anim.currentTime = t;
|
|
467
|
+
if (anim.playState === "idle") return "had gone idle (cancelled)";
|
|
468
|
+
if (!document.getAnimations().includes(anim)) return "was no longer on the page";
|
|
469
|
+
const now = typeof anim.currentTime === "number" ? anim.currentTime : NaN;
|
|
470
|
+
if (!(Math.abs(now - t) <= 1)) return `reported currentTime ${Number.isNaN(now) ? "null" : Math.round(now)}ms instead of ${Math.round(t)}ms`;
|
|
471
|
+
return null;
|
|
394
472
|
}, [index, timeMs]);
|
|
395
473
|
};
|
|
396
474
|
const framePaths = [];
|
|
@@ -419,11 +497,18 @@ async function runAnimationEval(options) {
|
|
|
419
497
|
let motionBbox = null;
|
|
420
498
|
let totalChangedPixels = 0;
|
|
421
499
|
let maxFrameRatio = 0;
|
|
500
|
+
let readback = null;
|
|
501
|
+
let firstSample = null;
|
|
422
502
|
for (let s = 1; s <= samples; s++) {
|
|
423
503
|
const fraction = s / samples;
|
|
424
504
|
const timeMs = timing.delayMs + Math.min(timing.durationMs * fraction, timing.durationMs - 1);
|
|
425
|
-
|
|
505
|
+
const seekedTo = Math.max(timing.delayMs, timeMs);
|
|
506
|
+
readback ??= await seek(timing.index, seekedTo);
|
|
426
507
|
const frame = await shot(`anim-${timing.index}-${Math.round(fraction * 100)}`);
|
|
508
|
+
firstSample ??= {
|
|
509
|
+
timeMs: seekedTo,
|
|
510
|
+
frame
|
|
511
|
+
};
|
|
427
512
|
if (options.stripPath) rowFrames.push(frame);
|
|
428
513
|
const delta = frameDelta(previous, frame, tolerance);
|
|
429
514
|
frames.push({
|
|
@@ -435,6 +520,29 @@ async function runAnimationEval(options) {
|
|
|
435
520
|
maxFrameRatio = Math.max(maxFrameRatio, delta.ratio);
|
|
436
521
|
previous = frame;
|
|
437
522
|
}
|
|
523
|
+
let seekIneffective = readback ? {
|
|
524
|
+
reason: "readback",
|
|
525
|
+
detail: readback
|
|
526
|
+
} : void 0;
|
|
527
|
+
if (!seekIneffective && firstSample && motionBbox && samples > 1) {
|
|
528
|
+
const replayReadback = await seek(timing.index, firstSample.timeMs);
|
|
529
|
+
const again = await shot(`anim-${timing.index}-replay`);
|
|
530
|
+
const region = (f) => cropRegion(f, motionBbox.x, motionBbox.y, motionBbox.width, motionBbox.height);
|
|
531
|
+
const replay = frameDelta(region(firstSample.frame), region(again), tolerance);
|
|
532
|
+
if (replayReadback) seekIneffective = {
|
|
533
|
+
reason: "readback",
|
|
534
|
+
detail: replayReadback
|
|
535
|
+
};
|
|
536
|
+
else if (replay.changedPixels >= minChangedPixels) {
|
|
537
|
+
await seek(timing.index, firstSample.timeMs);
|
|
538
|
+
const third = await shot(`anim-${timing.index}-replay-2`);
|
|
539
|
+
const differs = (a, b) => frameDelta(region(a), region(b), tolerance).changedPixels >= minChangedPixels;
|
|
540
|
+
if (differs(firstSample.frame, third) && differs(again, third)) seekIneffective = {
|
|
541
|
+
reason: "replay",
|
|
542
|
+
detail: `${replay.changedPixels}px differed at ${Math.round(firstSample.timeMs)}ms, and again on a second replay`
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
}
|
|
438
546
|
await seek(timing.index, restTimeForAnimation(timing));
|
|
439
547
|
if (options.stripPath && rowFrames.length > 0) stripRows.push(rowFrames);
|
|
440
548
|
evaluated.push({
|
|
@@ -443,9 +551,13 @@ async function runAnimationEval(options) {
|
|
|
443
551
|
visible: frames.some((f) => f.changedPixels >= minChangedPixels),
|
|
444
552
|
motionBbox,
|
|
445
553
|
totalChangedPixels,
|
|
446
|
-
maxFrameRatio: Number(maxFrameRatio.toFixed(4))
|
|
554
|
+
maxFrameRatio: Number(maxFrameRatio.toFixed(4)),
|
|
555
|
+
...seekIneffective ? { seekIneffective } : {}
|
|
447
556
|
});
|
|
448
557
|
}
|
|
558
|
+
const clockWindowMs = options.clockWindowMs ?? 2e3;
|
|
559
|
+
const clockSamples = Math.max(8, samples * 2);
|
|
560
|
+
const clockMotion = options.virtualTime ? await sampleClock(page, baseline, shot, clockWindowMs, clockSamples, tolerance, minChangedPixels, "clock") : void 0;
|
|
449
561
|
let strip;
|
|
450
562
|
if (options.stripPath && evaluated.some((a) => a.motionBbox)) {
|
|
451
563
|
const wanted = options.stripSelector;
|
|
@@ -528,18 +640,32 @@ async function runAnimationEval(options) {
|
|
|
528
640
|
}
|
|
529
641
|
await page.close();
|
|
530
642
|
let reducedMotion;
|
|
531
|
-
if (!options.skipReducedMotion && timings.length > 0) {
|
|
643
|
+
if (!options.skipReducedMotion && (timings.length > 0 || clockMotion?.visible)) {
|
|
532
644
|
const durationFloor = options.reducedMotionDurationFloorMs ?? 100;
|
|
533
645
|
const rmPage = await browser.newPage({ viewport });
|
|
534
646
|
await rmPage.emulateMedia({ reducedMotion: "reduce" });
|
|
535
647
|
await loadPage(rmPage);
|
|
536
648
|
const rmTimings = await collectAnimations(rmPage);
|
|
649
|
+
let rmClock;
|
|
650
|
+
if (options.virtualTime) {
|
|
651
|
+
const rmShot = async () => pngFromBuffer(await rmPage.screenshot({ animations: "allow" }));
|
|
652
|
+
rmClock = await sampleClock(rmPage, await rmShot(), rmShot, clockWindowMs, clockSamples, tolerance, minChangedPixels, "rm-clock");
|
|
653
|
+
}
|
|
537
654
|
await rmPage.close();
|
|
538
655
|
const remaining = rmTimings.filter((t) => t.playState !== "paused" && t.playState !== "idle" && t.durationMs >= durationFloor).map((t) => ({
|
|
539
656
|
selector: t.selector,
|
|
540
657
|
name: t.name,
|
|
541
658
|
durationMs: t.durationMs
|
|
542
659
|
}));
|
|
660
|
+
if (rmClock?.visible && rmClock.motionBbox) {
|
|
661
|
+
const b = rmClock.motionBbox;
|
|
662
|
+
const lasted = rmClock.settledAtMs ?? rmClock.windowMs;
|
|
663
|
+
if (lasted >= durationFloor) remaining.push({
|
|
664
|
+
selector: `(script-driven motion at ${b.x},${b.y} ${b.width}x${b.height})`,
|
|
665
|
+
name: "requestAnimationFrame / timers",
|
|
666
|
+
durationMs: lasted
|
|
667
|
+
});
|
|
668
|
+
}
|
|
543
669
|
reducedMotion = {
|
|
544
670
|
remainingCount: remaining.length,
|
|
545
671
|
remaining
|
|
@@ -550,7 +676,9 @@ async function runAnimationEval(options) {
|
|
|
550
676
|
settleMs,
|
|
551
677
|
infinite,
|
|
552
678
|
...reducedMotion ? { reducedMotion } : {},
|
|
553
|
-
...uncontrolledMotion ? { uncontrolledMotion } : {}
|
|
679
|
+
...uncontrolledMotion ? { uncontrolledMotion } : {},
|
|
680
|
+
...options.virtualTime ? { virtualTime: true } : {},
|
|
681
|
+
...clockMotion ? { clockMotion } : {}
|
|
554
682
|
}, {
|
|
555
683
|
settleThresholdMs: options.settleThresholdMs,
|
|
556
684
|
reducedMotionDurationFloorMs: options.reducedMotionDurationFloorMs
|
|
@@ -564,6 +692,8 @@ async function runAnimationEval(options) {
|
|
|
564
692
|
infinite,
|
|
565
693
|
...reducedMotion ? { reducedMotion } : {},
|
|
566
694
|
...uncontrolledMotion ? { uncontrolledMotion } : {},
|
|
695
|
+
...options.virtualTime ? { virtualTime: true } : {},
|
|
696
|
+
...clockMotion ? { clockMotion } : {},
|
|
567
697
|
issues,
|
|
568
698
|
...framePaths.length > 0 ? { framePaths } : {},
|
|
569
699
|
...strip ? { strip } : {}
|
|
@@ -574,7 +704,7 @@ function formatAnimationEvalReport(report, rules) {
|
|
|
574
704
|
const lines = [];
|
|
575
705
|
const { shown, status, note } = tierIssues(report.issues, rules);
|
|
576
706
|
lines.push(`${BOLD}${CYAN}vlmkit check animation${RESET}`);
|
|
577
|
-
lines.push(`${DIM}source: ${report.source} (${report.viewport.width}x${report.viewport.height})${RESET}`);
|
|
707
|
+
lines.push(`${DIM}source: ${report.source} (${report.viewport.width}x${report.viewport.height})${report.virtualTime ? ", page clock held (--virtual-time)" : ""}${RESET}`);
|
|
578
708
|
lines.push("");
|
|
579
709
|
lines.push(`status: ${status}`);
|
|
580
710
|
lines.push(`animations: ${report.animationCount} (evaluated ${report.evaluated.length}, infinite ${report.infinite.length})`);
|
|
@@ -588,12 +718,18 @@ function formatAnimationEvalReport(report, rules) {
|
|
|
588
718
|
const where = m.bbox ? ` at (${m.bbox.x},${m.bbox.y}) ${m.bbox.width}x${m.bbox.height}` : "";
|
|
589
719
|
lines.push(`uncontrolled motion: ${m.changedPixels}px${where} (rAF / video / GIF — frame deltas may be contaminated)${ruleTag("uncontrolled-motion")}`);
|
|
590
720
|
}
|
|
721
|
+
if (report.clockMotion) {
|
|
722
|
+
const c = report.clockMotion;
|
|
723
|
+
const where = c.motionBbox ? ` at (${c.motionBbox.x},${c.motionBbox.y}) ${c.motionBbox.width}x${c.motionBbox.height}` : "";
|
|
724
|
+
lines.push(!c.visible ? `script-driven motion: none in ${c.windowMs}ms of virtual time` : c.settledAtMs === null ? `script-driven motion${where}: still moving at ${c.windowMs}ms of virtual time${ruleTag("clock-motion-unsettled")}` : `script-driven motion${where}: settles by ${c.settledAtMs}ms of virtual time${ruleTag("long-settle")}`);
|
|
725
|
+
if (c.errors.length > 0) lines.push(`${DIM} page callbacks threw while the clock advanced: ${c.errors.join(" | ")}${RESET}`);
|
|
726
|
+
}
|
|
591
727
|
if (report.evaluated.length > 0) {
|
|
592
728
|
lines.push("");
|
|
593
729
|
lines.push("Evaluated animations:");
|
|
594
730
|
for (const anim of report.evaluated) {
|
|
595
731
|
const bbox = anim.motionBbox ? `(${anim.motionBbox.x},${anim.motionBbox.y}) ${anim.motionBbox.width}x${anim.motionBbox.height}` : "none";
|
|
596
|
-
const visibility = anim.visible ? `${GREEN}visible${RESET}` : `${RED}no visible effect${RESET}`;
|
|
732
|
+
const visibility = anim.seekIneffective ? `${RED}not measured (seek ineffective)${RESET}` : anim.visible ? `${GREEN}visible${RESET}` : `${RED}no visible effect${RESET}`;
|
|
597
733
|
const osc = computeOscillation(anim);
|
|
598
734
|
const oscLabel = osc.oscillating ? ` (${anim.direction.startsWith("alternate") ? anim.direction : "palindromic keyframes"}, leg ${Math.round(osc.legMs)}ms)` : "";
|
|
599
735
|
lines.push(` - ${anim.selector} \`${anim.name}\` ${Math.round(anim.durationMs)}ms x${anim.iterations ?? "∞"}${oscLabel}: ${visibility}, motion region ${bbox}, peak frame delta ${(anim.maxFrameRatio * 100).toFixed(2)}%`);
|
|
@@ -635,4 +771,4 @@ function formatAnimationEvalReport(report, rules) {
|
|
|
635
771
|
* `--json`, `--advisory`, the run ledger and the exit code.
|
|
636
772
|
*/
|
|
637
773
|
//#endregion
|
|
638
|
-
export { computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox };
|
|
774
|
+
export { clockSettledAt, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import { AnimationEvalIssue, AnimationEvalIssueKind, AnimationEvalOptions, AnimationEvalReport, AnimationFrameStat, AnimationTimingSample, DeriveIssuesInput, EvaluatedAnimation, FrameDeltaStat, OscillationInfo, ReducedMotionRemaining, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox } from "./animation-eval.mjs";
|
|
2
|
-
|
|
1
|
+
import { AnimationEvalIssue, AnimationEvalIssueKind, AnimationEvalOptions, AnimationEvalReport, AnimationFrameStat, AnimationTimingSample, ClockMotion, DeriveIssuesInput, EvaluatedAnimation, FrameDeltaStat, OscillationInfo, ReducedMotionRemaining, SeekIneffective, clockSettledAt, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox } from "./animation-eval.mjs";
|
|
2
|
+
import { HOLD_TIMELINE_SCRIPT, VIRTUAL_CLOCK_SCRIPT } from "./virtual-clock.mjs";
|
|
3
|
+
export { type AnimationEvalIssue, type AnimationEvalIssueKind, type AnimationEvalOptions, type AnimationEvalReport, type AnimationFrameStat, type AnimationTimingSample, type ClockMotion, type DeriveIssuesInput, type EvaluatedAnimation, type FrameDeltaStat, HOLD_TIMELINE_SCRIPT, type OscillationInfo, type ReducedMotionRemaining, type SeekIneffective, VIRTUAL_CLOCK_SCRIPT, clockSettledAt, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox };
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { HOLD_TIMELINE_SCRIPT, VIRTUAL_CLOCK_SCRIPT } from "./virtual-clock.mjs";
|
|
2
|
+
import { clockSettledAt, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox } from "./animation-eval.mjs";
|
|
3
|
+
export { HOLD_TIMELINE_SCRIPT, VIRTUAL_CLOCK_SCRIPT, clockSettledAt, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
//#region src/virtual-clock.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* A page clock the evaluator owns: `requestAnimationFrame`, `performance.now`, `Date`,
|
|
4
|
+
* `setTimeout` and `setInterval` all read one virtual time, held at 0 from document start,
|
|
5
|
+
* which only `window.__vlmkitClock.advanceTo(ms)` moves.
|
|
6
|
+
*
|
|
7
|
+
* Why: the Web Animations API is the only motion `check animation` could pause and seek.
|
|
8
|
+
* Everything driven by script — a rAF loop, a GSAP ticker, a canvas, a `setInterval`
|
|
9
|
+
* carousel — kept moving while the gate sampled, so all the gate could say about it was
|
|
10
|
+
* `uncontrolled-motion: mask it or stub the ticker`. This IS the stub. With the clock held,
|
|
11
|
+
* script-driven motion is a function of virtual time like a WAAPI animation's `currentTime`,
|
|
12
|
+
* so it can be sampled, it stops contaminating the WAAPI frames, and whatever still moves
|
|
13
|
+
* under a held clock (video, GIF, a worker) is genuinely uncontrolled.
|
|
14
|
+
*
|
|
15
|
+
* The technique is HyperFrames' (heygen-com/hyperframes, `producer/src/services/fileServer.ts`):
|
|
16
|
+
* a frozen `Date` / `performance.now` and a rAF queue flushed once per seek. Two departures:
|
|
17
|
+
* timers are virtual too (HyperFrames leaves `setTimeout` native — a `setInterval` carousel
|
|
18
|
+
* is the commonest uncontrolled motion on ordinary pages, and a composition is not), and
|
|
19
|
+
* frames advance one 60 fps step at a time, because a loop that integrates its own `dt`
|
|
20
|
+
* lands somewhere else when handed one 500ms jump.
|
|
21
|
+
*
|
|
22
|
+
* What it cannot hold: CSS animations and transitions run on `document.timeline`, which is
|
|
23
|
+
* the WAAPI half the evaluator already pauses; `<video>` / animated images; workers; and
|
|
24
|
+
* `MessageChannel` / promise scheduling, which are not time-based and run natively.
|
|
25
|
+
*
|
|
26
|
+
* Pages that draw on demand can also listen for `vlmkit:seek` — dispatched after every
|
|
27
|
+
* advance with `detail.timeMs` and `detail.waitUntil(promise)` — the same contract as
|
|
28
|
+
* HyperFrames' `hf-seek`, for a canvas or WebGL scene that renders from an explicit time.
|
|
29
|
+
*/
|
|
30
|
+
declare const VIRTUAL_CLOCK_SCRIPT = "(() => {\n if (window.__vlmkitClock) return;\n const FRAME_MS = 1000 / 60;\n const nativePerfNow = performance.now.bind(performance);\n const NativeDate = Date;\n // Virtual 0 is document start; Date keeps the real wall-clock date at that instant.\n const epochAtZero = NativeDate.now() - nativePerfNow();\n let now = 0;\n let lastFrame = 0;\n let seq = 0;\n let rafQueue = [];\n const timers = new Map();\n\n Object.defineProperty(performance, \"now\", { value: () => now, configurable: true, writable: true });\n\n function VirtualDate(...args) {\n if (!new.target) return new NativeDate(epochAtZero + now).toString();\n return args.length === 0 ? new NativeDate(epochAtZero + now) : new NativeDate(...args);\n }\n VirtualDate.prototype = NativeDate.prototype;\n VirtualDate.now = () => Math.floor(epochAtZero + now);\n VirtualDate.parse = NativeDate.parse;\n VirtualDate.UTC = NativeDate.UTC;\n window.Date = VirtualDate;\n\n window.requestAnimationFrame = (callback) => {\n const id = ++seq;\n rafQueue.push({ id, callback });\n return id;\n };\n window.cancelAnimationFrame = (id) => {\n rafQueue = rafQueue.filter((entry) => entry.id !== id);\n };\n\n const schedule = (callback, delay, args, interval) => {\n const id = ++seq;\n const ms = Math.max(0, Number(delay) || 0);\n timers.set(id, { due: now + ms, callback, args, interval: interval ? Math.max(1, ms) : 0 });\n return id;\n };\n window.setTimeout = (callback, delay, ...args) => schedule(callback, delay, args, false);\n window.setInterval = (callback, delay, ...args) => schedule(callback, delay, args, true);\n window.clearTimeout = (id) => { timers.delete(id); };\n window.clearInterval = (id) => { timers.delete(id); };\n\n // A throwing callback must not stop the clock for everything else on the page.\n const errors = [];\n const invoke = (callback, args) => {\n try {\n if (typeof callback === \"function\") callback(...args);\n else if (typeof callback === \"string\") (0, eval)(callback);\n } catch (error) {\n errors.push(String((error && error.message) || error));\n }\n };\n\n const nextTimer = () => {\n let best = null;\n for (const [id, timer] of timers) if (best === null || timer.due < best[1].due) best = [id, timer];\n return best;\n };\n\n // Microtasks between steps, so a promise chain started by one callback settles before the\n // next callback runs \u2014 the order it would have had on a real clock.\n const drain = () => Promise.resolve().then(() => undefined);\n\n async function advanceTo(target) {\n let guard = 0;\n while (guard++ < 100000) {\n const timer = nextTimer();\n const frameAt = lastFrame + FRAME_MS;\n const timerAt = timer ? timer[1].due : Infinity;\n const at = Math.min(frameAt, timerAt);\n if (at > target) break;\n now = Math.max(now, at);\n if (timer && timerAt <= frameAt) {\n const [id, entry] = timer;\n if (entry.interval) entry.due += entry.interval;\n else timers.delete(id);\n invoke(entry.callback, entry.args || []);\n } else {\n lastFrame = frameAt;\n const queue = rafQueue;\n rafQueue = [];\n for (const entry of queue) invoke(entry.callback, [now]);\n }\n await drain();\n }\n now = Math.max(now, target);\n const waits = [];\n window.dispatchEvent(new CustomEvent(\"vlmkit:seek\", {\n detail: { timeMs: now, waitUntil: (promise) => { waits.push(promise); } },\n }));\n await Promise.all(waits.map((p) => Promise.resolve(p).catch(() => undefined)));\n await drain();\n return now;\n }\n\n window.__vlmkitClock = {\n now: () => now,\n advanceTo,\n errors,\n pending: () => ({ timers: timers.size, frames: rafQueue.length }),\n };\n})()";
|
|
31
|
+
/**
|
|
32
|
+
* Every animation held from the instant it begins, with that instant recorded, so the whole
|
|
33
|
+
* page can be put at one moment of its timeline: `window.__vlmkitSeekTimeline(t)` seeks every
|
|
34
|
+
* held animation to `t - startAt`, and `__vlmkitTimelineAnimations()` lists what is held for
|
|
35
|
+
* picking instants. Used by `check integrity --timeline` together with `VIRTUAL_CLOCK_SCRIPT`,
|
|
36
|
+
* which holds the script half of the same moment.
|
|
37
|
+
*
|
|
38
|
+
* `startAt` is read off the virtual clock when one is installed (the page time a script that
|
|
39
|
+
* started the animation saw), else `performance.now()`. CSS animations and transitions run on
|
|
40
|
+
* `document.timeline`, which is real time: one that starts at load is caught at `transitionrun`
|
|
41
|
+
* / `animationstart` with the page clock still at 0, and its own `currentTime` already counts
|
|
42
|
+
* its delay, so `t - 0` is right. One a script starts later is caught when the browser next
|
|
43
|
+
* renders, which can be after the virtual clock has moved on — its `startAt` is then late by up
|
|
44
|
+
* to the advance that started it. That bound is the honest limit of seeking CSS by page time.
|
|
45
|
+
*/
|
|
46
|
+
declare const HOLD_TIMELINE_SCRIPT = "(() => {\n if (window.__vlmkitTimeline) return;\n const held = [];\n window.__vlmkitTimeline = held;\n const clockNow = () => (window.__vlmkitClock ? window.__vlmkitClock.now() : performance.now());\n const hold = (anim) => {\n if (!anim || held.some((h) => h.anim === anim)) return;\n held.push({ anim, startAt: clockNow() });\n try { anim.pause(); } catch {}\n };\n const onStart = (event) => {\n const target = event.target;\n if (!target || !target.getAnimations) return;\n for (const anim of target.getAnimations()) hold(anim);\n };\n document.addEventListener(\"animationstart\", onStart, true);\n document.addEventListener(\"transitionrun\", onStart, true);\n const nativeAnimate = Element.prototype.animate;\n Element.prototype.animate = function (...args) {\n const anim = nativeAnimate.apply(this, args);\n hold(anim);\n return anim;\n };\n window.__vlmkitSeekTimeline = (t) => {\n // Late arrivals first: anything running that the events missed (an animation already in\n // its active phase when the listeners attached) is held at the instant it is found.\n if (document.getAnimations) for (const anim of document.getAnimations()) hold(anim);\n for (const h of held) {\n try { h.anim.currentTime = Math.max(0, t - h.startAt); } catch {}\n }\n };\n window.__vlmkitTimelineAnimations = () => held.map((h) => {\n let timing = {};\n try { timing = h.anim.effect && h.anim.effect.getComputedTiming ? h.anim.effect.getComputedTiming() : {}; } catch {}\n return {\n startMs: h.startAt + (timing.delay || 0),\n durationMs: typeof timing.duration === \"number\" ? timing.duration : 0,\n iterations: Number.isFinite(timing.iterations) ? timing.iterations : null,\n };\n });\n})()";
|
|
47
|
+
//#endregion
|
|
48
|
+
export { HOLD_TIMELINE_SCRIPT, VIRTUAL_CLOCK_SCRIPT };
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
//#region src/virtual-clock.ts
|
|
2
|
+
/**
|
|
3
|
+
* A page clock the evaluator owns: `requestAnimationFrame`, `performance.now`, `Date`,
|
|
4
|
+
* `setTimeout` and `setInterval` all read one virtual time, held at 0 from document start,
|
|
5
|
+
* which only `window.__vlmkitClock.advanceTo(ms)` moves.
|
|
6
|
+
*
|
|
7
|
+
* Why: the Web Animations API is the only motion `check animation` could pause and seek.
|
|
8
|
+
* Everything driven by script — a rAF loop, a GSAP ticker, a canvas, a `setInterval`
|
|
9
|
+
* carousel — kept moving while the gate sampled, so all the gate could say about it was
|
|
10
|
+
* `uncontrolled-motion: mask it or stub the ticker`. This IS the stub. With the clock held,
|
|
11
|
+
* script-driven motion is a function of virtual time like a WAAPI animation's `currentTime`,
|
|
12
|
+
* so it can be sampled, it stops contaminating the WAAPI frames, and whatever still moves
|
|
13
|
+
* under a held clock (video, GIF, a worker) is genuinely uncontrolled.
|
|
14
|
+
*
|
|
15
|
+
* The technique is HyperFrames' (heygen-com/hyperframes, `producer/src/services/fileServer.ts`):
|
|
16
|
+
* a frozen `Date` / `performance.now` and a rAF queue flushed once per seek. Two departures:
|
|
17
|
+
* timers are virtual too (HyperFrames leaves `setTimeout` native — a `setInterval` carousel
|
|
18
|
+
* is the commonest uncontrolled motion on ordinary pages, and a composition is not), and
|
|
19
|
+
* frames advance one 60 fps step at a time, because a loop that integrates its own `dt`
|
|
20
|
+
* lands somewhere else when handed one 500ms jump.
|
|
21
|
+
*
|
|
22
|
+
* What it cannot hold: CSS animations and transitions run on `document.timeline`, which is
|
|
23
|
+
* the WAAPI half the evaluator already pauses; `<video>` / animated images; workers; and
|
|
24
|
+
* `MessageChannel` / promise scheduling, which are not time-based and run natively.
|
|
25
|
+
*
|
|
26
|
+
* Pages that draw on demand can also listen for `vlmkit:seek` — dispatched after every
|
|
27
|
+
* advance with `detail.timeMs` and `detail.waitUntil(promise)` — the same contract as
|
|
28
|
+
* HyperFrames' `hf-seek`, for a canvas or WebGL scene that renders from an explicit time.
|
|
29
|
+
*/
|
|
30
|
+
const VIRTUAL_CLOCK_SCRIPT = `(() => {
|
|
31
|
+
if (window.__vlmkitClock) return;
|
|
32
|
+
const FRAME_MS = 1000 / 60;
|
|
33
|
+
const nativePerfNow = performance.now.bind(performance);
|
|
34
|
+
const NativeDate = Date;
|
|
35
|
+
// Virtual 0 is document start; Date keeps the real wall-clock date at that instant.
|
|
36
|
+
const epochAtZero = NativeDate.now() - nativePerfNow();
|
|
37
|
+
let now = 0;
|
|
38
|
+
let lastFrame = 0;
|
|
39
|
+
let seq = 0;
|
|
40
|
+
let rafQueue = [];
|
|
41
|
+
const timers = new Map();
|
|
42
|
+
|
|
43
|
+
Object.defineProperty(performance, "now", { value: () => now, configurable: true, writable: true });
|
|
44
|
+
|
|
45
|
+
function VirtualDate(...args) {
|
|
46
|
+
if (!new.target) return new NativeDate(epochAtZero + now).toString();
|
|
47
|
+
return args.length === 0 ? new NativeDate(epochAtZero + now) : new NativeDate(...args);
|
|
48
|
+
}
|
|
49
|
+
VirtualDate.prototype = NativeDate.prototype;
|
|
50
|
+
VirtualDate.now = () => Math.floor(epochAtZero + now);
|
|
51
|
+
VirtualDate.parse = NativeDate.parse;
|
|
52
|
+
VirtualDate.UTC = NativeDate.UTC;
|
|
53
|
+
window.Date = VirtualDate;
|
|
54
|
+
|
|
55
|
+
window.requestAnimationFrame = (callback) => {
|
|
56
|
+
const id = ++seq;
|
|
57
|
+
rafQueue.push({ id, callback });
|
|
58
|
+
return id;
|
|
59
|
+
};
|
|
60
|
+
window.cancelAnimationFrame = (id) => {
|
|
61
|
+
rafQueue = rafQueue.filter((entry) => entry.id !== id);
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const schedule = (callback, delay, args, interval) => {
|
|
65
|
+
const id = ++seq;
|
|
66
|
+
const ms = Math.max(0, Number(delay) || 0);
|
|
67
|
+
timers.set(id, { due: now + ms, callback, args, interval: interval ? Math.max(1, ms) : 0 });
|
|
68
|
+
return id;
|
|
69
|
+
};
|
|
70
|
+
window.setTimeout = (callback, delay, ...args) => schedule(callback, delay, args, false);
|
|
71
|
+
window.setInterval = (callback, delay, ...args) => schedule(callback, delay, args, true);
|
|
72
|
+
window.clearTimeout = (id) => { timers.delete(id); };
|
|
73
|
+
window.clearInterval = (id) => { timers.delete(id); };
|
|
74
|
+
|
|
75
|
+
// A throwing callback must not stop the clock for everything else on the page.
|
|
76
|
+
const errors = [];
|
|
77
|
+
const invoke = (callback, args) => {
|
|
78
|
+
try {
|
|
79
|
+
if (typeof callback === "function") callback(...args);
|
|
80
|
+
else if (typeof callback === "string") (0, eval)(callback);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
errors.push(String((error && error.message) || error));
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const nextTimer = () => {
|
|
87
|
+
let best = null;
|
|
88
|
+
for (const [id, timer] of timers) if (best === null || timer.due < best[1].due) best = [id, timer];
|
|
89
|
+
return best;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// Microtasks between steps, so a promise chain started by one callback settles before the
|
|
93
|
+
// next callback runs — the order it would have had on a real clock.
|
|
94
|
+
const drain = () => Promise.resolve().then(() => undefined);
|
|
95
|
+
|
|
96
|
+
async function advanceTo(target) {
|
|
97
|
+
let guard = 0;
|
|
98
|
+
while (guard++ < 100000) {
|
|
99
|
+
const timer = nextTimer();
|
|
100
|
+
const frameAt = lastFrame + FRAME_MS;
|
|
101
|
+
const timerAt = timer ? timer[1].due : Infinity;
|
|
102
|
+
const at = Math.min(frameAt, timerAt);
|
|
103
|
+
if (at > target) break;
|
|
104
|
+
now = Math.max(now, at);
|
|
105
|
+
if (timer && timerAt <= frameAt) {
|
|
106
|
+
const [id, entry] = timer;
|
|
107
|
+
if (entry.interval) entry.due += entry.interval;
|
|
108
|
+
else timers.delete(id);
|
|
109
|
+
invoke(entry.callback, entry.args || []);
|
|
110
|
+
} else {
|
|
111
|
+
lastFrame = frameAt;
|
|
112
|
+
const queue = rafQueue;
|
|
113
|
+
rafQueue = [];
|
|
114
|
+
for (const entry of queue) invoke(entry.callback, [now]);
|
|
115
|
+
}
|
|
116
|
+
await drain();
|
|
117
|
+
}
|
|
118
|
+
now = Math.max(now, target);
|
|
119
|
+
const waits = [];
|
|
120
|
+
window.dispatchEvent(new CustomEvent("vlmkit:seek", {
|
|
121
|
+
detail: { timeMs: now, waitUntil: (promise) => { waits.push(promise); } },
|
|
122
|
+
}));
|
|
123
|
+
await Promise.all(waits.map((p) => Promise.resolve(p).catch(() => undefined)));
|
|
124
|
+
await drain();
|
|
125
|
+
return now;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
window.__vlmkitClock = {
|
|
129
|
+
now: () => now,
|
|
130
|
+
advanceTo,
|
|
131
|
+
errors,
|
|
132
|
+
pending: () => ({ timers: timers.size, frames: rafQueue.length }),
|
|
133
|
+
};
|
|
134
|
+
})()`;
|
|
135
|
+
/**
|
|
136
|
+
* Every animation held from the instant it begins, with that instant recorded, so the whole
|
|
137
|
+
* page can be put at one moment of its timeline: `window.__vlmkitSeekTimeline(t)` seeks every
|
|
138
|
+
* held animation to `t - startAt`, and `__vlmkitTimelineAnimations()` lists what is held for
|
|
139
|
+
* picking instants. Used by `check integrity --timeline` together with `VIRTUAL_CLOCK_SCRIPT`,
|
|
140
|
+
* which holds the script half of the same moment.
|
|
141
|
+
*
|
|
142
|
+
* `startAt` is read off the virtual clock when one is installed (the page time a script that
|
|
143
|
+
* started the animation saw), else `performance.now()`. CSS animations and transitions run on
|
|
144
|
+
* `document.timeline`, which is real time: one that starts at load is caught at `transitionrun`
|
|
145
|
+
* / `animationstart` with the page clock still at 0, and its own `currentTime` already counts
|
|
146
|
+
* its delay, so `t - 0` is right. One a script starts later is caught when the browser next
|
|
147
|
+
* renders, which can be after the virtual clock has moved on — its `startAt` is then late by up
|
|
148
|
+
* to the advance that started it. That bound is the honest limit of seeking CSS by page time.
|
|
149
|
+
*/
|
|
150
|
+
const HOLD_TIMELINE_SCRIPT = `(() => {
|
|
151
|
+
if (window.__vlmkitTimeline) return;
|
|
152
|
+
const held = [];
|
|
153
|
+
window.__vlmkitTimeline = held;
|
|
154
|
+
const clockNow = () => (window.__vlmkitClock ? window.__vlmkitClock.now() : performance.now());
|
|
155
|
+
const hold = (anim) => {
|
|
156
|
+
if (!anim || held.some((h) => h.anim === anim)) return;
|
|
157
|
+
held.push({ anim, startAt: clockNow() });
|
|
158
|
+
try { anim.pause(); } catch {}
|
|
159
|
+
};
|
|
160
|
+
const onStart = (event) => {
|
|
161
|
+
const target = event.target;
|
|
162
|
+
if (!target || !target.getAnimations) return;
|
|
163
|
+
for (const anim of target.getAnimations()) hold(anim);
|
|
164
|
+
};
|
|
165
|
+
document.addEventListener("animationstart", onStart, true);
|
|
166
|
+
document.addEventListener("transitionrun", onStart, true);
|
|
167
|
+
const nativeAnimate = Element.prototype.animate;
|
|
168
|
+
Element.prototype.animate = function (...args) {
|
|
169
|
+
const anim = nativeAnimate.apply(this, args);
|
|
170
|
+
hold(anim);
|
|
171
|
+
return anim;
|
|
172
|
+
};
|
|
173
|
+
window.__vlmkitSeekTimeline = (t) => {
|
|
174
|
+
// Late arrivals first: anything running that the events missed (an animation already in
|
|
175
|
+
// its active phase when the listeners attached) is held at the instant it is found.
|
|
176
|
+
if (document.getAnimations) for (const anim of document.getAnimations()) hold(anim);
|
|
177
|
+
for (const h of held) {
|
|
178
|
+
try { h.anim.currentTime = Math.max(0, t - h.startAt); } catch {}
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
window.__vlmkitTimelineAnimations = () => held.map((h) => {
|
|
182
|
+
let timing = {};
|
|
183
|
+
try { timing = h.anim.effect && h.anim.effect.getComputedTiming ? h.anim.effect.getComputedTiming() : {}; } catch {}
|
|
184
|
+
return {
|
|
185
|
+
startMs: h.startAt + (timing.delay || 0),
|
|
186
|
+
durationMs: typeof timing.duration === "number" ? timing.duration : 0,
|
|
187
|
+
iterations: Number.isFinite(timing.iterations) ? timing.iterations : null,
|
|
188
|
+
};
|
|
189
|
+
});
|
|
190
|
+
})()`;
|
|
191
|
+
//#endregion
|
|
192
|
+
export { HOLD_TIMELINE_SCRIPT, VIRTUAL_CLOCK_SCRIPT };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mizchi/vlmkit-animation-eval",
|
|
3
|
-
"version": "0.23.
|
|
3
|
+
"version": "0.23.2",
|
|
4
4
|
"description": "Frame-sampled animation evaluation for web pages: pause every Web Animation, seek deterministic sample points, and report visible effect, settle time, reduced-motion behaviour and uncontrolled motion. The measurement behind `vlmkit check animation` and `vlmkit-anim eval`.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "mizchi",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"pngjs": "^7.0.0",
|
|
40
|
-
"@mizchi/vlmkit-core": "0.23.
|
|
40
|
+
"@mizchi/vlmkit-core": "0.23.2"
|
|
41
41
|
},
|
|
42
42
|
"peerDependencies": {
|
|
43
43
|
"playwright": ">=1.61 <2"
|