@mizchi/vlmkit-animation-eval 0.24.0 → 0.28.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.
@@ -1,6 +1,5 @@
1
1
  import { PageLoadOptions } from "@mizchi/vlmkit-core/page-load.ts";
2
2
  import { RuleView } from "@mizchi/vlmkit-core/plugin/contract.ts";
3
- //#region src/animation-eval.d.ts
4
3
  export interface AnimationTimingSample {
5
4
  /** Index into the page's animation list at capture time. */
6
5
  index: number;
@@ -149,7 +148,9 @@ export interface ClockMotion {
149
148
  selector: string;
150
149
  name: string;
151
150
  kind: "transition" | "animation";
151
+ /** The sweep instant it was first seen at; `afterMs` is the instant before it, when it was not. */
152
152
  atMs: number;
153
+ afterMs?: number;
153
154
  durationMs?: number;
154
155
  }>;
155
156
  /**
@@ -184,7 +185,7 @@ export interface ReducedMotionRemaining {
184
185
  name: string;
185
186
  durationMs: number;
186
187
  }
187
- export type AnimationEvalIssueKind = "no-visible-effect" | "infinite-animation" | "reduced-motion-ignored" | "long-settle" | "uncontrolled-motion" | "seek-ineffective" | "clock-motion-unsettled" | "undefined-keyframes" | "motion-mostly-hidden" | "delayed-entrance" | "unknown-transition-property" | "reduced-motion-hides" | "layout-animation" | "loop-seam" | "stroke-incomplete" | "discrete-transition" | "animation-replayed" | "zero-duration-animation";
188
+ export type AnimationEvalIssueKind = "no-visible-effect" | "infinite-animation" | "reduced-motion-ignored" | "long-settle" | "uncontrolled-motion" | "seek-ineffective" | "clock-motion-unsettled" | "undefined-keyframes" | "motion-mostly-hidden" | "delayed-entrance" | "unknown-transition-property" | "unregistered-property-transition" | "inert-offset-animation" | "duplicate-keyframes" | "negative-delay-entrance" | "held-filter" | "held-paused-animation" | "stepped-keyframe" | "inert-size-animation" | "unknown-media-feature" | "overridden-animation" | "unitless-duration-var" | "counter-rotation-drift" | "reduced-motion-hides" | "layout-animation" | "loop-seam" | "stroke-incomplete" | "discrete-transition" | "animation-replayed" | "zero-duration-animation";
188
189
  export interface AnimationEvalIssue {
189
190
  kind: AnimationEvalIssueKind;
190
191
  severity: "warn" | "suspect";
@@ -216,6 +217,13 @@ export interface AnimationEvalReport {
216
217
  reducedMotion?: {
217
218
  remainingCount: number;
218
219
  remaining: ReducedMotionRemaining[];
220
+ /**
221
+ * Nothing that moves runs without the preference either (only opacity, colour, visibility):
222
+ * there was no motion to reduce, so the pass is not "honored" by any choice of the page's.
223
+ */
224
+ nothingToReduce?: boolean;
225
+ /** With `nothingToReduce`: the fades / colour animations that still run under reduce, as allowed. */
226
+ fadesUnderReduce?: number;
219
227
  };
220
228
  /** `animation-name`s with no @keyframes: nothing ran under them (`reducedMotion`: only under reduce). */
221
229
  undefinedKeyframes?: {
@@ -395,10 +403,7 @@ export interface DeriveIssuesInput {
395
403
  name: string;
396
404
  indicator?: string;
397
405
  }[];
398
- reducedMotion?: {
399
- remainingCount: number;
400
- remaining: ReducedMotionRemaining[];
401
- };
406
+ reducedMotion?: AnimationEvalReport["reducedMotion"];
402
407
  uncontrolledMotion?: FrameDeltaStat;
403
408
  virtualTime?: boolean;
404
409
  clockMotion?: ClockMotion;
@@ -411,6 +416,58 @@ export interface DeriveIssuesInput {
411
416
  unknownTransitions?: {
412
417
  selector: string;
413
418
  name: string;
419
+ unregistered?: boolean;
420
+ inertOffsets?: string[];
421
+ duplicate?: string[];
422
+ negativeDelayMs?: number;
423
+ durationMs?: number;
424
+ restFilter?: string;
425
+ /** The rule that holds it paused while it hides the element (animation-play-state: paused). */
426
+ heldPaused?: string;
427
+ /** A later animation in animation-name on the same property, whose fill covers this one's run. */
428
+ overridden?: {
429
+ by: string;
430
+ props: string[];
431
+ delayMs: number;
432
+ fill: string;
433
+ coveredMs: number | null;
434
+ };
435
+ /** A counter-rotation against an ancestor's turn at a rate that does not cancel it. */
436
+ counterDrift?: {
437
+ ancestor: string;
438
+ theirs: string;
439
+ mine: {
440
+ deg: number;
441
+ ms: number;
442
+ };
443
+ other: {
444
+ deg: number;
445
+ ms: number;
446
+ };
447
+ net: number;
448
+ };
449
+ /** A transition / animation duration var() that resolves to a number with no unit. */
450
+ unitlessVar?: {
451
+ prop: string;
452
+ text: string;
453
+ variable: string;
454
+ value: string;
455
+ };
456
+ /** A keyframe's steps() timing function that overrides the element's smooth one. */
457
+ steppedKeyframe?: {
458
+ at: string;
459
+ easing: string;
460
+ own: string;
461
+ };
462
+ /** Size properties its keyframes animate on a non-replaced inline box, where they do nothing. */
463
+ inertSize?: string[];
464
+ tag?: string;
465
+ /** An @media header the browser reads as "not all" (an unknown feature) around motion. */
466
+ unknownMedia?: {
467
+ header: string;
468
+ feature: string;
469
+ suggest: string | null;
470
+ };
414
471
  }[];
415
472
  /** CSS animations with no duration: they end as they begin. */
416
473
  zeroDuration?: {
@@ -476,4 +533,4 @@ export declare function deriveAnimationIssues(input: DeriveIssuesInput, options?
476
533
  }): AnimationEvalIssue[];
477
534
  export declare function runAnimationEval(options: AnimationEvalOptions): Promise<AnimationEvalReport>;
478
535
  export declare function formatAnimationEvalReport(report: AnimationEvalReport, rules?: RuleView): string;
479
- //#endregion
536
+ export {};
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { VIRTUAL_CLOCK_SCRIPT } from "./virtual-clock.mjs";
3
2
  import { captureTimelineFrames } from "./frames-capture.mjs";
3
+ import { VIRTUAL_CLOCK_SCRIPT } from "./virtual-clock.mjs";
4
4
  import { mkdir, writeFile } from "node:fs/promises";
5
5
  import { STABLE_SELECTOR_JS } from "@mizchi/vlmkit-core/stable-selector.ts";
6
6
  import { dirname, resolve } from "node:path";
@@ -16,7 +16,7 @@ import { cropRegion, encodePng } from "@mizchi/vlmkit-core/png-utils.ts";
16
16
  import { encodeWebp, imageFormatForPath } from "@mizchi/vlmkit-core/webp.ts";
17
17
  import { applyHar, settlePage, sourceToUrl } from "@mizchi/vlmkit-core/page-open.ts";
18
18
  import { formatInstant, playbackDelays } from "@mizchi/vlmkit-judge/frames.ts";
19
- //#region src/animation-eval.ts
19
+ // src/animation-eval.ts
20
20
  /**
21
21
  * Frame-sampled animation evaluator.
22
22
  *
@@ -78,11 +78,17 @@ function clockUpdatesOnly(clock) {
78
78
  if ((clock.started ?? []).length > 0 || (clock.replays ?? []).length > 0) return false;
79
79
  return r.timers > 0 && r.timers <= 5 * Math.max(1, clock.windowMs / 1e3);
80
80
  }
81
+ /**
82
+ * When a timer-started animation began, as far as the sweep's instants can say: "at 250ms" read
83
+ * as the start of a transition a timer began at 200ms (round 13), when 250 was only the first
84
+ * instant after it.
85
+ */
86
+ const beganText = (s) => s.afterMs !== void 0 && s.atMs - s.afterMs > 1e3 / 60 + 1e-6 ? `between ${s.afterMs}ms and ${s.atMs}ms` : `at ${s.atMs}ms`;
81
87
  /** Pure: what a clock sweep's motion is, named as far as the page let it be. */
82
88
  function clockMotionSource(clock) {
83
89
  const started = clock.started ?? [];
84
90
  if (started.length === 0) return "requestAnimationFrame / timers";
85
- return `a timer started ${started.slice(0, 3).map((s) => `${s.kind} \`${s.name}\` on ${s.selector} (begun at ${s.atMs}ms)`).join(", ")}${started.length > 3 ? ` and ${started.length - 3} more` : ""}`;
91
+ return `a timer started ${started.slice(0, 3).map((s) => `${s.kind} \`${s.name}\` on ${s.selector} (begun ${beganText(s)})`).join(", ")}${started.length > 3 ? ` and ${started.length - 3} more` : ""}`;
86
92
  }
87
93
  /** Pure: the settle instant of a clock sweep — null when its last interval still moved. */
88
94
  function clockSettledAt(times, frames, minChangedPixels) {
@@ -206,12 +212,127 @@ function deriveAnimationIssues(input, options = {}) {
206
212
  selector: u.selector,
207
213
  message: `${u.selector} transitions \`${u.name}\` over a gradient (${u.image}): a gradient is an image and does not interpolate, so a change to another gradient steps at once with no frame between. To fade it, build the gradient from registered colour properties (@property --c { syntax: "<color>"; inherits: false; initial-value: … }) and transition those, or cross-fade a second gradient layer's opacity. If the gradient never changes, this transition does nothing.`
208
214
  });
209
- for (const u of input.unknownTransitions ?? []) issues.push({
210
- kind: "unknown-transition-property",
211
- severity: "suspect",
212
- selector: u.selector,
213
- message: `${u.selector} transitions \`${u.name}\`, which is no CSS property, so that transition never runs and the property it meant changes in one frame. Check the spelling in transition / transition-property.`
214
- });
215
+ for (const u of input.unknownTransitions ?? []) {
216
+ if (u.duplicate) {
217
+ issues.push({
218
+ kind: "duplicate-keyframes",
219
+ severity: "suspect",
220
+ selector: u.selector,
221
+ message: `${u.selector} plays \`${u.name}\`, which ${u.duplicate.length} @keyframes rules define (${u.duplicate.map((d, i) => `#${i + 1}: ${d || "nothing"}`).join("; ")}): the last one in the cascade wins, so the others never run. Give each its own name.`
222
+ });
223
+ continue;
224
+ }
225
+ if (u.negativeDelayMs !== void 0) {
226
+ issues.push({
227
+ kind: "negative-delay-entrance",
228
+ severity: "warn",
229
+ selector: u.selector,
230
+ message: `${u.selector} \`${u.name}\` has animation-delay ${u.negativeDelayMs}ms: it starts ${-u.negativeDelayMs}ms into its ${u.durationMs}ms run, so that much of its entrance is skipped and it is already part way in at load. A stagger is a positive delay per item (calc(var(--i) * 80ms)); a negative one only suits a loop meant to start mid-run.`
231
+ });
232
+ continue;
233
+ }
234
+ if (u.overridden) {
235
+ const o = u.overridden;
236
+ issues.push({
237
+ kind: "overridden-animation",
238
+ severity: "suspect",
239
+ selector: u.selector,
240
+ message: `${u.selector} \`${u.name}\` and \`${o.by}\` both animate ${o.props.join(", ")}, and \`${o.by}\` comes later in animation-name, so its value wins${o.coveredMs === null ? " for the whole of" : ` for ${o.coveredMs}ms of`} \`${u.name}\`'s run${o.delayMs > 0 && (o.fill === "backwards" || o.fill === "both") ? ` (its ${o.fill} fill holds its first keyframe through its ${Math.round(o.delayMs)}ms delay)` : ""}: that part of \`${u.name}\` never shows. Animate one with an individual property (translate / scale / rotate compose with transform), or drop the backwards fill.`
241
+ });
242
+ continue;
243
+ }
244
+ if (u.counterDrift) {
245
+ const c = u.counterDrift;
246
+ issues.push({
247
+ kind: "counter-rotation-drift",
248
+ severity: "warn",
249
+ selector: u.selector,
250
+ message: `${u.selector} \`${u.name}\` turns ${Math.round(c.mine.deg)}° per ${Math.round(c.mine.ms)}ms against ${c.ancestor}'s \`${c.theirs}\` (${Math.round(c.other.deg)}° per ${Math.round(c.other.ms)}ms), so on screen it turns ${Math.abs(c.net).toFixed(1)}°/s ${c.net > 0 ? "clockwise" : "counterclockwise"}: a counter-rotation meant to keep it level needs the same duration, easing and delay as the turn it cancels. If the drift is meant, ignore this.`
251
+ });
252
+ continue;
253
+ }
254
+ if (u.unitlessVar) {
255
+ const v = u.unitlessVar;
256
+ issues.push({
257
+ kind: "unitless-duration-var",
258
+ severity: "suspect",
259
+ selector: u.selector,
260
+ message: `${u.selector} { ${v.prop}: ${v.text} } reads ${v.variable}, which is ${v.value}: a number with no unit, so the declaration is invalid at computed-value time and ${v.prop.startsWith("animation") ? "the animation" : "the transition"} is dropped (the element snaps). Give the token a unit (${v.value}ms), or write calc(var(${v.variable}) * 1ms).`
261
+ });
262
+ continue;
263
+ }
264
+ if (u.steppedKeyframe) {
265
+ const k = u.steppedKeyframe;
266
+ issues.push({
267
+ kind: "stepped-keyframe",
268
+ severity: "warn",
269
+ selector: u.selector,
270
+ message: `${u.selector} \`${u.name}\`'s ${k.at} keyframe sets animation-timing-function: ${k.easing}, which overrides the element's own ${k.own} from that keyframe to the next: it moves in jumps, not a glide. A timing function inside @keyframes applies per keyframe and wins over the element's; take it out of the keyframe (or give that animation its own keyframes) unless the steps are meant.`
271
+ });
272
+ continue;
273
+ }
274
+ if (u.inertSize) {
275
+ issues.push({
276
+ kind: "inert-size-animation",
277
+ severity: "suspect",
278
+ selector: u.selector,
279
+ message: `${u.selector} \`${u.name}\` animates ${u.inertSize.join(", ")}, but the element is a <${u.tag}> laid out inline (display: inline), where width and height do not apply: it has no box of its own to grow, so nothing is drawn. Give it display: block (or inline-block).`
280
+ });
281
+ continue;
282
+ }
283
+ if (u.unknownMedia) {
284
+ const m = u.unknownMedia;
285
+ issues.push({
286
+ kind: "unknown-media-feature",
287
+ severity: "suspect",
288
+ selector: u.selector,
289
+ message: `@media ${m.header} never matches: the browser does not know the media feature${m.feature ? ` \`${m.feature}\`` : ""} (or its value), so the query is false for everyone and the animations and transitions inside it never apply for anyone${m.suggest && m.suggest !== m.feature ? ` — did you mean \`${m.suggest}\`?` : ""}`
290
+ });
291
+ continue;
292
+ }
293
+ if (u.heldPaused !== void 0) {
294
+ issues.push({
295
+ kind: "held-paused-animation",
296
+ severity: "suspect",
297
+ selector: u.selector,
298
+ message: `${u.selector} \`${u.name}\` is held paused at rest by ${u.heldPaused}, and the element is invisible while it is (opacity 0): the animation never plays, so the element never appears. Whatever should release it has not: a class a script removes (check the name it removes matches), a state the page never reaches. The frames of this evaluation seek it, so they show it as if it ran.`
299
+ });
300
+ continue;
301
+ }
302
+ if (u.restFilter !== void 0) {
303
+ issues.push({
304
+ kind: "held-filter",
305
+ severity: "warn",
306
+ selector: u.selector,
307
+ message: `${u.selector} \`${u.name}\` ends on filter: ${u.restFilter} and its fill holds it at rest: a blur left there softens the element for good (at 1x a blur under 1px can draw as no blur, so a screenshot may not show it), End the animation without the filter, or fill it backwards so the element's own style shows once it ends.`
308
+ });
309
+ continue;
310
+ }
311
+ if (u.inertOffsets) {
312
+ issues.push({
313
+ kind: "inert-offset-animation",
314
+ severity: "suspect",
315
+ selector: u.selector,
316
+ message: `${u.selector} \`${u.name}\` animates ${u.inertOffsets.join(", ")}, but the element is position: static, where ${u.inertOffsets.length === 1 ? "that offset does" : "offsets do"} nothing: whatever else the animation does still shows, and the move it meant never happens. Give it position: relative, or animate transform: translate() (or translate) instead.`
317
+ });
318
+ continue;
319
+ }
320
+ if (u.unregistered) {
321
+ issues.push({
322
+ kind: "unregistered-property-transition",
323
+ severity: "suspect",
324
+ selector: u.selector,
325
+ message: `${u.selector} transitions \`${u.name}\`, a custom property no @property registers: an unregistered custom property has no type, so it does not interpolate and whatever it drives (a gradient stop, a width through calc()) changes in one frame. Register it — @property ${u.name} { syntax: "<percentage>"; inherits: false; initial-value: 0%; }, with the syntax of its values — and the transition runs.`
326
+ });
327
+ continue;
328
+ }
329
+ issues.push({
330
+ kind: "unknown-transition-property",
331
+ severity: "suspect",
332
+ selector: u.selector,
333
+ message: `${u.selector} transitions \`${u.name}\`, which is no CSS property, so that transition never runs and the property it meant changes in one frame. Check the spelling in transition / transition-property.`
334
+ });
335
+ }
215
336
  for (const u of input.undefinedKeyframes ?? []) issues.push({
216
337
  kind: "undefined-keyframes",
217
338
  severity: "suspect",
@@ -564,13 +685,220 @@ const UNKNOWN_TRANSITION_PROPERTY_SCRIPT = `(() => {
564
685
  ${ANIMATION_HELPERS_JS}
565
686
  const out = [];
566
687
  const seen = new Set();
688
+ // Custom properties an @property rule registers (in the sheets the page can read): only those
689
+ // have a type, and a transition on any other one steps at once (round 13's ring).
690
+ const registered = new Set();
691
+ const walk = (rules) => {
692
+ for (const r of rules) {
693
+ if (typeof CSSPropertyRule !== "undefined" && r instanceof CSSPropertyRule) registered.add(r.name);
694
+ else if (r.cssRules) walk(r.cssRules);
695
+ }
696
+ };
697
+ for (const sheet of document.styleSheets) {
698
+ try { walk(sheet.cssRules); } catch {}
699
+ }
700
+ // Registered with a type anywhere (CSS.registerProperty in a script, a sheet the page cannot
701
+ // read): such a property computes \`initial\` to its initial value, an unregistered one to
702
+ // nothing. A switch registered from JS read as unregistered (held-out set).
703
+ const typedProperty = (name) => {
704
+ const probe = document.createElement("div");
705
+ probe.style.setProperty(name, "initial");
706
+ document.documentElement.append(probe);
707
+ const v = getComputedStyle(probe).getPropertyValue(name).trim();
708
+ probe.remove();
709
+ return v !== "";
710
+ };
711
+ // Every @keyframes rule by name, in sheet order, with the properties it animates: the last one
712
+ // of a name wins, and a component's fade-up lost its rise to a utility's later fade-up (round 15).
713
+ const keyframes = new Map();
714
+ const walkKf = (rules) => {
715
+ for (const r of rules) {
716
+ if (typeof CSSKeyframesRule !== "undefined" && r instanceof CSSKeyframesRule) {
717
+ const props = new Set();
718
+ for (const k of r.cssRules) for (let i = 0; i < k.style.length; i++) props.add(k.style[i]);
719
+ if (!keyframes.has(r.name)) keyframes.set(r.name, []);
720
+ keyframes.get(r.name).push([...props]);
721
+ } else if (r.cssRules) walkKf(r.cssRules);
722
+ }
723
+ };
724
+ for (const sheet of document.styleSheets) {
725
+ try { walkKf(sheet.cssRules); } catch {}
726
+ }
567
727
  for (const el of document.querySelectorAll("*")) {
568
728
  const cs = getComputedStyle(el);
729
+ if (out.length < 8) {
730
+ for (const a of el.getAnimations()) {
731
+ const name = a.animationName;
732
+ const t = a.effect && a.effect.getComputedTiming ? a.effect.getComputedTiming() : null;
733
+ const kf = a.effect && a.effect.getKeyframes ? a.effect.getKeyframes() : [];
734
+ const selector = stableSelector(el);
735
+ const defs = name ? keyframes.get(name) : undefined;
736
+ if (defs && defs.length > 1 && !seen.has("dup\u0000" + name)) {
737
+ seen.add("dup\u0000" + name);
738
+ out.push({ selector, name, duplicate: defs.map((d) => d.join(", ")) });
739
+ }
740
+ // An entrance with a negative delay starts part way through: a row 240ms into its 300ms
741
+ // rise was there at load, and the stagger read as running backwards (round 15).
742
+ const first = kf[0] || {};
743
+ const hiddenStart = Number(first.opacity) < 0.05 || (first.transform && first.transform !== "none") || (first.translate && first.translate !== "none");
744
+ if (t && Number(t.delay) < 0 && Number.isFinite(Number(t.iterations)) && hiddenStart && !seen.has("neg\u0000" + selector)) {
745
+ seen.add("neg\u0000" + selector);
746
+ out.push({ selector, name: name || "an animation", negativeDelayMs: Number(t.delay), durationMs: Number(t.duration) });
747
+ }
748
+ // Held paused by the page's CSS (animation-play-state: paused) while it hides the element:
749
+ // results held by a boot class that a script never removed stayed at opacity 0 for good,
750
+ // and the evaluation, seeking every animation, read them "visible" (round 16).
751
+ if (a.playState === "paused" && /paused/.test(cs.animationPlayState) && Number(cs.opacity) < 0.05 && !seen.has("hold\u0000" + selector)) {
752
+ seen.add("hold\u0000" + selector);
753
+ let rule = "";
754
+ const findRule = (rules) => {
755
+ for (const r of rules) {
756
+ if (rule) return;
757
+ if (r.selectorText && r.style && /paused/.test(r.style.animationPlayState || "")) {
758
+ try { if (el.matches(r.selectorText)) rule = r.selectorText + " { animation-play-state: " + r.style.animationPlayState + (r.style.getPropertyPriority("animation-play-state") ? " !important" : "") + " }"; } catch {}
759
+ } else if (r.cssRules) findRule(r.cssRules);
760
+ }
761
+ };
762
+ for (const sheet of document.styleSheets) { try { findRule(sheet.cssRules); } catch {} }
763
+ if (!rule && /paused/.test(el.style.animationPlayState || "")) rule = "its style attribute";
764
+ out.push({ selector, name: name || "an animation", heldPaused: rule || "animation-play-state: paused" });
765
+ }
766
+ // steps() written inside a keyframe overrides the element's smooth easing: a shared
767
+ // entrance's from { animation-timing-function: steps(5, end) } made a panel hop (round 17).
768
+ {
769
+ const stepFn = (e) => /^steps\\(|^step-/.test(String(e || ""));
770
+ const names = cs.animationName.split(/,\\s*/);
771
+ const fns = cs.animationTimingFunction.split(/,\\s*(?![^()]*\\))/);
772
+ const mine = (fns[Math.max(0, names.indexOf(name)) % Math.max(1, fns.length)] || "ease").trim();
773
+ const odd = !stepFn(mine) ? kf.slice(0, -1).find((k) => stepFn(k.easing)) : undefined;
774
+ if (name && odd && !seen.has("stp\\u0000" + selector)) {
775
+ seen.add("stp\\u0000" + selector);
776
+ out.push({ selector, name, steppedKeyframe: { at: odd.offset === 0 ? "from" : odd.offset === 1 ? "to" : Math.round(Number(odd.computedOffset ?? odd.offset) * 100) + "%", easing: String(odd.easing), own: mine } });
777
+ }
778
+ }
779
+ // width / height animated on a non-replaced inline box do nothing: a usage bar written as
780
+ // an empty <span> stayed 0x0 for its whole fill (round 17).
781
+ if (cs.display === "inline" && !/^(img|video|canvas|svg|iframe|input|select|textarea|object|embed)$/i.test(el.tagName) && !seen.has("inl\\u0000" + selector)) {
782
+ const sizes = [...new Set(kf.flatMap((k) => Object.keys(k).filter((p) => /^(width|height|min-width|min-height|max-width|max-height|inline-size|block-size)$/.test(p))))];
783
+ if (sizes.length > 0) {
784
+ seen.add("inl\\u0000" + selector);
785
+ out.push({ selector, name: name || "an animation", inertSize: sizes, tag: el.tagName.toLowerCase() });
786
+ }
787
+ }
788
+ // A fill that holds a filter at rest: blur(0.6px) left a card soft for good, and even
789
+ // blur(0) keeps a filter layer the card is rasterised through (round 15).
790
+ const last = kf[kf.length - 1] || {};
791
+ const changes = (f) => [...f.matchAll(/([a-z-]+)\\(([^)]*)\\)/g)].some(([, fn, arg]) => {
792
+ const v = parseFloat(arg);
793
+ if (!Number.isFinite(v)) return true;
794
+ if (/^(blur|grayscale|sepia|invert|hue-rotate)$/.test(fn)) return Math.abs(v) > 1e-3;
795
+ if (/^(brightness|contrast|saturate|opacity)$/.test(fn)) return Math.abs((arg.includes("%") ? v / 100 : v) - 1) > 1e-3;
796
+ return true;
797
+ });
798
+ if (t && (t.fill === "forwards" || t.fill === "both") && last.filter && last.filter !== "none" && changes(String(last.filter)) && !seen.has("flt\u0000" + selector)) {
799
+ seen.add("flt\u0000" + selector);
800
+ out.push({ selector, name: name || "an animation", restFilter: String(last.filter) });
801
+ }
802
+ }
803
+ }
804
+ // Two animations on one element on one property: the later in animation-name wins wherever its
805
+ // fill reaches. A toast's rise was replaced for its whole run by the pulse after it, whose both
806
+ // fill held scale(1) through its delay, and the rise read "visible" from its fade (round 18).
807
+ if (out.length < 8) {
808
+ const order = cs.animationName.split(/,\\s*/);
809
+ const css = el.getAnimations().filter((a) => typeof CSSAnimation !== "undefined" && a instanceof CSSAnimation)
810
+ .sort((a, b) => order.indexOf(a.animationName) - order.indexOf(b.animationName));
811
+ const propsOf = (a) => new Set(((a.effect && a.effect.getKeyframes) ? a.effect.getKeyframes() : []).flatMap((k) => Object.keys(k).filter((p) => !["offset", "computedOffset", "easing", "composite", "opacity"].includes(p))));
812
+ const span = (a, applying) => {
813
+ const t = a.effect.getComputedTiming();
814
+ const delay = Number(t.delay) || 0;
815
+ const end = Number(t.endTime);
816
+ const fill = t.fill;
817
+ const from = applying && (fill === "backwards" || fill === "both") ? 0 : delay;
818
+ const to = applying && (fill === "forwards" || fill === "both") ? Infinity : end;
819
+ return [from, to, delay, fill];
820
+ };
821
+ for (let i = 0; i < css.length; i++) {
822
+ for (let j = i + 1; j < css.length; j++) {
823
+ const shared = [...propsOf(css[j])].filter((p) => propsOf(css[i]).has(p));
824
+ if (shared.length === 0 || (css[j].effect.composite || "replace") !== "replace") continue;
825
+ const [ai, bi] = span(css[i], false);
826
+ const [aj, bj, dj, fj] = span(css[j], true);
827
+ const overlap = Math.min(bi, bj) - Math.max(ai, aj);
828
+ const selector = stableSelector(el);
829
+ if (overlap > 0 && !seen.has("ovr\u0000" + selector)) {
830
+ seen.add("ovr\u0000" + selector);
831
+ out.push({ selector, name: css[i].animationName, overridden: { by: css[j].animationName, props: shared, delayMs: dj, fill: fj, coveredMs: Number.isFinite(overlap) ? Math.round(overlap) : null } });
832
+ }
833
+ }
834
+ }
835
+ }
836
+ // A counter-rotation that does not cancel its ancestor's turn: a label at -360deg per 5s inside
837
+ // a dial at 360deg per 4s drifted 18deg/s on screen (round 18).
838
+ if (out.length < 8) {
839
+ const turnRate = (node) => {
840
+ for (const a of node.getAnimations()) {
841
+ if (typeof CSSAnimation === "undefined" || !(a instanceof CSSAnimation)) continue;
842
+ const t = a.effect.getComputedTiming();
843
+ if (t.iterations !== Infinity || !(Number(t.duration) > 0)) continue;
844
+ const kf = a.effect.getKeyframes();
845
+ const angle = (k) => {
846
+ const m = /rotate(?:Z)?\\((-?[\\d.]+)(deg|turn|rad|grad)\\)/.exec(String((k && (k.transform || k.rotate)) || ""));
847
+ if (!m) return 0;
848
+ const v = Number(m[1]);
849
+ return m[2] === "turn" ? v * 360 : m[2] === "rad" ? (v * 180) / Math.PI : m[2] === "grad" ? v * 0.9 : v;
850
+ };
851
+ const d = angle(kf[kf.length - 1]) - angle(kf[0]);
852
+ if (Math.abs(d) < 1) continue;
853
+ return { rate: (d / Number(t.duration)) * 1000, name: a.animationName, ms: Number(t.duration), deg: d };
854
+ }
855
+ return null;
856
+ };
857
+ const mine = turnRate(el);
858
+ if (mine) {
859
+ for (let p = el.parentElement; p; p = p.parentElement) {
860
+ const theirs = turnRate(p);
861
+ if (!theirs) continue;
862
+ const net = mine.rate + theirs.rate;
863
+ const selector = stableSelector(el);
864
+ if (Math.sign(mine.rate) !== Math.sign(theirs.rate) && Math.abs(net) > 0.5 && !seen.has("ctr\u0000" + selector)) {
865
+ seen.add("ctr\u0000" + selector);
866
+ out.push({ selector, name: mine.name, counterDrift: { ancestor: stableSelector(p), theirs: theirs.name, mine: { deg: mine.deg, ms: mine.ms }, other: { deg: theirs.deg, ms: theirs.ms }, net } });
867
+ }
868
+ break;
869
+ }
870
+ }
871
+ }
872
+ // An offset animated on a static box does nothing: a notice meant to slide in animated
873
+ // \`left\` and only faded, and \`check animation\` read it "visible" (round 14).
874
+ if (cs.position === "static" && out.length < 8) {
875
+ for (const a of el.getAnimations()) {
876
+ const kf = (a.effect && a.effect.getKeyframes) ? a.effect.getKeyframes() : [];
877
+ const offs = [...new Set(kf.flatMap((k) => Object.keys(k).filter((p) => /^(top|left|right|bottom|inset)/.test(p))))];
878
+ if (offs.length === 0) continue;
879
+ // It moves by a transform as well: the slide happens, the offset is only dead weight (a
880
+ // held-out box animating left and translateX together slid 200px and read "never moves").
881
+ if (kf.some((k) => ["transform", "translate"].some((p) => k[p] !== undefined && k[p] !== "none"))) continue;
882
+ const selector = stableSelector(el);
883
+ const key = selector + "\u0000" + (a.animationName || "");
884
+ if (seen.has(key)) continue;
885
+ seen.add(key);
886
+ out.push({ selector, name: a.animationName || "an animation", inertOffsets: offs });
887
+ }
888
+ }
569
889
  const props = cs.transitionProperty.split(",").map((p) => p.trim());
570
890
  const durations = cs.transitionDuration.split(",").map((d) => parseFloat(d) || 0);
571
891
  props.forEach((name, i) => {
572
- if (!name || name === "all" || name === "none" || name.startsWith("--")) return;
892
+ if (!name || name === "all" || name === "none") return;
573
893
  if (!(durations[i % durations.length] > 0)) return;
894
+ if (name.startsWith("--")) {
895
+ if (registered.has(name) || typedProperty(name)) return;
896
+ const selector = stableSelector(el);
897
+ if (seen.has(selector + "\u0000" + name) || out.length >= 8) return;
898
+ seen.add(selector + "\u0000" + name);
899
+ out.push({ selector, name, unregistered: true });
900
+ return;
901
+ }
574
902
  if (CSS.supports(name, "initial")) return;
575
903
  const selector = stableSelector(el);
576
904
  if (seen.has(selector + "\\u0000" + name) || out.length >= 8) return;
@@ -578,6 +906,81 @@ ${ANIMATION_HELPERS_JS}
578
906
  out.push({ selector, name });
579
907
  });
580
908
  }
909
+ // A duration token with no unit: transition: transform var(--motion-fast) with --motion-fast: 180
910
+ // is invalid at computed-value time, so the drawer had no transition and snapped (round 18).
911
+ {
912
+ const PROPS = ["transition", "transition-duration", "transition-delay", "animation", "animation-duration", "animation-delay"];
913
+ const walkVar = (rules) => {
914
+ for (const r of rules) {
915
+ if (out.length >= 8) return;
916
+ if (typeof CSSStyleRule !== "undefined" && r instanceof CSSStyleRule) {
917
+ for (const prop of PROPS) {
918
+ const text = r.style.getPropertyValue(prop);
919
+ if (!text || !text.includes("var(")) continue;
920
+ let el = null;
921
+ try { el = document.querySelector(r.selectorText); } catch {}
922
+ if (!el) continue;
923
+ const cs = getComputedStyle(el);
924
+ for (const m of text.matchAll(/var\\(\\s*(--[\\w-]+)/g)) {
925
+ // Inside calc() a unitless number is a multiplier (calc(var(--i) * 80ms)), not a duration.
926
+ const before = text.slice(0, m.index);
927
+ const at = before.lastIndexOf("calc(");
928
+ if (at >= 0) {
929
+ let depth = 0;
930
+ for (const ch of before.slice(at + 4)) depth += ch === "(" ? 1 : ch === ")" ? -1 : 0;
931
+ if (depth > 0) continue;
932
+ }
933
+ const v = cs.getPropertyValue(m[1]).trim();
934
+ const key = "var\u0000" + r.selectorText + "\u0000" + prop;
935
+ if (/^-?\\d*\\.?\\d+$/.test(v) && !seen.has(key)) {
936
+ seen.add(key);
937
+ out.push({ selector: r.selectorText, name: prop, unitlessVar: { prop, text, variable: m[1], value: v } });
938
+ }
939
+ }
940
+ }
941
+ } else if (r.cssRules) walkVar(r.cssRules);
942
+ }
943
+ };
944
+ for (const sheet of document.styleSheets) { try { walkVar(sheet.cssRules); } catch {} }
945
+ }
946
+ // An @media whose feature the browser does not know never matches (it reads as "not all"): an
947
+ // entrance behind @media (prefers-reduce-motion: no-preference) never played for anyone, and
948
+ // the page read "animations: 0 … No animation issues detected" (round 17).
949
+ {
950
+ const KNOWN = ["prefers-reduced-motion", "prefers-color-scheme", "prefers-contrast", "prefers-reduced-transparency", "forced-colors", "hover", "any-hover", "pointer", "any-pointer", "orientation", "min-width", "max-width", "width", "min-height", "max-height", "height", "aspect-ratio", "resolution", "min-resolution", "max-resolution", "color-gamut", "display-mode", "scripting", "inverted-colors"];
951
+ const near = (f) => {
952
+ let best = null, bd = Infinity;
953
+ for (const k of KNOWN) {
954
+ const d = (() => { const m = []; for (let i = 0; i <= f.length; i++) { m[i] = [i]; for (let j = 1; j <= k.length; j++) m[i][j] = i === 0 ? j : Math.min(m[i - 1][j] + 1, m[i][j - 1] + 1, m[i - 1][j - 1] + (f[i - 1] === k[j - 1] ? 0 : 1)); } return m[f.length][k.length]; })();
955
+ if (d < bd) { bd = d; best = k; }
956
+ }
957
+ return bd <= 3 ? best : null;
958
+ };
959
+ const moves = (rules) => [...rules].some((r) => (r.style && (/\\S/.test(r.style.animationName || "") && r.style.animationName !== "none" || /\\S/.test(r.style.transitionProperty || "") && (r.style.transitionDuration || "0s") !== "0s")) || (r.cssRules && moves(r.cssRules)));
960
+ // Chromium keeps an unknown feature's text and evaluates it as false; so does its negation. A
961
+ // known feature (and value) matches exactly one of (f) and not (f).
962
+ const unknownAtom = (cond) => {
963
+ for (const m of String(cond).matchAll(/\\(([^()]+)\\)/g)) {
964
+ const atom = "(" + m[1] + ")";
965
+ if (!window.matchMedia(atom).matches && !window.matchMedia("not " + atom).matches) return m[1].trim();
966
+ }
967
+ return null;
968
+ };
969
+ const walkMedia = (rules) => {
970
+ for (const r of rules) {
971
+ if (typeof CSSMediaRule !== "undefined" && r instanceof CSSMediaRule && moves(r.cssRules)) {
972
+ const header = r.conditionText || r.media.mediaText;
973
+ const atom = unknownAtom(header);
974
+ if (atom && !seen.has("med\\u0000" + header) && out.length < 8) {
975
+ seen.add("med\\u0000" + header);
976
+ const feature = (/^\\s*([a-z-]+)/i.exec(atom) || [])[1] || "";
977
+ out.push({ selector: "@media " + header, name: "@media", unknownMedia: { header, feature, suggest: feature ? near(feature) : null } });
978
+ }
979
+ } else if (r.cssRules) walkMedia(r.cssRules);
980
+ }
981
+ };
982
+ for (const sheet of document.styleSheets) { try { walkMedia(sheet.cssRules); } catch {} }
983
+ }
581
984
  return out;
582
985
  })()`;
583
986
  /**
@@ -624,6 +1027,27 @@ ${ANIMATION_HELPERS_JS}
624
1027
  return d;
625
1028
  };
626
1029
  const unit = (k) => (k === "turn" ? "°" : k === "opacity" || k === "scale" ? "%" : "px");
1030
+ // What is in view of it: its children (or itself), clipped by every clipping ancestor and the
1031
+ // viewport, with their content. A ticker one copy long and a shimmer clipped away at both ends
1032
+ // jump in their transform and in nothing seen (authoring v1).
1033
+ const inView = (el) => {
1034
+ let clip = { l: 0, t: 0, r: innerWidth, b: innerHeight };
1035
+ for (let n = el.parentElement; n; n = n.parentElement) {
1036
+ const cs = getComputedStyle(n);
1037
+ if (cs.overflowX !== "visible" || cs.overflowY !== "visible" || cs.clipPath !== "none") {
1038
+ const q = n.getBoundingClientRect();
1039
+ clip = { l: Math.max(clip.l, q.left), t: Math.max(clip.t, q.top), r: Math.min(clip.r, q.right), b: Math.min(clip.b, q.bottom) };
1040
+ }
1041
+ }
1042
+ const parts = el.children.length > 0 ? [...el.children] : [el];
1043
+ return parts
1044
+ .map((c) => ({ q: c.getBoundingClientRect(), key: c.tagName + "." + c.className + "|" + (c.textContent || "").trim().slice(0, 80) }))
1045
+ .filter(({ q }) => q.right > clip.l + 0.5 && q.left < clip.r - 0.5 && q.bottom > clip.t + 0.5 && q.top < clip.b - 0.5)
1046
+ .map(({ q, key }) => ({ x: q.left, y: q.top, w: q.width, h: q.height, key }));
1047
+ };
1048
+ const sameView = (a, b) =>
1049
+ a.length === b.length &&
1050
+ a.every((p) => b.some((q) => q.key === p.key && Math.abs(q.x - p.x) < 1.5 && Math.abs(q.y - p.y) < 1.5 && Math.abs(q.w - p.w) < 1.5 && Math.abs(q.h - p.h) < 1.5));
627
1051
  const describe = (el) => {
628
1052
  let n = el, why = null;
629
1053
  for (let depth = 0; n && depth < 4 && !why; n = n.parentElement, depth++) {
@@ -648,7 +1072,7 @@ ${ANIMATION_HELPERS_JS}
648
1072
  try {
649
1073
  const repeats = !Number.isFinite(t.iterations) || t.iterations > 1;
650
1074
  if (repeats) {
651
- const why = describe(el) || (/spin|load|busy|progress/i.test(name + " " + (el.className && el.className.baseVal !== undefined ? el.className.baseVal : el.className)) ? "named " + name : null);
1075
+ const why = describe(el) || (/spin|load|busy|progress|shimmer|skeleton|marquee|ticker/i.test(name + " " + (el.className && el.className.baseVal !== undefined ? el.className.baseVal : el.className)) ? "named " + name : null);
652
1076
  if (why) out.indicators.push({ index, selector, name, why });
653
1077
  }
654
1078
  const frames = anim.effect.getKeyframes ? anim.effect.getKeyframes() : [];
@@ -656,11 +1080,16 @@ ${ANIMATION_HELPERS_JS}
656
1080
  if (repeats && !stepped && !String(t.direction).startsWith("alternate") && props.length > 0) {
657
1081
  const at = (ms) => { anim.currentTime = ms; return pose(el, props); };
658
1082
  const end = delay + d;
659
- const a = at(end - 2), b = at(end - 1), c = at(end + 0.001), e = at(end + 1);
1083
+ const a = at(end - 2), b = at(end - 1);
1084
+ const v1 = inView(el);
1085
+ const c = at(end + 0.001);
1086
+ const v2 = inView(el);
1087
+ const e = at(end + 1);
660
1088
  const before = diff(a, b), across = diff(b, c), after = diff(c, e);
1089
+ const unseen = sameView(v1, v2);
661
1090
  for (const k of Object.keys(across)) {
662
1091
  const usual = Math.max(before[k], after[k]);
663
- if (across[k] >= 2 && across[k] > 4 * usual + 0.5) {
1092
+ if (across[k] >= 2 && across[k] > 4 * usual + 0.5 && !((k === "x" || k === "y") && unseen)) {
664
1093
  const first = frames[0], last = frames[frames.length - 1];
665
1094
  const prop = k === "turn" || k === "x" || k === "y" || k === "scale" ? "transform" : k.replace(/\\d+$/, "");
666
1095
  out.seams.push({
@@ -848,6 +1277,7 @@ async function sampleClock(page, baseline, shot, windowMs, count, tolerance, min
848
1277
  const known = new Set((await listStarted().catch(() => [])).map((a) => a.key));
849
1278
  const started = [];
850
1279
  const replays = /* @__PURE__ */ new Map();
1280
+ let prevT = 0;
851
1281
  for (const t of times) {
852
1282
  await advanceClock(page, t);
853
1283
  for (const a of await listStarted().catch(() => [])) {
@@ -870,9 +1300,11 @@ async function sampleClock(page, baseline, shot, windowMs, count, tolerance, min
870
1300
  name: a.name,
871
1301
  kind: a.kind,
872
1302
  atMs: t,
1303
+ afterMs: prevT,
873
1304
  ...a.durationMs !== null ? { durationMs: a.durationMs } : {}
874
1305
  });
875
1306
  }
1307
+ prevT = t;
876
1308
  const frame = await shot(`${label}-${t}ms`);
877
1309
  const delta = frameDelta(previous, frame, tolerance);
878
1310
  frames.push(delta);
@@ -958,6 +1390,20 @@ async function runAnimationEval(options) {
958
1390
  const shot = async (_label) => pngFromBuffer(await page.screenshot({ animations: "allow" }));
959
1391
  for (const t of timings) if (t.index >= 0) await seek(t.index, restTimeForAnimation(t));
960
1392
  const evaluable = timings.filter((t) => t.index >= 0 && t.durationMs > 0).slice(0, maxAnimations);
1393
+ const ancestorsOf = await page.evaluate(() => {
1394
+ const list = window.__vlmkitAnims ?? [];
1395
+ const target = (a) => a.effect?.target ?? null;
1396
+ const out = {};
1397
+ list.forEach((a, i) => {
1398
+ const el = target(a);
1399
+ if (!el) return;
1400
+ out[i] = list.map((b, j) => ({
1401
+ b,
1402
+ j
1403
+ })).filter(({ b, j }) => j !== i && target(b) !== el && target(b)?.contains(el)).map(({ j }) => j);
1404
+ });
1405
+ return out;
1406
+ }).catch(() => ({}));
961
1407
  const restProbe = await shot("rest");
962
1408
  const baseline = await shot("rest-recheck");
963
1409
  const restDelta = frameDelta(restProbe, baseline, tolerance);
@@ -965,7 +1411,7 @@ async function runAnimationEval(options) {
965
1411
  const evaluated = [];
966
1412
  const stripRows = [];
967
1413
  for (const timing of evaluable) {
968
- const siblings = timings.filter((t) => t.index >= 0 && t.index !== timing.index && t.selector === timing.selector);
1414
+ const siblings = timings.filter((t) => t.index >= 0 && t.index !== timing.index && (t.selector === timing.selector || (ancestorsOf[timing.index] ?? []).includes(t.index)));
969
1415
  const frames = [];
970
1416
  const rowFrames = [];
971
1417
  let previous = baseline;
@@ -974,6 +1420,12 @@ async function runAnimationEval(options) {
974
1420
  let maxFrameRatio = 0;
975
1421
  let readback = null;
976
1422
  let firstSample = null;
1423
+ {
1424
+ await seek(timing.index, timing.delayMs);
1425
+ for (const sib of siblings) await seek(sib.index, timing.delayMs);
1426
+ const d0 = frameDelta(baseline, await shot(`anim-${timing.index}-0`), tolerance);
1427
+ if (d0.changedPixels >= minChangedPixels) motionBbox = unionBbox(motionBbox, d0.bbox);
1428
+ }
977
1429
  for (let s = 1; s <= samples; s++) {
978
1430
  const fraction = s / samples;
979
1431
  const timeMs = timing.delayMs + Math.min(timing.durationMs * fraction, timing.durationMs - 1);
@@ -1224,7 +1676,7 @@ async function runAnimationEval(options) {
1224
1676
  const b = rmClock.motionBbox;
1225
1677
  const lasted = rmClock.settledAtMs ?? rmClock.windowMs;
1226
1678
  if (lasted >= durationFloor && (rmClock.started ?? []).length > 0) for (const st of rmClock.started) remaining.push({
1227
- selector: `${st.selector} (a ${st.kind} a timer started at ${st.atMs}ms)`,
1679
+ selector: `${st.selector} (a ${st.kind} a timer started ${beganText(st)})`,
1228
1680
  name: st.name,
1229
1681
  durationMs: st.durationMs ?? lasted
1230
1682
  });
@@ -1234,9 +1686,16 @@ async function runAnimationEval(options) {
1234
1686
  durationMs: lasted
1235
1687
  });
1236
1688
  }
1689
+ const moves = (t) => !t.properties || t.properties.length === 0 || t.properties.some((p) => !NOT_MOTION.has(p));
1690
+ const nothingToReduce = remaining.length === 0 && !timings.some(moves) && !clockMotion?.visible;
1691
+ const fadesUnderReduce = rmTimings.filter((t) => t.playState !== "idle" && t.durationMs >= durationFloor && !moves(t)).length;
1237
1692
  reducedMotion = {
1238
1693
  remainingCount: remaining.length,
1239
- remaining
1694
+ remaining,
1695
+ ...nothingToReduce ? {
1696
+ nothingToReduce: true,
1697
+ fadesUnderReduce
1698
+ } : {}
1240
1699
  };
1241
1700
  }
1242
1701
  const key = (u) => `${u.selector}\u0000${u.name}`;
@@ -1292,13 +1751,14 @@ function formatAnimationEvalReport(report, rules) {
1292
1751
  lines.push(`${BOLD}${CYAN}vlmkit check animation${RESET}`);
1293
1752
  lines.push(`${DIM}source: ${report.source} (${report.viewport.width}x${report.viewport.height})${report.virtualTime ? ", page clock held (--virtual-time)" : ""}${RESET}`);
1294
1753
  lines.push("");
1295
- lines.push(`status: ${status}`);
1754
+ const onlyReduced = status === "suspect" && shown.some((i) => i.row.kind === "reduced-motion-ignored") && shown.every((i) => i.row.kind === "reduced-motion-ignored" || i.tier !== "suspect");
1755
+ lines.push(`status: ${status}${onlyReduced ? ` — only reduced-motion-ignored (WCAG 2.3.3, AAA): no other rule fails. If the brief sets no reduced-motion policy, the motion passed; --rule reduced-motion-ignored=off exits 0` : ""}`);
1296
1756
  lines.push(`animations: ${report.animationCount} (evaluated ${report.evaluated.length}, infinite ${report.infinite.length})`, ...report.scrollDriven ? [`scroll-driven: ${report.scrollDriven.map((s) => `${s.selector} \`${s.name}\` on ${s.timeline}`).join(", ")} — its time is the scroll's, so it is not evaluated here: \`vlmkit inspect motion <page> --selector <el>\` sweeps the scroll`] : []);
1297
1757
  const firedKinds = new Set(shown.map((entry) => entry.row.kind));
1298
1758
  const ruleTag = (kind) => firedKinds.has(kind) ? ` ${DIM}[${kind}]${RESET}` : "";
1299
1759
  if (report.settleMs === null) lines.push(`settle: never (infinite animation)` + (firedKinds.has("infinite-animation") ? ` ${DIM}[infinite-animation]${RESET}` : ` ${DIM}(no rule covers this — \`long-settle\` needs a settle time to compare)${RESET}`));
1300
1760
  else lines.push(`settle: ${Math.round(report.settleMs)}ms${ruleTag("long-settle")}`);
1301
- if (report.reducedMotion) lines.push(report.reducedMotion.remainingCount === 0 ? `reduced-motion: honored${report.issues.some((i) => i.kind === "reduced-motion-hides") ? ` — but ${report.issues.filter((i) => i.kind === "reduced-motion-hides").length} element(s) rest hidden or out of place under it${ruleTag("reduced-motion-hides")}` : ""}` : `reduced-motion: ${report.reducedMotion.remainingCount} animation(s) still running${ruleTag("reduced-motion-ignored")}`);
1761
+ if (report.reducedMotion) lines.push(report.reducedMotion.nothingToReduce && !report.issues.some((i) => i.kind === "held-paused-animation") ? `reduced-motion: nothing to reduce — no animation here moves anything (only opacity, colour or visibility)${report.reducedMotion.fadesUnderReduce ? `, and the ${report.reducedMotion.fadesUnderReduce} that run still run under reduce, which the preference allows` : ""}; not a sign the page has a prefers-reduced-motion rule` : report.reducedMotion.remainingCount === 0 && report.issues.some((i) => i.kind === "held-paused-animation") ? `reduced-motion: not judged — ${report.issues.filter((i) => i.kind === "held-paused-animation").length} animation(s) are held paused by the page and never run, with or without the preference${ruleTag("held-paused-animation")}` : report.reducedMotion.remainingCount === 0 ? `reduced-motion: honored${report.issues.some((i) => i.kind === "reduced-motion-hides") ? ` — but ${report.issues.filter((i) => i.kind === "reduced-motion-hides").length} element(s) rest hidden or out of place under it${ruleTag("reduced-motion-hides")}` : ""}` : `reduced-motion: ${report.reducedMotion.remainingCount} animation(s) still running${ruleTag("reduced-motion-ignored")}`);
1302
1762
  if (report.uncontrolledMotion) {
1303
1763
  const m = report.uncontrolledMotion;
1304
1764
  const where = m.bbox ? ` at (${m.bbox.x},${m.bbox.y}) ${m.bbox.width}x${m.bbox.height}` : "";
@@ -1307,7 +1767,7 @@ function formatAnimationEvalReport(report, rules) {
1307
1767
  if (report.clockMotion) {
1308
1768
  const c = report.clockMotion;
1309
1769
  const where = c.motionBbox ? ` at (${c.motionBbox.x},${c.motionBbox.y}) ${c.motionBbox.width}x${c.motionBbox.height}` : "";
1310
- lines.push(!c.visible ? `script-driven motion: none in ${c.windowMs}ms of virtual time` : c.settledAtMs === null && clockUpdatesOnly(c) ? `script-driven change${where}: a timer updates it in place (${c.runs.timers} run(s), no animation frame) — not motion${ruleTag("clock-motion-unsettled")}` : 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")}`);
1770
+ lines.push(!c.visible ? `script-driven motion: none in ${c.windowMs}ms of virtual time` : c.settledAtMs === null && clockUpdatesOnly(c) ? `script-driven change${where}: a timer updates it in place (${c.runs.timers} run(s), no animation frame) — not motion${ruleTag("clock-motion-unsettled")}` : 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")}${(c.started ?? []).some((st) => (st.durationMs ?? 0) > 0) ? ` — the sweep's own frames only: what the timer started runs ${Math.max(...c.started.map((st) => st.durationMs ?? 0))}ms on its own clock, so measure it with \`vlmkit inspect motion <page> --selector <el>\`` : ""}`);
1311
1771
  if (c.visible && (c.started ?? []).length > 0) lines.push(`${DIM} not a requestAnimationFrame loop: ${clockMotionSource(c)}${RESET}`);
1312
1772
  if (c.errors.length > 0) lines.push(`${DIM} page callbacks threw while the clock advanced: ${c.errors.join(" | ")}${RESET}`);
1313
1773
  }
@@ -1362,5 +1822,4 @@ function formatAnimationEvalReport(report, rules) {
1362
1822
  * (`@mizchi/vlmkit-core/plugin/runner.ts`), which owns argument parsing,
1363
1823
  * `--json`, `--advisory`, the run ledger and the exit code.
1364
1824
  */
1365
- //#endregion
1366
1825
  export { DELAYED_ENTRANCE_MS, clockMotionSource, clockSettledAt, clockUpdatesOnly, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox };
@@ -1,7 +1,6 @@
1
1
  import { PageLoadOptions } from "@mizchi/vlmkit-core/page-load.ts";
2
2
  import { FrameEntry, FramesSource } from "@mizchi/vlmkit-judge/frames.ts";
3
3
  import { Page } from "playwright";
4
- //#region src/frames-capture.d.ts
5
4
  export interface HeldAnimationTiming {
6
5
  /** When it starts on the page timeline, delay included. */
7
6
  startMs: number;
@@ -115,5 +114,4 @@ export declare function captureTimelineFrames(page: Page, url: string, options:
115
114
  reducedMotion?: boolean;
116
115
  }): Promise<FramesWritten & {
117
116
  instants: number[];
118
- }>;
119
- //#endregion
117
+ }>;
@@ -5,7 +5,7 @@ import { navigationOptions } from "@mizchi/vlmkit-core/page-load.ts";
5
5
  import { applyHar, settlePage } from "@mizchi/vlmkit-core/page-open.ts";
6
6
  import { FRAMES_FORMAT, frameFileName } from "@mizchi/vlmkit-judge/frames.ts";
7
7
  import { timelineInstants } from "@mizchi/vlmkit-judge/persistence.ts";
8
- //#region src/frames-capture.ts
8
+ // src/frames-capture.ts
9
9
  /**
10
10
  * Frames at chosen instants: the page loaded with its clock and animations held, moved to an
11
11
  * instant of its own time, captured, and written as a `vlmkit-frames/1` sequence.
@@ -418,5 +418,4 @@ async function captureTimelineFrames(page, url, options) {
418
418
  instants
419
419
  };
420
420
  }
421
- //#endregion
422
421
  export { COARSE_GRID_MS, MAX_SWEEP_NAVIGATIONS, captureStable, captureTimelineFrames, defaultTimelineInstants, frameSourceFacts, frameWriter, openHeldTimeline };
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { HOLD_TIMELINE_SCRIPT, VIRTUAL_CLOCK_SCRIPT } from "./virtual-clock.mjs";
2
1
  import { 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
3
  export { HOLD_TIMELINE_SCRIPT, VIRTUAL_CLOCK_SCRIPT, clockSettledAt, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox };
@@ -1,4 +1,3 @@
1
- //#region src/virtual-clock.d.ts
2
1
  /**
3
2
  * A page clock the evaluator owns: `requestAnimationFrame`, `performance.now`, `Date`,
4
3
  * `setTimeout` and `setInterval` all read one virtual time, held at 0 from document start,
@@ -67,5 +66,4 @@ export declare const VIRTUAL_CLOCK_SCRIPT = "(() => {\n if (window.__vlmkitCloc
67
66
  * browser next renders, which can be after the virtual clock has moved on — its start is then late
68
67
  * by up to the advance that started it. That bound is the honest limit of seeking CSS by page time.
69
68
  */
70
- export declare const HOLD_TIMELINE_SCRIPT = "(() => {\n if (window.__vlmkitTimeline) return;\n // { anim, anchor, anchorAt, startAt, pagePaused, cancelled, endedByHold, endedAt }: at page time\n // t a held animation is at anchor + (t - anchorAt) * playbackRate of its local time, clamped to\n // [0, its effect's end]. startAt, for the callers that attribute motion, is the page time its\n // local time was 0 at when it runs forwards (anchorAt - anchor / rate), and the page time it\n // began running backwards from its anchor when it does not. endedByHold: a seek ended it\n // (finish()), at page time endedAt, so its finished state is the hold's, not the page's.\n const held = [];\n window.__vlmkitTimeline = held;\n const entries = new WeakMap();\n const clockNow = () => (window.__vlmkitClock ? window.__vlmkitClock.now() : performance.now());\n const proto = Animation.prototype;\n const nativePause = proto.pause;\n const nativePlay = proto.play;\n const nativeCancel = proto.cancel;\n const nativeFinish = proto.finish;\n const nativeReverse = proto.reverse;\n const nativeUpdateRate = proto.updatePlaybackRate;\n const nativeListen = EventTarget.prototype.addEventListener;\n const accessor = (name) => Object.getOwnPropertyDescriptor(proto, name);\n const currentTimeAccessor = accessor(\"currentTime\");\n const rateAccessor = accessor(\"playbackRate\");\n const startTimeAccessor = accessor(\"startTime\");\n const setCurrent = (anim, ms) => currentTimeAccessor.set.call(anim, ms);\n // Only what runs on the document timeline has a time to seek to: a scroll-driven animation's\n // times are percentages, and pausing one froze a reading-progress bar for good.\n const timeBased = (anim) =>\n typeof DocumentTimeline !== \"undefined\" && anim.timeline instanceof DocumentTimeline;\n // The local time its effect ends at (Infinity when it repeats forever; 0 with no effect).\n const endOf = (anim) => {\n try {\n const end = anim.effect ? anim.effect.getComputedTiming().endTime : 0;\n return typeof end === \"number\" ? end : Infinity;\n } catch { return Infinity; }\n };\n const local = (h, t) => h.anchor + (t - h.anchorAt) * h.anim.playbackRate;\n // Run to its end at page time t: past its effect's end forwards, or back to 0 backwards. One that\n // repeats forever only ends backwards (finish() refuses it forwards).\n const reached = (h, t, end) => {\n const rate = h.anim.playbackRate;\n if (rate > 0) return Number.isFinite(end) && local(h, t) >= end;\n return rate < 0 && local(h, t) <= 0;\n };\n // Where the page clock puts a held animation, ending nothing. A rate of 0 is the page's: it stays.\n const place = (h, t, end = endOf(h.anim)) => {\n if (h.anim.playbackRate === 0) return;\n try { setCurrent(h.anim, Math.min(Math.max(local(h, t), 0), end)); } catch {}\n };\n // While a held animation's end is delivered to the page — its finished promise's reactions, its\n // finish event — what the page starts begins at that end on the page clock, not at the later\n // instant the seek had reached (a coarse sweep started a second stage up to a whole step late).\n // { at, clock }: good while the clock still reads clock, and swept in the task after, since\n // the finish event is dispatched when the browser next renders, after the seek has returned.\n let origin = null;\n const sweep = new MessageChannel();\n sweep.port1.onmessage = () => { origin = null; };\n const startNow = () => {\n const now = clockNow();\n return origin !== null && origin.clock === now ? origin.at : now;\n };\n const adopt = (h) => {\n if (!h.endedByHold || h.endedAt === null) return;\n origin = { at: h.endedAt, clock: clockNow() };\n sweep.port2.postMessage(0);\n };\n // Our reaction on the finished promise the page will wait on, registered before the page can\n // register its own (the animate wrapper runs first), so it runs first when the promise resolves.\n // Each time the animation leaves its finished state the promise is a new one.\n const watch = (h) => {\n try {\n const promise = h.anim.finished;\n if (promise === h.watched) return;\n h.watched = promise;\n promise.then(() => adopt(h), () => {});\n } catch {}\n };\n // Paused where it is, with any pending playback rate applied: reverse() and updatePlaybackRate()\n // leave the new rate pending until the next frame (Chromium 141: playbackRate still read 1 after\n // reverse()), and writing currentTime completes the pause, and applies it, at once.\n const pauseHere = (anim) => {\n try { nativePause.call(anim); } catch {}\n const current = anim.currentTime;\n if (typeof current !== \"number\") return 0;\n try { setCurrent(anim, current); } catch {}\n return current;\n };\n // Animations the page ended itself with finish(): the page's, at any page time.\n const pageFinished = new WeakSet();\n // Held again from where it is now, at the page time it is now: after the page let it run, or\n // moved it. Every rate but 0 is taken over; one at rate 0 does not move, and is left running.\n const takeOver = (h) => {\n if (h.anim.playbackRate !== 0) h.anchor = pauseHere(h.anim);\n else h.anchor = typeof h.anim.currentTime === \"number\" ? h.anim.currentTime : 0;\n h.anchorAt = clockNow();\n h.pagePaused = false;\n h.cancelled = false;\n h.endedByHold = false;\n pageFinished.delete(h.anim);\n watch(h);\n };\n // anchored: its currentTime is the page's choice (new Animation() played, synchronously);\n // otherwise it was found by an event or a sweep, after real time ran, and it begins where found.\n const hold = (anim, anchored = false) => {\n if (!anim || entries.has(anim) || !timeBased(anim)) return;\n const state = anim.playState;\n const at = startNow();\n const h = {\n anim,\n anchor: 0,\n anchorAt: at,\n get startAt() {\n const rate = this.anim.playbackRate;\n return rate > 0 ? this.anchorAt - this.anchor / rate : this.anchorAt;\n },\n // One the page has already paused (a scrubber, animation-play-state: paused) is the page's.\n pagePaused: state === \"paused\",\n cancelled: false,\n endedByHold: false,\n endedAt: null,\n watched: null,\n };\n entries.set(anim, h);\n held.push(h);\n watch(h);\n try { nativeListen.call(anim, \"finish\", () => adopt(h)); } catch {}\n // Found finished while the clock is still at 0: it ran out in the real time load took, and is\n // held from 0 like a running one. Found finished later, it is the page's.\n const restart = state === \"finished\" && clockNow() === 0 && !pageFinished.has(anim);\n if ((state !== \"running\" && !restart) || anim.playbackRate === 0) return;\n const current = pauseHere(anim);\n if (anchored) h.anchor = current;\n else if (anim.playbackRate < 0) {\n // Run backwards it starts from its end, where play() would rewind it to.\n const end = endOf(anim);\n h.anchor = Number.isFinite(end) ? end : current;\n }\n // Put at its page time now when that is not where it was found: one that ran out at load, and\n // one started at a held animation's end that the clock has already passed.\n if (restart || at !== clockNow()) place(h, clockNow());\n };\n // A held animation whose time the hold keeps: not paused or finished by the page, not cancelled\n // or idle. Placing one the page finished would undo its finish().\n const live = (h) => {\n if (!h || h.pagePaused || h.cancelled) return false;\n const state = h.anim.playState;\n return state !== \"idle\" && (state !== \"finished\" || h.endedByHold);\n };\n // The page's own pause and play are seen: a held animation the page pauses is placed at the\n // page's present first (its currentTime is only as fresh as the last seek), then left to the\n // page; one it plays is taken over again from where that leaves it. An animation built with\n // new Animation() is held when the page first plays it.\n proto.pause = function () {\n const h = entries.get(this);\n if (h && !h.pagePaused && !h.cancelled && this.playState !== \"idle\") {\n if (live(h)) place(h, clockNow());\n h.pagePaused = true;\n h.endedByHold = false;\n }\n return nativePause.call(this);\n };\n proto.play = function () {\n const h = entries.get(this);\n if (live(h)) place(h, clockNow());\n const result = nativePlay.call(this);\n if (h) takeOver(h);\n else hold(this, true);\n return result;\n };\n proto.finish = function () {\n pageFinished.add(this);\n const h = entries.get(this);\n if (h) h.endedByHold = false;\n return nativeFinish.call(this);\n };\n // The page's own writes are seen too: one that moves a held animation holds it again from where\n // the write leaves it, at the page time the page made it. Without this a strobe the page set to\n // its end and reversed (currentTime = 2000; playbackRate = -1) sat where the hold had it. One the\n // page had finished and now sets running again (currentTime = 0) is taken over at once, not left\n // to run on the real clock until the next seek.\n const moved = (anim, change) => {\n const h = entries.get(anim);\n const wasLive = live(h);\n if (wasLive) place(h, clockNow());\n const result = change();\n if (wasLive || (h && !h.pagePaused && !h.cancelled && anim.playState === \"running\")) takeOver(h);\n return result;\n };\n for (const [name, desc] of [[\"currentTime\", currentTimeAccessor], [\"playbackRate\", rateAccessor], [\"startTime\", startTimeAccessor]]) {\n if (!desc || !desc.set) continue;\n Object.defineProperty(proto, name, {\n ...desc,\n set(value) { moved(this, () => desc.set.call(this, value)); },\n });\n }\n proto.reverse = function () {\n return moved(this, () => nativeReverse.call(this));\n };\n // On a held animation the new rate is set at once: it is paused, where updatePlaybackRate() and\n // a playbackRate write do the same, except that updatePlaybackRate() leaves it pending a frame.\n proto.updatePlaybackRate = function (rate) {\n if (!live(entries.get(this))) return nativeUpdateRate.call(this, rate);\n return moved(this, () => { rateAccessor.set.call(this, rate); });\n };\n // animationstart and transitionrun are not composed, so each open shadow root is listened to\n // on its own: the ones a script attaches as it attaches them, declarative ones when found.\n const listening = new WeakSet();\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 const listen = (root) => {\n if (listening.has(root)) return;\n listening.add(root);\n root.addEventListener(\"animationstart\", onStart, true);\n root.addEventListener(\"transitionrun\", onStart, true);\n };\n listen(document);\n const nativeAttachShadow = Element.prototype.attachShadow;\n Element.prototype.attachShadow = function (...args) {\n const root = nativeAttachShadow.apply(this, args);\n if (root && root.mode === \"open\") listen(root);\n return root;\n };\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 // document.getAnimations() leaves out shadow trees: every open root, at any depth.\n const openRoots = () => {\n const out = [];\n const walk = (root) => {\n for (const el of root.querySelectorAll(\"*\")) {\n if (el.shadowRoot) { out.push(el.shadowRoot); walk(el.shadowRoot); }\n }\n };\n walk(document);\n return out;\n };\n // SMIL runs on each outermost <svg>'s own timeline, which begins when that svg is inserted\n // (Chromium 141: 0 right after insertion) — at load for one in the page. Each is paused and\n // put at its page time when found, so its startAt is the page time it was found at.\n const SMIL = \"animate, animateTransform, animateMotion, set\";\n const svgs = [];\n const svgSeen = new WeakSet();\n const placeSvg = (s, t) => {\n try {\n s.svg.pauseAnimations();\n s.svg.setCurrentTime(Math.max(0, t - s.startAt) / 1000);\n } catch {}\n };\n // Late arrivals: anything the events missed is held at the instant it is found. A CSS animation\n // still in its delay has fired no animationstart, so both readers sweep: the list read after\n // advanceTo(0) holds everything that exists then. One a script starts later is held by the seek\n // that first finds it.\n const collectLate = () => {\n const roots = openRoots();\n if (document.getAnimations) for (const anim of document.getAnimations()) hold(anim);\n for (const root of roots) {\n listen(root);\n if (root.getAnimations) for (const anim of root.getAnimations()) hold(anim);\n }\n for (const root of [document, ...roots]) {\n for (const svg of root.querySelectorAll(\"svg\")) {\n if (svg.ownerSVGElement || svgSeen.has(svg) || !svg.querySelector(SMIL)) continue;\n svgSeen.add(svg);\n const s = { svg, startAt: clockNow() };\n svgs.push(s);\n placeSvg(s, s.startAt);\n }\n }\n };\n // Once paused through the API a CSS animation outlives its animation-name; the name is compared\n // escaped too, since computed style serialises slide:in as slide\\:in.\n const nameGone = (anim) => {\n if (typeof anim.animationName !== \"string\" || !anim.effect || !anim.effect.target) return false;\n try {\n const listed = getComputedStyle(anim.effect.target, anim.effect.pseudoElement || null)\n .animationName.split(\",\").map((n) => n.trim());\n const escaped = typeof CSS !== \"undefined\" && CSS.escape ? CSS.escape(anim.animationName) : anim.animationName;\n return !listed.includes(anim.animationName) && !listed.includes(escaped);\n } catch { return false; }\n };\n // Every state is read before any animation is moved: playState and computed style each bring\n // style up to date, and read after a currentTime write they recomputed it once per animation:\n // 120 seeks of 150 dealt cards took 855ms that way and ~170ms read first (114ms before these\n // checks existed). Each effect's end is read with them; with that, and each card's finish() at\n // its end, 120 seeks of another 150-card CSS deal measured ~130ms before and ~180ms after.\n //\n // Returns how many animations it ended: their finish events are dispatched when the browser next\n // renders (the clock's rendered()), and what those start can itself end before t.\n window.__vlmkitSeekTimeline = (t) => {\n collectLate();\n const zero = clockNow() === 0;\n let ended = 0;\n const states = held.map((h) => {\n if (h.cancelled) return { state: \"cancelled\", end: 0 };\n const state = h.anim.playState;\n if (state !== \"idle\" && nameGone(h.anim)) return { state: \"gone\", end: 0 };\n return { state, end: state === \"idle\" ? 0 : endOf(h.anim) };\n });\n held.forEach((h, i) => {\n const { state, end } = states[i];\n if (state === \"cancelled\") return;\n // Never revive: setting currentTime on a cancelled (idle) animation brings it back. One the\n // page cancelled, or a CSS one whose element no longer lists its name, is cancelled for good\n // and stays in the list for the callers that attribute motion to it.\n if (state === \"idle\" || state === \"gone\") {\n if (state === \"gone\") { try { nativeCancel.call(h.anim); } catch {} }\n h.cancelled = true;\n return;\n }\n if (state === \"running\") {\n // Running again by a route no wrapper sees (animation-play-state, a changed effect): take\n // it over.\n takeOver(h);\n } else if (state === \"finished\") {\n if (h.endedByHold) {\n // Ended by an earlier seek: it stays ended while the page time is past its end, and a\n // seek back before it (check flash attributes a window at its middle) pauses it and puts\n // it back, instead of letting it run on the real clock.\n if (reached(h, t, end)) return;\n try { nativePause.call(h.anim); } catch {}\n h.endedByHold = false;\n watch(h);\n place(h, t, end);\n return;\n }\n // Ended by the page (finish()), or found finished after the clock moved: the page's.\n // Finished while the clock is still at 0, it ran out during load: held from 0.\n if (h.pagePaused || !zero || pageFinished.has(h.anim)) return;\n h.anchor = h.anim.playbackRate < 0 && Number.isFinite(end) ? end : 0;\n h.anchorAt = 0;\n try { nativePause.call(h.anim); } catch {}\n watch(h);\n }\n if (h.pagePaused || h.anim.playbackRate === 0) return;\n if (!reached(h, t, end)) {\n place(h, t, end);\n return;\n }\n // At or past its end: ended natively, so finished resolves and onfinish / finish listeners\n // run; what they start begins at this end (adopt). A CSS animation's animationend is the\n // phase change, which finish() makes once, as a seek past the end did before.\n const rate = h.anim.playbackRate;\n h.endedAt = Math.max(h.anchorAt, h.anchorAt + ((rate > 0 ? end : 0) - h.anchor) / rate);\n h.endedByHold = true;\n watch(h);\n try {\n nativeFinish.call(h.anim);\n ended += 1;\n } catch {\n h.endedByHold = false;\n place(h, t, end);\n }\n });\n for (const s of svgs) placeSvg(s, t);\n return ended;\n };\n // A SMIL clock value that is a plain number (seconds unless a unit says otherwise), else null.\n const clockValue = (text) => {\n const m = /^\\s*(\\d+(?:\\.\\d+)?|\\.\\d+)(ms|s|min|h)?\\s*$/.exec(text || \"\");\n return m ? Number(m[1]) * { ms: 1, s: 1000, min: 60000, h: 3600000 }[m[2] || \"s\"] : null;\n };\n // begin / dur / repeatCount / repeatDur read off the element; what is not a plain number\n // (an event or syncbase begin, an indefinite or absent dur) is listed as repeating from 0.\n const smilTiming = (el, startAt) => {\n const unknown = { startMs: 0, durationMs: 0, iterations: null };\n const begin = el.hasAttribute(\"begin\") ? clockValue(el.getAttribute(\"begin\")) : 0;\n const dur = clockValue(el.getAttribute(\"dur\"));\n if (begin === null || dur === null) return unknown;\n let iterations = 1;\n const count = el.getAttribute(\"repeatCount\");\n if (count !== null) {\n if (count.trim() === \"indefinite\") iterations = null;\n else if (Number(count) > 0) iterations = Number(count);\n else return unknown;\n }\n const repeatDur = el.getAttribute(\"repeatDur\");\n if (repeatDur !== null && repeatDur.trim() !== \"indefinite\") {\n const span = clockValue(repeatDur);\n if (span === null || !(dur > 0)) return unknown;\n iterations = iterations === null ? span / dur : Math.min(iterations, span / dur);\n } else if (repeatDur !== null && count === null) iterations = null;\n return { startMs: startAt + begin, durationMs: dur, iterations };\n };\n window.__vlmkitTimelineAnimations = () => {\n collectLate();\n const out = held.map((h) => {\n let timing = {};\n try { timing = h.anim.effect && h.anim.effect.getComputedTiming ? h.anim.effect.getComputedTiming() : {}; } catch {}\n const delay = typeof timing.delay === \"number\" ? timing.delay : 0;\n const duration = typeof timing.duration === \"number\" ? timing.duration : 0;\n const iterations = Number.isFinite(timing.iterations) ? timing.iterations : null;\n const rate = h.anim.playbackRate;\n if (!(rate < 0)) {\n // Local times on the page's clock: at rate 2 a 1000ms animation takes 500ms of page time.\n const speed = rate > 0 ? rate : 1;\n return { startMs: h.startAt + delay / speed, durationMs: duration / speed, iterations };\n }\n // Run backwards from its anchor, it plays its active phase from there down to its delay:\n // it enters it once its local time falls below the active phase's end.\n const speed = -rate;\n const activeEnd = delay + (typeof timing.activeDuration === \"number\" ? timing.activeDuration : 0);\n return {\n startMs: h.anchorAt + Math.max(0, h.anchor - activeEnd) / speed,\n durationMs: duration / speed,\n iterations: duration > 0 ? Math.max(0, Math.min(h.anchor, activeEnd) - delay) / duration : 0,\n };\n });\n for (const s of svgs) for (const el of s.svg.querySelectorAll(SMIL)) out.push(smilTiming(el, s.startAt));\n return out;\n };\n})()";
71
- //#endregion
69
+ export declare const HOLD_TIMELINE_SCRIPT = "(() => {\n if (window.__vlmkitTimeline) return;\n // { anim, anchor, anchorAt, startAt, pagePaused, cancelled, endedByHold, endedAt }: at page time\n // t a held animation is at anchor + (t - anchorAt) * playbackRate of its local time, clamped to\n // [0, its effect's end]. startAt, for the callers that attribute motion, is the page time its\n // local time was 0 at when it runs forwards (anchorAt - anchor / rate), and the page time it\n // began running backwards from its anchor when it does not. endedByHold: a seek ended it\n // (finish()), at page time endedAt, so its finished state is the hold's, not the page's.\n const held = [];\n window.__vlmkitTimeline = held;\n const entries = new WeakMap();\n const clockNow = () => (window.__vlmkitClock ? window.__vlmkitClock.now() : performance.now());\n const proto = Animation.prototype;\n const nativePause = proto.pause;\n const nativePlay = proto.play;\n const nativeCancel = proto.cancel;\n const nativeFinish = proto.finish;\n const nativeReverse = proto.reverse;\n const nativeUpdateRate = proto.updatePlaybackRate;\n const nativeListen = EventTarget.prototype.addEventListener;\n const accessor = (name) => Object.getOwnPropertyDescriptor(proto, name);\n const currentTimeAccessor = accessor(\"currentTime\");\n const rateAccessor = accessor(\"playbackRate\");\n const startTimeAccessor = accessor(\"startTime\");\n const setCurrent = (anim, ms) => currentTimeAccessor.set.call(anim, ms);\n // Only what runs on the document timeline has a time to seek to: a scroll-driven animation's\n // times are percentages, and pausing one froze a reading-progress bar for good.\n const timeBased = (anim) =>\n typeof DocumentTimeline !== \"undefined\" && anim.timeline instanceof DocumentTimeline;\n // The local time its effect ends at (Infinity when it repeats forever; 0 with no effect).\n const endOf = (anim) => {\n try {\n const end = anim.effect ? anim.effect.getComputedTiming().endTime : 0;\n return typeof end === \"number\" ? end : Infinity;\n } catch { return Infinity; }\n };\n const local = (h, t) => h.anchor + (t - h.anchorAt) * h.anim.playbackRate;\n // Run to its end at page time t: past its effect's end forwards, or back to 0 backwards. One that\n // repeats forever only ends backwards (finish() refuses it forwards).\n const reached = (h, t, end) => {\n const rate = h.anim.playbackRate;\n if (rate > 0) return Number.isFinite(end) && local(h, t) >= end;\n return rate < 0 && local(h, t) <= 0;\n };\n // Where the page clock puts a held animation, ending nothing. A rate of 0 is the page's: it stays.\n const place = (h, t, end = endOf(h.anim)) => {\n if (h.anim.playbackRate === 0) return;\n try { setCurrent(h.anim, Math.min(Math.max(local(h, t), 0), end)); } catch {}\n };\n // While a held animation's end is delivered to the page — its finished promise's reactions, its\n // finish event — what the page starts begins at that end on the page clock, not at the later\n // instant the seek had reached (a coarse sweep started a second stage up to a whole step late).\n // { at, clock }: good while the clock still reads clock, and swept in the task after, since\n // the finish event is dispatched when the browser next renders, after the seek has returned.\n let origin = null;\n const sweep = new MessageChannel();\n sweep.port1.onmessage = () => { origin = null; };\n const startNow = () => {\n const now = clockNow();\n return origin !== null && origin.clock === now ? origin.at : now;\n };\n const adopt = (h) => {\n if (!h.endedByHold || h.endedAt === null) return;\n origin = { at: h.endedAt, clock: clockNow() };\n sweep.port2.postMessage(0);\n };\n // Our reaction on the finished promise the page will wait on, registered before the page can\n // register its own (the animate wrapper runs first), so it runs first when the promise resolves.\n // Each time the animation leaves its finished state the promise is a new one.\n const watch = (h) => {\n try {\n const promise = h.anim.finished;\n if (promise === h.watched) return;\n h.watched = promise;\n promise.then(() => adopt(h), () => {});\n } catch {}\n };\n // Paused where it is, with any pending playback rate applied: reverse() and updatePlaybackRate()\n // leave the new rate pending until the next frame (Chromium 141: playbackRate still read 1 after\n // reverse()), and writing currentTime completes the pause, and applies it, at once.\n const pauseHere = (anim) => {\n try { nativePause.call(anim); } catch {}\n const current = anim.currentTime;\n if (typeof current !== \"number\") return 0;\n try { setCurrent(anim, current); } catch {}\n return current;\n };\n // Animations the page ended itself with finish(): the page's, at any page time.\n const pageFinished = new WeakSet();\n // Held again from where it is now, at the page time it is now: after the page let it run, or\n // moved it. Every rate but 0 is taken over; one at rate 0 does not move, and is left running.\n const takeOver = (h) => {\n if (h.anim.playbackRate !== 0) h.anchor = pauseHere(h.anim);\n else h.anchor = typeof h.anim.currentTime === \"number\" ? h.anim.currentTime : 0;\n h.anchorAt = clockNow();\n h.pagePaused = false;\n h.cancelled = false;\n h.endedByHold = false;\n pageFinished.delete(h.anim);\n watch(h);\n };\n // anchored: its currentTime is the page's choice (new Animation() played, synchronously);\n // otherwise it was found by an event or a sweep, after real time ran, and it begins where found.\n const hold = (anim, anchored = false) => {\n if (!anim || entries.has(anim) || !timeBased(anim)) return;\n const state = anim.playState;\n const at = startNow();\n const h = {\n anim,\n anchor: 0,\n anchorAt: at,\n get startAt() {\n const rate = this.anim.playbackRate;\n return rate > 0 ? this.anchorAt - this.anchor / rate : this.anchorAt;\n },\n // One the page has already paused (a scrubber, animation-play-state: paused) is the page's.\n pagePaused: state === \"paused\",\n // Where the page held it: released by a route no wrapper sees (animation-play-state) it runs\n // on from here, and one that ran out on the real clock before the first seek began here.\n pausedAt: state === \"paused\" && typeof anim.currentTime === \"number\" ? anim.currentTime : 0,\n cancelled: false,\n endedByHold: false,\n endedAt: null,\n watched: null,\n };\n entries.set(anim, h);\n held.push(h);\n watch(h);\n try { nativeListen.call(anim, \"finish\", () => adopt(h)); } catch {}\n // Found finished while the clock is still at 0: it ran out in the real time load took, and is\n // held from 0 like a running one. Found finished later, it is the page's.\n const restart = state === \"finished\" && clockNow() === 0 && !pageFinished.has(anim);\n if ((state !== \"running\" && !restart) || anim.playbackRate === 0) return;\n const current = pauseHere(anim);\n if (anchored) h.anchor = current;\n else if (anim.playbackRate < 0) {\n // Run backwards it starts from its end, where play() would rewind it to.\n const end = endOf(anim);\n h.anchor = Number.isFinite(end) ? end : current;\n }\n // Put at its page time now when that is not where it was found: one that ran out at load, and\n // one started at a held animation's end that the clock has already passed.\n if (restart || at !== clockNow()) place(h, clockNow());\n };\n // A held animation whose time the hold keeps: not paused or finished by the page, not cancelled\n // or idle. Placing one the page finished would undo its finish().\n const live = (h) => {\n if (!h || h.pagePaused || h.cancelled) return false;\n const state = h.anim.playState;\n return state !== \"idle\" && (state !== \"finished\" || h.endedByHold);\n };\n // The page's own pause and play are seen: a held animation the page pauses is placed at the\n // page's present first (its currentTime is only as fresh as the last seek), then left to the\n // page; one it plays is taken over again from where that leaves it. An animation built with\n // new Animation() is held when the page first plays it.\n proto.pause = function () {\n const h = entries.get(this);\n if (h && !h.pagePaused && !h.cancelled && this.playState !== \"idle\") {\n if (live(h)) place(h, clockNow());\n h.pagePaused = true;\n h.endedByHold = false;\n }\n return nativePause.call(this);\n };\n proto.play = function () {\n const h = entries.get(this);\n if (live(h)) place(h, clockNow());\n const result = nativePlay.call(this);\n if (h) takeOver(h);\n else hold(this, true);\n return result;\n };\n proto.finish = function () {\n pageFinished.add(this);\n const h = entries.get(this);\n if (h) h.endedByHold = false;\n return nativeFinish.call(this);\n };\n // The page's own writes are seen too: one that moves a held animation holds it again from where\n // the write leaves it, at the page time the page made it. Without this a strobe the page set to\n // its end and reversed (currentTime = 2000; playbackRate = -1) sat where the hold had it. One the\n // page had finished and now sets running again (currentTime = 0) is taken over at once, not left\n // to run on the real clock until the next seek.\n const moved = (anim, change) => {\n const h = entries.get(anim);\n const wasLive = live(h);\n if (wasLive) place(h, clockNow());\n const result = change();\n if (wasLive || (h && !h.pagePaused && !h.cancelled && anim.playState === \"running\")) takeOver(h);\n return result;\n };\n for (const [name, desc] of [[\"currentTime\", currentTimeAccessor], [\"playbackRate\", rateAccessor], [\"startTime\", startTimeAccessor]]) {\n if (!desc || !desc.set) continue;\n Object.defineProperty(proto, name, {\n ...desc,\n set(value) { moved(this, () => desc.set.call(this, value)); },\n });\n }\n proto.reverse = function () {\n return moved(this, () => nativeReverse.call(this));\n };\n // On a held animation the new rate is set at once: it is paused, where updatePlaybackRate() and\n // a playbackRate write do the same, except that updatePlaybackRate() leaves it pending a frame.\n proto.updatePlaybackRate = function (rate) {\n if (!live(entries.get(this))) return nativeUpdateRate.call(this, rate);\n return moved(this, () => { rateAccessor.set.call(this, rate); });\n };\n // animationstart and transitionrun are not composed, so each open shadow root is listened to\n // on its own: the ones a script attaches as it attaches them, declarative ones when found.\n const listening = new WeakSet();\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 const listen = (root) => {\n if (listening.has(root)) return;\n listening.add(root);\n root.addEventListener(\"animationstart\", onStart, true);\n root.addEventListener(\"transitionrun\", onStart, true);\n };\n listen(document);\n const nativeAttachShadow = Element.prototype.attachShadow;\n Element.prototype.attachShadow = function (...args) {\n const root = nativeAttachShadow.apply(this, args);\n if (root && root.mode === \"open\") listen(root);\n return root;\n };\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 // document.getAnimations() leaves out shadow trees: every open root, at any depth.\n const openRoots = () => {\n const out = [];\n const walk = (root) => {\n for (const el of root.querySelectorAll(\"*\")) {\n if (el.shadowRoot) { out.push(el.shadowRoot); walk(el.shadowRoot); }\n }\n };\n walk(document);\n return out;\n };\n // SMIL runs on each outermost <svg>'s own timeline, which begins when that svg is inserted\n // (Chromium 141: 0 right after insertion) — at load for one in the page. Each is paused and\n // put at its page time when found, so its startAt is the page time it was found at.\n const SMIL = \"animate, animateTransform, animateMotion, set\";\n const svgs = [];\n const svgSeen = new WeakSet();\n const placeSvg = (s, t) => {\n try {\n s.svg.pauseAnimations();\n s.svg.setCurrentTime(Math.max(0, t - s.startAt) / 1000);\n } catch {}\n };\n // Late arrivals: anything the events missed is held at the instant it is found. A CSS animation\n // still in its delay has fired no animationstart, so both readers sweep: the list read after\n // advanceTo(0) holds everything that exists then. One a script starts later is held by the seek\n // that first finds it.\n const collectLate = () => {\n const roots = openRoots();\n if (document.getAnimations) for (const anim of document.getAnimations()) hold(anim);\n for (const root of roots) {\n listen(root);\n if (root.getAnimations) for (const anim of root.getAnimations()) hold(anim);\n }\n for (const root of [document, ...roots]) {\n for (const svg of root.querySelectorAll(\"svg\")) {\n if (svg.ownerSVGElement || svgSeen.has(svg) || !svg.querySelector(SMIL)) continue;\n svgSeen.add(svg);\n const s = { svg, startAt: clockNow() };\n svgs.push(s);\n placeSvg(s, s.startAt);\n }\n }\n };\n // Once paused through the API a CSS animation outlives its animation-name; the name is compared\n // escaped too, since computed style serialises slide:in as slide\\:in.\n const nameGone = (anim) => {\n if (typeof anim.animationName !== \"string\" || !anim.effect || !anim.effect.target) return false;\n try {\n const listed = getComputedStyle(anim.effect.target, anim.effect.pseudoElement || null)\n .animationName.split(\",\").map((n) => n.trim());\n const escaped = typeof CSS !== \"undefined\" && CSS.escape ? CSS.escape(anim.animationName) : anim.animationName;\n return !listed.includes(anim.animationName) && !listed.includes(escaped);\n } catch { return false; }\n };\n // Every state is read before any animation is moved: playState and computed style each bring\n // style up to date, and read after a currentTime write they recomputed it once per animation:\n // 120 seeks of 150 dealt cards took 855ms that way and ~170ms read first (114ms before these\n // checks existed). Each effect's end is read with them; with that, and each card's finish() at\n // its end, 120 seeks of another 150-card CSS deal measured ~130ms before and ~180ms after.\n //\n // Returns how many animations it ended: their finish events are dispatched when the browser next\n // renders (the clock's rendered()), and what those start can itself end before t.\n // Whether this CSS animation's own entry in animation-play-state is \"paused\" now.\n const cssPlayPaused = (anim) => {\n try {\n if (typeof CSSAnimation === \"undefined\" || !(anim instanceof CSSAnimation)) return false;\n const el = anim.effect && anim.effect.target;\n if (!el) return false;\n const cs = getComputedStyle(el, anim.effect.pseudoElement || null);\n const names = cs.animationName.split(\",\").map((n) => n.trim());\n const states = cs.animationPlayState.split(\",\").map((n) => n.trim());\n const i = names.indexOf(anim.animationName);\n return (states[i < 0 ? 0 : i % states.length] || \"running\") === \"paused\";\n } catch { return false; }\n };\n window.__vlmkitSeekTimeline = (t) => {\n collectLate();\n const zero = clockNow() === 0;\n let ended = 0;\n const states = held.map((h) => {\n if (h.cancelled) return { state: \"cancelled\", end: 0 };\n const state = h.anim.playState;\n if (state !== \"idle\" && nameGone(h.anim)) return { state: \"gone\", end: 0 };\n return { state, end: state === \"idle\" ? 0 : endOf(h.anim) };\n });\n held.forEach((h, i) => {\n const { state, end } = states[i];\n if (state === \"cancelled\") return;\n // Never revive: setting currentTime on a cancelled (idle) animation brings it back. One the\n // page cancelled, or a CSS one whose element no longer lists its name, is cancelled for good\n // and stays in the list for the callers that attribute motion to it.\n if (state === \"idle\" || state === \"gone\") {\n if (state === \"gone\") { try { nativeCancel.call(h.anim); } catch {} }\n h.cancelled = true;\n return;\n }\n if (state === \"running\") {\n // Running again by a route no wrapper sees (animation-play-state, a changed effect): take\n // it over.\n takeOver(h);\n } else if (state === \"finished\") {\n if (h.endedByHold) {\n // Ended by an earlier seek: it stays ended while the page time is past its end, and a\n // seek back before it (check flash attributes a window at its middle) pauses it and puts\n // it back, instead of letting it run on the real clock.\n if (reached(h, t, end)) return;\n try { nativePause.call(h.anim); } catch {}\n h.endedByHold = false;\n watch(h);\n place(h, t, end);\n return;\n }\n // Ended by the page (finish()), or found finished after the clock moved: the page's.\n // Finished while the clock is still at 0, it ran out during load: held from 0. One the page\n // had paused and released by its CSS (a boot class lifted when the fonts are in) ran out on\n // the real clock too, from where it was held: results whose entrance was held until\n // document.fonts.ready read \"travels 0px … target-static\" (round 16).\n if (!zero || pageFinished.has(h.anim)) return;\n if (h.pagePaused && !h.cssReleased) {\n let released = false;\n try {\n const el = h.anim.effect && h.anim.effect.target;\n released = !!el && typeof CSSAnimation !== \"undefined\" && h.anim instanceof CSSAnimation &&\n !/paused/.test(getComputedStyle(el).animationPlayState);\n } catch {}\n if (!released) return;\n h.cssReleased = true;\n }\n h.pagePaused = false;\n h.anchor = h.anim.playbackRate < 0 && Number.isFinite(end) ? end : h.pausedAt || 0;\n h.anchorAt = 0;\n try { nativePause.call(h.anim); } catch {}\n watch(h);\n }\n if (h.pagePaused || h.anim.playbackRate === 0) return;\n // Paused by its CSS while held (a marquee's animation-play-state: paused on :hover): it stays\n // where it is, and carries on from there once its CSS runs it again. Seeked through the pause,\n // a hovered strip read \"travels 309px\" and still-mismatch (authoring v1).\n const cssPaused = cssPlayPaused(h.anim);\n if (cssPaused) {\n if (h.cssPausedAt === undefined) h.cssPausedAt = Math.min(Math.max(local(h, h.lastT ?? t), 0), end);\n h.lastT = t;\n return;\n }\n if (h.cssPausedAt !== undefined) {\n h.anchor = h.cssPausedAt;\n h.anchorAt = t;\n h.cssPausedAt = undefined;\n }\n h.lastT = t;\n if (!reached(h, t, end)) {\n place(h, t, end);\n return;\n }\n // At or past its end: ended natively, so finished resolves and onfinish / finish listeners\n // run; what they start begins at this end (adopt). A CSS animation's animationend is the\n // phase change, which finish() makes once, as a seek past the end did before.\n const rate = h.anim.playbackRate;\n h.endedAt = Math.max(h.anchorAt, h.anchorAt + ((rate > 0 ? end : 0) - h.anchor) / rate);\n h.endedByHold = true;\n watch(h);\n try {\n nativeFinish.call(h.anim);\n ended += 1;\n } catch {\n h.endedByHold = false;\n place(h, t, end);\n }\n });\n for (const s of svgs) placeSvg(s, t);\n return ended;\n };\n // A SMIL clock value that is a plain number (seconds unless a unit says otherwise), else null.\n const clockValue = (text) => {\n const m = /^\\s*(\\d+(?:\\.\\d+)?|\\.\\d+)(ms|s|min|h)?\\s*$/.exec(text || \"\");\n return m ? Number(m[1]) * { ms: 1, s: 1000, min: 60000, h: 3600000 }[m[2] || \"s\"] : null;\n };\n // begin / dur / repeatCount / repeatDur read off the element; what is not a plain number\n // (an event or syncbase begin, an indefinite or absent dur) is listed as repeating from 0.\n const smilTiming = (el, startAt) => {\n const unknown = { startMs: 0, durationMs: 0, iterations: null };\n const begin = el.hasAttribute(\"begin\") ? clockValue(el.getAttribute(\"begin\")) : 0;\n const dur = clockValue(el.getAttribute(\"dur\"));\n if (begin === null || dur === null) return unknown;\n let iterations = 1;\n const count = el.getAttribute(\"repeatCount\");\n if (count !== null) {\n if (count.trim() === \"indefinite\") iterations = null;\n else if (Number(count) > 0) iterations = Number(count);\n else return unknown;\n }\n const repeatDur = el.getAttribute(\"repeatDur\");\n if (repeatDur !== null && repeatDur.trim() !== \"indefinite\") {\n const span = clockValue(repeatDur);\n if (span === null || !(dur > 0)) return unknown;\n iterations = iterations === null ? span / dur : Math.min(iterations, span / dur);\n } else if (repeatDur !== null && count === null) iterations = null;\n return { startMs: startAt + begin, durationMs: dur, iterations };\n };\n window.__vlmkitTimelineAnimations = () => {\n collectLate();\n const out = held.map((h) => {\n let timing = {};\n try { timing = h.anim.effect && h.anim.effect.getComputedTiming ? h.anim.effect.getComputedTiming() : {}; } catch {}\n const delay = typeof timing.delay === \"number\" ? timing.delay : 0;\n const duration = typeof timing.duration === \"number\" ? timing.duration : 0;\n const iterations = Number.isFinite(timing.iterations) ? timing.iterations : null;\n const rate = h.anim.playbackRate;\n if (!(rate < 0)) {\n // Local times on the page's clock: at rate 2 a 1000ms animation takes 500ms of page time.\n const speed = rate > 0 ? rate : 1;\n return { startMs: h.startAt + delay / speed, durationMs: duration / speed, iterations };\n }\n // Run backwards from its anchor, it plays its active phase from there down to its delay:\n // it enters it once its local time falls below the active phase's end.\n const speed = -rate;\n const activeEnd = delay + (typeof timing.activeDuration === \"number\" ? timing.activeDuration : 0);\n return {\n startMs: h.anchorAt + Math.max(0, h.anchor - activeEnd) / speed,\n durationMs: duration / speed,\n iterations: duration > 0 ? Math.max(0, Math.min(h.anchor, activeEnd) - delay) / duration : 0,\n };\n });\n for (const s of svgs) for (const el of s.svg.querySelectorAll(SMIL)) out.push(smilTiming(el, s.startAt));\n return out;\n };\n})()";
@@ -1,4 +1,4 @@
1
- //#region src/virtual-clock.ts
1
+ // src/virtual-clock.ts
2
2
  /**
3
3
  * A page clock the evaluator owns: `requestAnimationFrame`, `performance.now`, `Date`,
4
4
  * `setTimeout` and `setInterval` all read one virtual time, held at 0 from document start,
@@ -387,6 +387,9 @@ const HOLD_TIMELINE_SCRIPT = `(() => {
387
387
  },
388
388
  // One the page has already paused (a scrubber, animation-play-state: paused) is the page's.
389
389
  pagePaused: state === "paused",
390
+ // Where the page held it: released by a route no wrapper sees (animation-play-state) it runs
391
+ // on from here, and one that ran out on the real clock before the first seek began here.
392
+ pausedAt: state === "paused" && typeof anim.currentTime === "number" ? anim.currentTime : 0,
390
393
  cancelled: false,
391
394
  endedByHold: false,
392
395
  endedAt: null,
@@ -564,6 +567,19 @@ const HOLD_TIMELINE_SCRIPT = `(() => {
564
567
  //
565
568
  // Returns how many animations it ended: their finish events are dispatched when the browser next
566
569
  // renders (the clock's rendered()), and what those start can itself end before t.
570
+ // Whether this CSS animation's own entry in animation-play-state is "paused" now.
571
+ const cssPlayPaused = (anim) => {
572
+ try {
573
+ if (typeof CSSAnimation === "undefined" || !(anim instanceof CSSAnimation)) return false;
574
+ const el = anim.effect && anim.effect.target;
575
+ if (!el) return false;
576
+ const cs = getComputedStyle(el, anim.effect.pseudoElement || null);
577
+ const names = cs.animationName.split(",").map((n) => n.trim());
578
+ const states = cs.animationPlayState.split(",").map((n) => n.trim());
579
+ const i = names.indexOf(anim.animationName);
580
+ return (states[i < 0 ? 0 : i % states.length] || "running") === "paused";
581
+ } catch { return false; }
582
+ };
567
583
  window.__vlmkitSeekTimeline = (t) => {
568
584
  collectLate();
569
585
  const zero = clockNow() === 0;
@@ -602,14 +618,43 @@ const HOLD_TIMELINE_SCRIPT = `(() => {
602
618
  return;
603
619
  }
604
620
  // Ended by the page (finish()), or found finished after the clock moved: the page's.
605
- // Finished while the clock is still at 0, it ran out during load: held from 0.
606
- if (h.pagePaused || !zero || pageFinished.has(h.anim)) return;
607
- h.anchor = h.anim.playbackRate < 0 && Number.isFinite(end) ? end : 0;
621
+ // Finished while the clock is still at 0, it ran out during load: held from 0. One the page
622
+ // had paused and released by its CSS (a boot class lifted when the fonts are in) ran out on
623
+ // the real clock too, from where it was held: results whose entrance was held until
624
+ // document.fonts.ready read "travels 0px … target-static" (round 16).
625
+ if (!zero || pageFinished.has(h.anim)) return;
626
+ if (h.pagePaused && !h.cssReleased) {
627
+ let released = false;
628
+ try {
629
+ const el = h.anim.effect && h.anim.effect.target;
630
+ released = !!el && typeof CSSAnimation !== "undefined" && h.anim instanceof CSSAnimation &&
631
+ !/paused/.test(getComputedStyle(el).animationPlayState);
632
+ } catch {}
633
+ if (!released) return;
634
+ h.cssReleased = true;
635
+ }
636
+ h.pagePaused = false;
637
+ h.anchor = h.anim.playbackRate < 0 && Number.isFinite(end) ? end : h.pausedAt || 0;
608
638
  h.anchorAt = 0;
609
639
  try { nativePause.call(h.anim); } catch {}
610
640
  watch(h);
611
641
  }
612
642
  if (h.pagePaused || h.anim.playbackRate === 0) return;
643
+ // Paused by its CSS while held (a marquee's animation-play-state: paused on :hover): it stays
644
+ // where it is, and carries on from there once its CSS runs it again. Seeked through the pause,
645
+ // a hovered strip read "travels 309px" and still-mismatch (authoring v1).
646
+ const cssPaused = cssPlayPaused(h.anim);
647
+ if (cssPaused) {
648
+ if (h.cssPausedAt === undefined) h.cssPausedAt = Math.min(Math.max(local(h, h.lastT ?? t), 0), end);
649
+ h.lastT = t;
650
+ return;
651
+ }
652
+ if (h.cssPausedAt !== undefined) {
653
+ h.anchor = h.cssPausedAt;
654
+ h.anchorAt = t;
655
+ h.cssPausedAt = undefined;
656
+ }
657
+ h.lastT = t;
613
658
  if (!reached(h, t, end)) {
614
659
  place(h, t, end);
615
660
  return;
@@ -687,5 +732,4 @@ const HOLD_TIMELINE_SCRIPT = `(() => {
687
732
  return out;
688
733
  };
689
734
  })()`;
690
- //#endregion
691
735
  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.24.0",
3
+ "version": "0.28.0",
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`.",
5
5
  "license": "MIT",
6
6
  "author": "mizchi",
@@ -37,8 +37,8 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "pngjs": "^7.0.0",
40
- "@mizchi/vlmkit-core": "0.24.0",
41
- "@mizchi/vlmkit-judge": "0.24.0"
40
+ "@mizchi/vlmkit-core": "0.28.0",
41
+ "@mizchi/vlmkit-judge": "0.28.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "playwright": ">=1.61 <2"