@mizchi/vlmkit-animation-eval 0.23.2 → 0.24.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,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { VIRTUAL_CLOCK_SCRIPT } from "./virtual-clock.mjs";
3
+ import { captureTimelineFrames } from "./frames-capture.mjs";
3
4
  import { mkdir, writeFile } from "node:fs/promises";
4
5
  import { STABLE_SELECTOR_JS } from "@mizchi/vlmkit-core/stable-selector.ts";
5
- import { dirname, join, resolve } from "node:path";
6
+ import { dirname, resolve } from "node:path";
6
7
  import { PNG } from "pngjs";
7
8
  import { BOLD, CYAN, DIM, GREEN, RED, RESET, YELLOW } from "@mizchi/vlmkit-core/terminal-colors.ts";
8
9
  import { retuneNote, tierIssues } from "@mizchi/vlmkit-core/plugin/rule-prose.ts";
@@ -14,6 +15,7 @@ import { encodeApng } from "@mizchi/vlmkit-core/apng.ts";
14
15
  import { cropRegion, encodePng } from "@mizchi/vlmkit-core/png-utils.ts";
15
16
  import { encodeWebp, imageFormatForPath } from "@mizchi/vlmkit-core/webp.ts";
16
17
  import { applyHar, settlePage, sourceToUrl } from "@mizchi/vlmkit-core/page-open.ts";
18
+ import { formatInstant, playbackDelays } from "@mizchi/vlmkit-judge/frames.ts";
17
19
  //#region src/animation-eval.ts
18
20
  /**
19
21
  * Frame-sampled animation evaluator.
@@ -40,11 +42,10 @@ import { applyHar, settlePage, sourceToUrl } from "@mizchi/vlmkit-core/page-open
40
42
  *
41
43
  * Usage:
42
44
  * vlmkit check animation <html-or-url>
43
- * vlmkit check animation <html-or-url> --json --frames out/frames
44
- * vlmkit-anim eval <page.html> (the same report from the animation tool)
45
+ * vlmkit check animation <html-or-url> --json --frames out/frames --at 0..600/100
45
46
  *
46
- * Lives in its own package (`@mizchi/vlmkit-animation-eval`) so the animation
47
- * authoring tool can depend on the measurement without the rest of vlmkit.
47
+ * Lives in its own package (`@mizchi/vlmkit-animation-eval`) so a caller can
48
+ * depend on the measurement without the rest of vlmkit.
48
49
  */
49
50
  /**
50
51
  * Effective oscillation of one animation. WAAPI folds both `alternate`
@@ -70,6 +71,19 @@ function computeOscillation(t) {
70
71
  legMs: t.durationMs
71
72
  };
72
73
  }
74
+ /** Pure: the sweep's pixels changed only as a slow timer updated the page (no animation frames). */
75
+ function clockUpdatesOnly(clock) {
76
+ const r = clock.runs;
77
+ if (!r || r.frames > 0) return false;
78
+ if ((clock.started ?? []).length > 0 || (clock.replays ?? []).length > 0) return false;
79
+ return r.timers > 0 && r.timers <= 5 * Math.max(1, clock.windowMs / 1e3);
80
+ }
81
+ /** Pure: what a clock sweep's motion is, named as far as the page let it be. */
82
+ function clockMotionSource(clock) {
83
+ const started = clock.started ?? [];
84
+ 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` : ""}`;
86
+ }
73
87
  /** Pure: the settle instant of a clock sweep — null when its last interval still moved. */
74
88
  function clockSettledAt(times, frames, minChangedPixels) {
75
89
  let settled = 0;
@@ -140,10 +154,76 @@ function computeSettleMs(animations) {
140
154
  }
141
155
  return settle;
142
156
  }
157
+ /** A delay this long (ms) at least, with the element held unseen through it, is a `delayed-entrance`. */
158
+ const DELAYED_ENTRANCE_MS = 1e3;
143
159
  function deriveAnimationIssues(input, options = {}) {
144
160
  const settleThreshold = options.settleThresholdMs ?? 3e3;
145
161
  const durationFloor = options.reducedMotionDurationFloorMs ?? 100;
146
162
  const issues = [];
163
+ for (const h of input.reducedHidden ?? []) {
164
+ const gone = h.reducedOpacity < .05;
165
+ issues.push({
166
+ kind: "reduced-motion-hides",
167
+ severity: "suspect",
168
+ selector: h.selector,
169
+ message: gone ? `${h.selector} rests at opacity ${h.reducedOpacity.toFixed(2)} under prefers-reduced-motion: reduce, and at ${h.opacity.toFixed(2)} without it: the reduce rule took its animation away, and with it the fill that showed it. Give it its end state in that rule (opacity: 1, transform: none), or make the hidden state the first keyframe's (fill: both) instead of the element's own.` : `${h.selector} rests ${Math.round(h.offPx)}px from its place under prefers-reduced-motion: reduce: the reduce rule took its animation away and left the element where the animation started. Give it its end state in that rule (transform: none).`
170
+ });
171
+ }
172
+ for (const push of input.shapes?.pushes ?? []) {
173
+ const moved = push.moved.map((m) => `${m.selector} ${Math.round(Math.hypot(m.dx, m.dy))}px`).join(", ");
174
+ issues.push({
175
+ kind: "layout-animation",
176
+ severity: "warn",
177
+ selector: push.selector,
178
+ message: `${push.selector} \`${push.name}\` animates ${push.props.map((p) => p.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)).join(", ")}, a layout property, in the flow, so it moves ${push.count} element(s) that have no animation of their own: ${moved}${push.count > push.moved.length ? ", …" : ""}. If they are meant to stay put, animate transform instead (or take ${push.selector} out of the flow); if pushing them is the design (an accordion opening), this is it.`
179
+ });
180
+ }
181
+ for (const seam of input.shapes?.seams ?? []) {
182
+ const keyed = seam.from !== null && seam.to !== null ? ` (its keyframes run from ${seam.from} to ${seam.to})` : "";
183
+ const what = seam.channel === "turn" ? "turns" : seam.channel === "opacity" ? "fades" : "jumps";
184
+ issues.push({
185
+ kind: "loop-seam",
186
+ severity: "suspect",
187
+ selector: seam.selector,
188
+ message: `${seam.selector} \`${seam.name}\` ${what} ${seam.step.toFixed(1)}${seam.unit} in one step at the end of every run, against ${seam.usual.toFixed(2)}${seam.unit} a ms either side${keyed}: the run ends off the pose the next begins on. End it on the same pose it starts on (360deg for a turn, a whole copy for a ticker).`
189
+ });
190
+ }
191
+ for (const stroke of input.shapes?.strokes ?? []) issues.push({
192
+ kind: "stroke-incomplete",
193
+ severity: "suspect",
194
+ selector: stroke.selector,
195
+ message: `${stroke.selector} \`${stroke.name}\` draws its stroke and rests ${Math.round(stroke.drawn * 100)}% drawn: ${stroke.note}. A dash shorter than the line leaves the rest of it off; make the dash (and the offset it starts from) at least the line's length, or set pathLength and use that.`
196
+ });
197
+ for (const z of input.zeroDuration ?? []) issues.push({
198
+ kind: "zero-duration-animation",
199
+ severity: "suspect",
200
+ selector: z.selector,
201
+ message: `${z.selector} \`${z.name}\` has no duration (0s): it ends the moment it begins, and its fill holds its last keyframe from the start. If it is meant to follow the scroll, \`animation-timeline\` has to come after the \`animation\` shorthand, which resets it to auto (and the duration to 0s); otherwise give it a duration.`
202
+ });
203
+ for (const u of input.discreteTransitions ?? []) issues.push({
204
+ kind: "discrete-transition",
205
+ severity: "warn",
206
+ selector: u.selector,
207
+ 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
+ });
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.undefinedKeyframes ?? []) issues.push({
216
+ kind: "undefined-keyframes",
217
+ severity: "suspect",
218
+ selector: u.selector,
219
+ message: `${u.selector} names \`${u.name}\` in animation-name${u.reducedMotion ? " under prefers-reduced-motion: reduce" : ""}, but no @keyframes ${u.name} exists, so nothing runs` + (u.reducedMotion ? " — whatever that rule was meant to do for reduced-motion users (hide, settle) does not happen." : ".")
220
+ });
221
+ for (const anim of input.evaluated) if (anim.startsHidden && anim.delayMs >= 1e3 && (anim.fill === "backwards" || anim.fill === "both")) issues.push({
222
+ kind: "delayed-entrance",
223
+ severity: "warn",
224
+ selector: anim.selector,
225
+ message: `${anim.selector} is held unseen for the first ${Math.round(anim.delayMs)}ms: \`${anim.name}\` waits ${Math.round(anim.delayMs)}ms (animation-delay) and its fill (${anim.fill}) keeps its first, hidden keyframe until then. If it should appear with the page, drop the delay; if the wait is meant, this is its design.`
226
+ });
147
227
  for (const anim of input.evaluated) {
148
228
  if (anim.seekIneffective) {
149
229
  const why = anim.seekIneffective.reason === "readback" ? `after a seek the animation ${anim.seekIneffective.detail} — the page cancelled or replaced it, so the gate was moving an object nothing renders` : `seeking back to its first sample did not reproduce that frame (${anim.seekIneffective.detail}) — something other than this animation's time drives those pixels`;
@@ -155,6 +235,17 @@ function deriveAnimationIssues(input, options = {}) {
155
235
  });
156
236
  continue;
157
237
  }
238
+ if (anim.visible && anim.motionBbox && anim.elementBox) {
239
+ const box = anim.elementBox;
240
+ const seen = anim.motionBbox.width * anim.motionBbox.height;
241
+ const area = box.width * box.height;
242
+ if (area >= 400 && seen < area * .25 && (box.topmost ?? 0) < .5) issues.push({
243
+ kind: "motion-mostly-hidden",
244
+ severity: "warn",
245
+ selector: anim.selector,
246
+ message: `${anim.selector} \`${anim.name}\` moved pixels in only ${anim.motionBbox.width}x${anim.motionBbox.height} of its ${box.width}x${box.height} box (${Math.round(seen / area * 100)}%), and it is the topmost thing painted on ${Math.round((box.topmost ?? 0) * 100)}% of that box at rest: most of it is clipped or covered — \`vlmkit inspect motion <page> --selector ${anim.selector}\` names the clip or the cover.`
247
+ });
248
+ }
158
249
  if (!anim.visible) issues.push({
159
250
  kind: "no-visible-effect",
160
251
  severity: "suspect",
@@ -166,15 +257,32 @@ function deriveAnimationIssues(input, options = {}) {
166
257
  kind: "infinite-animation",
167
258
  severity: "warn",
168
259
  selector: anim.selector,
169
- message: `${anim.selector} animation \`${anim.name}\` runs forever — the page never settles. To fix the page, give it a bounded \`animation-iteration-count\` (or stop it once its work is done). If it is meant to run forever, the capture side has to absorb it instead: mask it with \`vlmkit snapshot <url> --mask "${anim.selector}"\` (that flag belongs to \`snapshot\` / \`diff html\`, not to this gate) or pause animations before screenshots.`
260
+ message: anim.indicator ? `${anim.selector} animation \`${anim.name}\` runs forever, on what reads as a loading indicator (${anim.indicator}), which is meant to: that is not a defect of the page. The capture side absorbs it: mask it with \`vlmkit snapshot <url> --mask "${anim.selector}"\` (that flag belongs to \`snapshot\` / \`diff html\`, not to this gate) or pause animations before screenshots. If it should stop once its work is done, give it a bounded \`animation-iteration-count\` or remove it then.` : `${anim.selector} animation \`${anim.name}\` runs forever — the page never settles. To fix the page, give it a bounded \`animation-iteration-count\` (or stop it once its work is done). If it is meant to run forever, the capture side has to absorb it instead: mask it with \`vlmkit snapshot <url> --mask "${anim.selector}"\` (that flag belongs to \`snapshot\` / \`diff html\`, not to this gate) or pause animations before screenshots.`
170
261
  });
171
262
  const clock = input.clockMotion;
172
- if (clock?.visible && clock.settledAtMs === null) {
263
+ for (const r of clock?.replays ?? []) {
264
+ const when = r.atMs.slice(0, 3).map((t) => `${t}ms`).join(", ");
265
+ issues.push({
266
+ kind: "animation-replayed",
267
+ severity: r.newElement ? "suspect" : "warn",
268
+ selector: r.selector,
269
+ message: r.newElement ? `${r.selector} \`${r.name}\` plays again by ${when}${r.atMs.length > 3 ? ", …" : ""} of virtual time on a new element: the page replaced it (a re-render — innerHTML, a framework re-keying the node), and each new one plays its entrance again. Update what it shows (textContent, an attribute) instead of re-creating it.` : `${r.selector} \`${r.name}\` begins again by ${when}${r.atMs.length > 3 ? ", …" : ""} of virtual time on the same element (a class or animation-name toggled on a timer). If it should play once, nothing should start it again.`
270
+ });
271
+ }
272
+ const updatesOnly = clock ? clockUpdatesOnly(clock) : false;
273
+ if (clock?.visible && clock.settledAtMs === null && updatesOnly) {
173
274
  const b = clock.motionBbox;
174
275
  issues.push({
175
276
  kind: "clock-motion-unsettled",
176
277
  severity: "warn",
177
- message: `Script-driven motion at (${b.x},${b.y}) ${b.width}x${b.height} is still changing at ${clock.windowMs}ms of virtual time — a requestAnimationFrame / timer loop that never stops, so the page never settles. Stop the loop once its work is done, and check \`matchMedia("(prefers-reduced-motion: reduce)")\` in the script; if it is meant to run forever, mask the region in captures.`
278
+ message: `The page at (${b.x},${b.y}) ${b.width}x${b.height} changes only when a timer updates it (${clock.runs.timers} timer run(s) in ${clock.windowMs}ms of virtual time, no animation frame): a value updated in place (a clock, a live price) is not motion, and needs nothing under reduced motion. It does keep captures from being still: mask the region in them.`
279
+ });
280
+ } else if (clock?.visible && clock.settledAtMs === null) {
281
+ const b = clock.motionBbox;
282
+ issues.push({
283
+ kind: "clock-motion-unsettled",
284
+ severity: "warn",
285
+ message: `Script-driven motion at (${b.x},${b.y}) ${b.width}x${b.height} is still changing at ${clock.windowMs}ms of virtual time — ${(clock.started ?? []).length > 0 ? `${clockMotionSource(clock)}, and it` : "a requestAnimationFrame / timer loop that"} never stops, so the page never settles. Stop the loop once its work is done, and check \`matchMedia("(prefers-reduced-motion: reduce)")\` in the script; if it is meant to run forever, mask the region in captures.`
178
286
  });
179
287
  } else if (clock?.visible && clock.settledAtMs !== null && clock.settledAtMs > settleThreshold) issues.push({
180
288
  kind: "long-settle",
@@ -201,7 +309,7 @@ function deriveAnimationIssues(input, options = {}) {
201
309
  kind: "reduced-motion-ignored",
202
310
  severity: "suspect",
203
311
  ...sample ? { selector: sample.selector } : {},
204
- message: `${input.reducedMotion.remainingCount} animation(s) still run under \`prefers-reduced-motion: reduce\` emulation: ${input.reducedMotion.remaining.slice(0, 4).map((r) => `${r.selector} \`${r.name}\` ${Math.round(r.durationMs)}ms`).join(", ")}${input.reducedMotion.remaining.length > 4 ? `, and ${input.reducedMotion.remaining.length - 4} more` : ""} — motion is not reduced for users who requested it. Add \`@media (prefers-reduced-motion: reduce)\` and either set \`animation: none\` on them or shorten each duration below ${durationFloor}ms.` + (input.reducedMotion.remaining.some((r) => r.selector.startsWith("(script-driven")) ? ` For the script-driven motion, read \`matchMedia("(prefers-reduced-motion: reduce)")\` and skip or shorten the loop.` : "")
312
+ message: `${input.reducedMotion.remainingCount} animation(s) still run under \`prefers-reduced-motion: reduce\` emulation: ${input.reducedMotion.remaining.slice(0, 4).map((r) => `${r.selector} \`${r.name}\` ${Math.round(r.durationMs)}ms`).join(", ")}${input.reducedMotion.remaining.length > 4 ? `, and ${input.reducedMotion.remaining.length - 4} more` : ""} — motion is not reduced for users who requested it. Add \`@media (prefers-reduced-motion: reduce)\` and either set \`animation: none\` on them or shorten each duration below ${durationFloor}ms. If an element only reaches its place through an animation (an entrance from off-screen or from opacity 0), give it that end state in the same rule — \`animation: none\` alone leaves it where the animation started.` + (input.reducedMotion.remaining.some((r) => r.selector.startsWith("(script-driven")) ? ` For the script-driven motion, read \`matchMedia("(prefers-reduced-motion: reduce)")\` and skip or shorten the loop.` : "") + (input.reducedMotion.remaining.some((r) => r.selector.includes(" a transition a timer started")) ? ` For a transition a timer started, \`transition: none\` on it in that rule reduces it too.` : "") + ` When the task's brief sets no reduced-motion policy, this is WCAG 2.3.3 (AAA) advice rather than a defect of the repair: say so and judge the rest with \`--rule reduced-motion-ignored=off\`.`
205
313
  });
206
314
  }
207
315
  return issues;
@@ -212,18 +320,42 @@ function deriveAnimationIssues(input, options = {}) {
212
320
  * the dedupe between them silently fails.
213
321
  */
214
322
  const ANIMATION_HELPERS_JS = `
323
+ function keyframeProps(anim) {
324
+ try {
325
+ const skip = new Set(["offset", "computedOffset", "easing", "composite"]);
326
+ const frames = anim.effect && anim.effect.getKeyframes ? anim.effect.getKeyframes() : [];
327
+ const props = new Set();
328
+ for (const k of frames) for (const key of Object.keys(k)) if (!skip.has(key)) props.add(key);
329
+ if (anim.transitionProperty) props.add(anim.transitionProperty);
330
+ return [...props];
331
+ } catch {}
332
+ return [];
333
+ }
215
334
  ${STABLE_SELECTOR_JS}
216
335
 
217
336
  function describeTiming(anim) {
218
- let timing = { duration: 0, delay: 0, iterations: 1, direction: "normal" };
337
+ let timing = { duration: 0, delay: 0, iterations: 1, direction: "normal", easing: "linear", fill: "none", startsHidden: false };
219
338
  try {
220
339
  const computed = anim.effect && anim.effect.getComputedTiming ? anim.effect.getComputedTiming() : null;
221
340
  if (computed) {
341
+ // A CSS animation's timing function lives on its keyframes (the effect's own easing is
342
+ // linear); a transition or el.animate() carries it on the effect.
343
+ const frames = anim.effect.getKeyframes ? anim.effect.getKeyframes().slice(0, -1) : [];
344
+ const keyed = [...new Set(frames.map((k) => k.easing).filter(Boolean))];
222
345
  timing = {
223
346
  duration: typeof computed.duration === "number" ? computed.duration : 0,
224
347
  delay: computed.delay || 0,
225
348
  iterations: computed.iterations,
226
349
  direction: computed.direction || "normal",
350
+ easing: computed.easing && computed.easing !== "linear" ? computed.easing : keyed.join(" / ") || "linear",
351
+ fill: computed.fill || "none",
352
+ // Its first keyframe leaves it unseen (opacity 0 or visibility hidden): held there
353
+ // through a delay by a backwards fill, the element is not on screen until it starts.
354
+ startsHidden: (() => {
355
+ const first = anim.effect.getKeyframes ? anim.effect.getKeyframes()[0] : null;
356
+ if (!first) return false;
357
+ return (first.opacity !== undefined && Number(first.opacity) <= 0.05) || first.visibility === "hidden";
358
+ })(),
227
359
  };
228
360
  }
229
361
  } catch {}
@@ -242,11 +374,18 @@ const ANIMATION_HELPERS_JS = `
242
374
  const first = keyframes[0];
243
375
  const last = keyframes[keyframes.length - 1];
244
376
  const props = Object.keys(first).filter((k) => !skip.has(k));
377
+ const same = (a, b) => props.every((k) => String(a[k]) === String(b[k]));
378
+ // Out and back means mirrored: each keyframe at offset o has its twin at 1 - o. An
379
+ // enter / hold / exit (0%, 15%, 90%, 100%, first == last) is not, and read "leg 1650ms".
380
+ const mirrored = keyframes.every((k) =>
381
+ keyframes.some((m) => Math.abs(m.computedOffset - (1 - k.computedOffset)) < 0.011 && same(k, m))
382
+ );
245
383
  return props.length > 0
246
384
  && props.every((k) => k in last && String(first[k]) === String(last[k]))
247
385
  && keyframes.slice(1, -1).some((mid) =>
248
386
  props.some((k) => k in mid && String(mid[k]) !== String(first[k]))
249
- );
387
+ )
388
+ && mirrored;
250
389
  } catch {}
251
390
  return false;
252
391
  }
@@ -296,6 +435,7 @@ ${ANIMATION_HELPERS_JS}
296
435
  const target = event.target;
297
436
  if (!target || !target.getAnimations) return;
298
437
  for (const anim of target.getAnimations()) {
438
+ if (anim.timeline && !(anim.timeline instanceof DocumentTimeline)) continue;
299
439
  const name = animationName(anim);
300
440
  if (event.animationName !== undefined && name !== event.animationName) continue;
301
441
  const timing = describeTiming(anim);
@@ -309,6 +449,7 @@ ${ANIMATION_HELPERS_JS}
309
449
  iterations: Number.isFinite(timing.iterations) ? timing.iterations : null,
310
450
  direction: timing.direction || "normal",
311
451
  palindromic: isPalindromic(anim),
452
+ properties: keyframeProps(anim),
312
453
  authorPlayState,
313
454
  });
314
455
  window.__vlmkitHeld.push(anim);
@@ -321,7 +462,16 @@ ${ANIMATION_HELPERS_JS}
321
462
  })()`;
322
463
  const COLLECT_ANIMATIONS_SCRIPT = `(() => {
323
464
  ${ANIMATION_HELPERS_JS}
324
- const anims = document.getAnimations ? document.getAnimations({ subtree: true }) : [];
465
+ // On a scroll timeline an animation's time is a share of the scroll, not ms: seeking it threw
466
+ // "not supported for progress based animations" (round 12). It is listed, not evaluated.
467
+ const all = document.getAnimations ? document.getAnimations({ subtree: true }) : [];
468
+ const anims = all.filter((a) => !a.timeline || a.timeline instanceof DocumentTimeline);
469
+ window.__vlmkitScrollDriven = all
470
+ .filter((a) => a.timeline && !(a.timeline instanceof DocumentTimeline))
471
+ .map((a) => {
472
+ const el = a.effect && a.effect.target;
473
+ return { selector: el ? stableSelector(el) : "(no target)", name: animationName(a), timeline: el ? getComputedStyle(el).animationTimeline : "" };
474
+ });
325
475
  window.__vlmkitAnims = anims;
326
476
  return anims.map((anim, index) => {
327
477
  const timing = describeTiming(anim);
@@ -349,14 +499,278 @@ ${ANIMATION_HELPERS_JS}
349
499
  name,
350
500
  durationMs: timing.duration,
351
501
  delayMs: timing.delay,
502
+ easing: timing.easing,
503
+ fill: timing.fill,
504
+ startsHidden: timing.startsHidden,
352
505
  iterations: Number.isFinite(timing.iterations) ? timing.iterations : null,
353
506
  playState,
354
507
  currentTimeMs,
355
508
  direction: timing.direction || "normal",
356
509
  palindromic,
510
+ properties: keyframeProps(anim),
357
511
  };
358
512
  });
359
513
  })()`;
514
+ /**
515
+ * Names in an element's computed `animation-name` that no animation ran under: the name has no
516
+ * @keyframes. A reduced-motion rule set to such a name ran nothing, so "honored" was reported
517
+ * for a toast that then never left (from a dynamic-markup run).
518
+ */
519
+ /** Properties whose animation changes how something looks, not where it is or how big. */
520
+ const NOT_MOTION = /* @__PURE__ */ new Set([
521
+ "opacity",
522
+ "visibility",
523
+ "display",
524
+ "contentVisibility",
525
+ "color",
526
+ "backgroundColor",
527
+ "borderColor",
528
+ "borderTopColor",
529
+ "borderRightColor",
530
+ "borderBottomColor",
531
+ "borderLeftColor",
532
+ "outlineColor",
533
+ "textDecorationColor",
534
+ "caretColor",
535
+ "fill",
536
+ "stroke",
537
+ "boxShadow",
538
+ "textShadow"
539
+ ]);
540
+ /**
541
+ * Every animated element at rest — each finite animation finished — with the opacity it renders
542
+ * at and the centre of its box: the targets the page's animations had (null), or those given.
543
+ */
544
+ const restStateScript = (selectors) => `(() => {
545
+ ${STABLE_SELECTOR_JS}
546
+ const given = ${JSON.stringify(selectors)};
547
+ const els = new Set();
548
+ if (given) for (const sel of given) { const el = document.querySelector(sel); if (el) els.add(el); }
549
+ else {
550
+ for (const a of document.getAnimations()) if (a.effect && a.effect.target) els.add(a.effect.target);
551
+ for (const r of window.__vlmkitStarted || []) { try { const el = document.querySelector(r.selector); if (el) els.add(el); } catch {} }
552
+ }
553
+ for (const a of document.getAnimations()) {
554
+ try { if (Number.isFinite(a.effect.getComputedTiming().endTime)) a.finish(); } catch {}
555
+ }
556
+ return [...els].map((el) => {
557
+ let op = getComputedStyle(el).visibility === "hidden" ? 0 : 1;
558
+ for (let n = el; n; n = n.parentElement) op *= Number(getComputedStyle(n).opacity);
559
+ const r = el.getBoundingClientRect();
560
+ return { selector: given ? given[[...els].indexOf(el)] ?? stableSelector(el) : stableSelector(el), opacity: op, x: r.x + r.width / 2, y: r.y + r.height / 2 };
561
+ });
562
+ })()`;
563
+ const UNKNOWN_TRANSITION_PROPERTY_SCRIPT = `(() => {
564
+ ${ANIMATION_HELPERS_JS}
565
+ const out = [];
566
+ const seen = new Set();
567
+ for (const el of document.querySelectorAll("*")) {
568
+ const cs = getComputedStyle(el);
569
+ const props = cs.transitionProperty.split(",").map((p) => p.trim());
570
+ const durations = cs.transitionDuration.split(",").map((d) => parseFloat(d) || 0);
571
+ props.forEach((name, i) => {
572
+ if (!name || name === "all" || name === "none" || name.startsWith("--")) return;
573
+ if (!(durations[i % durations.length] > 0)) return;
574
+ if (CSS.supports(name, "initial")) return;
575
+ const selector = stableSelector(el);
576
+ if (seen.has(selector + "\\u0000" + name) || out.length >= 8) return;
577
+ seen.add(selector + "\\u0000" + name);
578
+ out.push({ selector, name });
579
+ });
580
+ }
581
+ return out;
582
+ })()`;
583
+ /**
584
+ * What an animation does beyond its own box, read from the held animations themselves
585
+ * (motion-repair round 10, where each of these passed every gate):
586
+ * - `pushes`: an in-flow element animating a layout property (`margin-top`) moves the elements
587
+ * after it — their boxes at the start and the end of its first run differ.
588
+ * - `seams`: a repeating animation whose run does not end on the pose the next one begins on
589
+ * (a spinner keyed to 350deg jumps 10deg a second). The step across the end of a run against
590
+ * the steps either side of it; `steps()` timing is left out (every step jumps by design).
591
+ * - `strokes`: a dashed SVG stroke drawing itself that rests part drawn (a dash shorter than
592
+ * its line), from the dash pattern along the path's length.
593
+ * - `indicators`: a looping animation on a loading indicator (role progressbar / status,
594
+ * aria-busy, or named spin / load / busy), which is meant to run forever.
595
+ * Each animation's time is put back as it was found.
596
+ */
597
+ const MOTION_SHAPE_SCRIPT = `(() => {
598
+ ${ANIMATION_HELPERS_JS}
599
+ const anims = window.__vlmkitAnims || [];
600
+ const LAYOUT = /^(margin|padding|width|height|minWidth|minHeight|maxWidth|maxHeight|borderWidth|border(Top|Right|Bottom|Left)Width|fontSize|lineHeight|flexBasis|gap|rowGap|columnGap|gridTemplate)/;
601
+ const nums = (v) => (String(v).match(/-?\\d*\\.?\\d+(e-?\\d+)?/g) || []).map(Number);
602
+ const pose = (el, props) => {
603
+ const cs = getComputedStyle(el);
604
+ const out = {};
605
+ for (const p of props) {
606
+ if (p === "transform") {
607
+ const m = new DOMMatrix(cs.transform === "none" ? undefined : cs.transform);
608
+ out.turn = (Math.atan2(m.b, m.a) * 180) / Math.PI;
609
+ out.x = m.e;
610
+ out.y = m.f;
611
+ out.scale = Math.hypot(m.a, m.b) * 100;
612
+ } else if (p === "opacity") out.opacity = Number(cs.opacity) * 100;
613
+ else nums(cs[p]).forEach((n, i) => { out[p + i] = n; });
614
+ }
615
+ return out;
616
+ };
617
+ const diff = (a, b) => {
618
+ const d = {};
619
+ for (const k of Object.keys(a)) {
620
+ let v = Math.abs((b[k] ?? 0) - a[k]);
621
+ if (k === "turn") v = Math.min(v, 360 - v);
622
+ d[k] = v;
623
+ }
624
+ return d;
625
+ };
626
+ const unit = (k) => (k === "turn" ? "°" : k === "opacity" || k === "scale" ? "%" : "px");
627
+ const describe = (el) => {
628
+ let n = el, why = null;
629
+ for (let depth = 0; n && depth < 4 && !why; n = n.parentElement, depth++) {
630
+ const role = n.getAttribute && n.getAttribute("role");
631
+ if (role === "progressbar" || role === "status") why = 'role="' + role + '"';
632
+ else if (n.getAttribute && n.getAttribute("aria-busy") === "true") why = 'aria-busy="true"';
633
+ }
634
+ return why;
635
+ };
636
+ const out = { pushes: [], seams: [], strokes: [], indicators: [] };
637
+ anims.forEach((anim, index) => {
638
+ const el = anim.effect && anim.effect.target;
639
+ if (!el || !anim.effect.getComputedTiming) return;
640
+ const t = anim.effect.getComputedTiming();
641
+ const d = typeof t.duration === "number" ? t.duration : 0;
642
+ if (!(d > 0)) return;
643
+ const delay = t.delay || 0;
644
+ const props = keyframeProps(anim);
645
+ const saved = anim.currentTime;
646
+ const selector = stableSelector(el);
647
+ const name = animationName(anim);
648
+ try {
649
+ const repeats = !Number.isFinite(t.iterations) || t.iterations > 1;
650
+ 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);
652
+ if (why) out.indicators.push({ index, selector, name, why });
653
+ }
654
+ const frames = anim.effect.getKeyframes ? anim.effect.getKeyframes() : [];
655
+ const stepped = [t.easing || "", ...frames.map((k) => k.easing || "")].some((e) => /steps|step-/.test(e));
656
+ if (repeats && !stepped && !String(t.direction).startsWith("alternate") && props.length > 0) {
657
+ const at = (ms) => { anim.currentTime = ms; return pose(el, props); };
658
+ const end = delay + d;
659
+ const a = at(end - 2), b = at(end - 1), c = at(end + 0.001), e = at(end + 1);
660
+ const before = diff(a, b), across = diff(b, c), after = diff(c, e);
661
+ for (const k of Object.keys(across)) {
662
+ const usual = Math.max(before[k], after[k]);
663
+ if (across[k] >= 2 && across[k] > 4 * usual + 0.5) {
664
+ const first = frames[0], last = frames[frames.length - 1];
665
+ const prop = k === "turn" || k === "x" || k === "y" || k === "scale" ? "transform" : k.replace(/\\d+$/, "");
666
+ out.seams.push({
667
+ selector, name, channel: k, step: across[k], usual, unit: unit(k),
668
+ from: first && first[prop] !== undefined ? String(first[prop]) : null,
669
+ to: last && last[prop] !== undefined ? String(last[prop]) : null,
670
+ prop,
671
+ });
672
+ break;
673
+ }
674
+ }
675
+ }
676
+ const cs = getComputedStyle(el);
677
+ const inFlow = cs.position !== "absolute" && cs.position !== "fixed";
678
+ const layoutProps = props.filter((p) => LAYOUT.test(p));
679
+ if (inFlow && layoutProps.length > 0) {
680
+ const skip = new Set();
681
+ for (let n = el; n; n = n.parentElement) skip.add(n);
682
+ const others = [...document.body.querySelectorAll("*")].filter((n) => !skip.has(n) && !el.contains(n)).slice(0, 2000);
683
+ const rects = () => others.map((n) => n.getBoundingClientRect());
684
+ anim.currentTime = delay;
685
+ const start = rects();
686
+ anim.currentTime = delay + d - 0.001;
687
+ const finish = rects();
688
+ const moved = [];
689
+ others.forEach((n, i) => {
690
+ const s0 = start[i], s1 = finish[i];
691
+ if (s0.width === 0 && s0.height === 0 && s1.width === 0 && s1.height === 0) return;
692
+ const dx = s1.x - s0.x, dy = s1.y - s0.y;
693
+ if (Math.hypot(dx, dy) < 2) return;
694
+ // Only the outermost of what moved together: a moved paragraph's text moves with it.
695
+ const parent = n.parentElement;
696
+ const pi = parent ? others.indexOf(parent) : -1;
697
+ if (pi >= 0) {
698
+ const pdx = finish[pi].x - start[pi].x, pdy = finish[pi].y - start[pi].y;
699
+ if (Math.abs(pdx - dx) < 1 && Math.abs(pdy - dy) < 1) return;
700
+ }
701
+ moved.push({ selector: stableSelector(n), dx, dy });
702
+ });
703
+ if (moved.length > 0) out.pushes.push({ selector, name, props: layoutProps, moved: moved.slice(0, 3), count: moved.length });
704
+ }
705
+ if (el instanceof SVGGeometryElement && Number.isFinite(t.iterations) && props.some((p) => p === "strokeDashoffset" || p === "strokeDasharray")) {
706
+ const drawnShare = () => {
707
+ const st = getComputedStyle(el);
708
+ if (!st.strokeDasharray || st.strokeDasharray === "none") return 1;
709
+ const dash = st.strokeDasharray.split(/[ ,]+/).map(parseFloat).filter((v) => Number.isFinite(v));
710
+ const pattern = dash.length % 2 === 1 ? [...dash, ...dash] : dash;
711
+ const period = pattern.reduce((x, y) => x + y, 0);
712
+ const len = el.getTotalLength();
713
+ const attr = Number(el.getAttribute("pathLength"));
714
+ const scaleLen = Number.isFinite(attr) && attr > 0 ? attr / len : 1;
715
+ const off = parseFloat(st.strokeDashoffset) || 0;
716
+ if (!(period > 0 && len > 0)) return 1;
717
+ let on = 0;
718
+ const step = len / 400;
719
+ for (let x = step / 2; x < len; x += step) {
720
+ let ph = (((x * scaleLen + off) % period) + period) % period;
721
+ for (let k = 0; k < pattern.length; k++) {
722
+ if (ph < pattern[k]) { if (k % 2 === 0) on++; break; }
723
+ ph -= pattern[k];
724
+ }
725
+ }
726
+ return { drawn: on / 400, note: "stroke-dasharray " + st.strokeDasharray + " with stroke-dashoffset " + st.strokeDashoffset + " on a line " + (len * scaleLen).toFixed(1) + " long" };
727
+ };
728
+ anim.currentTime = delay;
729
+ const first = drawnShare();
730
+ anim.currentTime = delay + d * t.iterations;
731
+ const rest = drawnShare();
732
+ const fd = typeof first === "number" ? first : first.drawn;
733
+ if (typeof rest !== "number" && Math.abs(rest.drawn - fd) > 0.05 && rest.drawn > 0.02 && rest.drawn < 0.98) {
734
+ out.strokes.push({ selector, name, drawn: rest.drawn, note: rest.note });
735
+ }
736
+ }
737
+ } catch {}
738
+ anim.currentTime = saved;
739
+ });
740
+ return out;
741
+ })()`;
742
+ const DISCRETE_TRANSITION_SCRIPT = `(() => {
743
+ ${ANIMATION_HELPERS_JS}
744
+ const out = [];
745
+ for (const el of document.querySelectorAll("*")) {
746
+ const cs = getComputedStyle(el);
747
+ if (!/gradient\\(/.test(cs.backgroundImage)) continue;
748
+ const props = cs.transitionProperty.split(",").map((p) => p.trim());
749
+ const durations = cs.transitionDuration.split(",").map((d) => parseFloat(d) || 0);
750
+ // Named, not \`all\`: a gradient button with \`transition: all\` for its hover lift was 4 of 5
751
+ // findings on the repo's pages, and its gradient never changes.
752
+ const i = props.findIndex((p, k) => /^(background|background-image)$/.test(p) && durations[k % durations.length] > 0);
753
+ if (i < 0 || out.length >= 8) continue;
754
+ const image = cs.backgroundImage.length > 60 ? cs.backgroundImage.slice(0, 57) + "..." : cs.backgroundImage;
755
+ out.push({ selector: stableSelector(el), name: props[i], image });
756
+ }
757
+ return out;
758
+ })()`;
759
+ const UNDEFINED_KEYFRAMES_SCRIPT = `(() => {
760
+ ${ANIMATION_HELPERS_JS}
761
+ const ran = new Set((window.__vlmkitStarted || []).map((r) => r.selector + "\\u0000" + r.name));
762
+ const out = [];
763
+ for (const el of document.querySelectorAll("*")) {
764
+ const names = getComputedStyle(el).animationName.split(",").map((n) => n.trim()).filter((n) => n && n !== "none");
765
+ if (names.length === 0) continue;
766
+ const selector = stableSelector(el);
767
+ const live = new Set(el.getAnimations().map((a) => a.animationName).filter(Boolean));
768
+ for (const name of names) {
769
+ if (!live.has(name) && !ran.has(selector + "\\u0000" + name)) out.push({ selector, name });
770
+ }
771
+ }
772
+ return out;
773
+ })()`;
360
774
  function pngFromBuffer(buffer) {
361
775
  const png = PNG.sync.read(buffer);
362
776
  return {
@@ -409,8 +823,56 @@ async function sampleClock(page, baseline, shot, windowMs, count, tolerance, min
409
823
  const frames = [];
410
824
  let previous = baseline;
411
825
  let motionBbox = null;
826
+ const listStarted = () => page.evaluate(`(() => {
827
+ ${STABLE_SELECTOR_JS}
828
+ const seen = (window.__vlmkitSeenAnims = window.__vlmkitSeenAnims || new WeakSet());
829
+ const targets = (window.__vlmkitSeenTargets = window.__vlmkitSeenTargets || new WeakSet());
830
+ return document.getAnimations().map((a) => {
831
+ const el = a.effect && a.effect.target;
832
+ const fresh = !seen.has(a);
833
+ seen.add(a);
834
+ const newElement = !!el && !targets.has(el);
835
+ if (el) targets.add(el);
836
+ const kind = typeof a.transitionProperty === "string" ? "transition" : "animation";
837
+ const name = kind === "transition" ? a.transitionProperty : (a.animationName || a.id || "(el.animate)");
838
+ let durationMs = null;
839
+ try { durationMs = Number(a.effect.getComputedTiming().duration) || null; } catch {}
840
+ return { key: (el ? stableSelector(el) : "(no target)") + "\\u0000" + kind + "\\u0000" + name, selector: el ? stableSelector(el) : "(no target)", name, kind, durationMs, fresh, newElement };
841
+ });
842
+ })()`);
843
+ const readRuns = () => page.evaluate(() => {
844
+ const c = window.__vlmkitClock;
845
+ return c?.runs ? c.runs() : null;
846
+ }).catch(() => null);
847
+ const runsBefore = await readRuns();
848
+ const known = new Set((await listStarted().catch(() => [])).map((a) => a.key));
849
+ const started = [];
850
+ const replays = /* @__PURE__ */ new Map();
412
851
  for (const t of times) {
413
852
  await advanceClock(page, t);
853
+ for (const a of await listStarted().catch(() => [])) {
854
+ if (known.has(a.key) && a.fresh && a.kind === "animation") {
855
+ const r = replays.get(a.key) ?? {
856
+ selector: a.selector,
857
+ name: a.name,
858
+ atMs: [],
859
+ newElement: false
860
+ };
861
+ r.atMs.push(t);
862
+ r.newElement ||= a.newElement;
863
+ replays.set(a.key, r);
864
+ continue;
865
+ }
866
+ if (known.has(a.key)) continue;
867
+ known.add(a.key);
868
+ started.push({
869
+ selector: a.selector,
870
+ name: a.name,
871
+ kind: a.kind,
872
+ atMs: t,
873
+ ...a.durationMs !== null ? { durationMs: a.durationMs } : {}
874
+ });
875
+ }
414
876
  const frame = await shot(`${label}-${t}ms`);
415
877
  const delta = frameDelta(previous, frame, tolerance);
416
878
  frames.push(delta);
@@ -418,6 +880,7 @@ async function sampleClock(page, baseline, shot, windowMs, count, tolerance, min
418
880
  previous = frame;
419
881
  }
420
882
  const errors = await page.evaluate(() => [...window.__vlmkitClock.errors]);
883
+ const runsAfter = await readRuns();
421
884
  return {
422
885
  windowMs,
423
886
  times,
@@ -425,13 +888,19 @@ async function sampleClock(page, baseline, shot, windowMs, count, tolerance, min
425
888
  motionBbox,
426
889
  visible: frames.some((f) => f.changedPixels >= minChangedPixels),
427
890
  settledAtMs: clockSettledAt(times, frames, minChangedPixels),
428
- errors: errors.slice(0, 5)
891
+ errors: errors.slice(0, 5),
892
+ ...started.length > 0 ? { started } : {},
893
+ ...replays.size > 0 ? { replays: [...replays.values()] } : {},
894
+ ...runsBefore && runsAfter ? { runs: {
895
+ frames: runsAfter.frames - runsBefore.frames,
896
+ timers: runsAfter.timers - runsBefore.timers
897
+ } } : {}
429
898
  };
430
899
  }
431
900
  async function runAnimationEval(options) {
432
901
  const viewport = options.viewport ?? {
433
902
  width: 1280,
434
- height: 720
903
+ height: 800
435
904
  };
436
905
  const samples = Math.max(1, options.samples ?? 4);
437
906
  const maxAnimations = options.maxAnimations ?? 8;
@@ -449,16 +918,31 @@ async function runAnimationEval(options) {
449
918
  } else await navigatePage(p, pageUrl, options);
450
919
  if (options.virtualTime) await advanceClock(p, 0);
451
920
  };
921
+ if (options.framesDir && pageUrl === void 0) throw new UsageError("--frames needs the page as a file or URL to load, not inline HTML.");
922
+ const framePaths = [];
452
923
  return await withBrowser(async (browser) => {
453
924
  const page = await browser.newPage({ viewport });
454
925
  await loadPage(page);
455
926
  const timings = await collectAnimations(page);
456
- const selfDriven = timings.filter((t) => t.playState !== "paused" && t.playState !== "idle");
457
- const settleMs = computeSettleMs(selfDriven);
458
- const infinite = selfDriven.filter((t) => t.iterations === null).map((t) => ({
927
+ const scrollDriven = await page.evaluate(() => window.__vlmkitScrollDriven ?? []);
928
+ const zeroDuration = timings.filter((t) => t.type === "css-animation" && t.durationMs === 0).map((t) => ({
459
929
  selector: t.selector,
460
930
  name: t.name
461
931
  }));
932
+ const shapes = await page.evaluate(MOTION_SHAPE_SCRIPT);
933
+ const discreteTransitions = await page.evaluate(DISCRETE_TRANSITION_SCRIPT);
934
+ const undefinedOnPage = await page.evaluate(UNDEFINED_KEYFRAMES_SCRIPT);
935
+ const unknownTransitions = await page.evaluate(UNKNOWN_TRANSITION_PROPERTY_SCRIPT);
936
+ const selfDriven = timings.filter((t) => t.playState !== "paused" && t.playState !== "idle");
937
+ const settleMs = computeSettleMs(selfDriven);
938
+ const infinite = selfDriven.filter((t) => t.iterations === null).map((t) => {
939
+ const indicator = shapes.indicators.find((i) => i.index === t.index)?.why;
940
+ return {
941
+ selector: t.selector,
942
+ name: t.name,
943
+ ...indicator ? { indicator } : {}
944
+ };
945
+ });
462
946
  const seek = async (index, timeMs) => {
463
947
  return await page.evaluate(([i, t]) => {
464
948
  const anim = window.__vlmkitAnims?.[i];
@@ -471,17 +955,7 @@ async function runAnimationEval(options) {
471
955
  return null;
472
956
  }, [index, timeMs]);
473
957
  };
474
- const framePaths = [];
475
- if (options.framesDir) await mkdir(options.framesDir, { recursive: true });
476
- const shot = async (label) => {
477
- const buffer = await page.screenshot({ animations: "allow" });
478
- if (options.framesDir) {
479
- const path = join(options.framesDir, `${label}.png`);
480
- await writeFile(path, buffer);
481
- framePaths.push(path);
482
- }
483
- return pngFromBuffer(buffer);
484
- };
958
+ const shot = async (_label) => pngFromBuffer(await page.screenshot({ animations: "allow" }));
485
959
  for (const t of timings) if (t.index >= 0) await seek(t.index, restTimeForAnimation(t));
486
960
  const evaluable = timings.filter((t) => t.index >= 0 && t.durationMs > 0).slice(0, maxAnimations);
487
961
  const restProbe = await shot("rest");
@@ -491,6 +965,7 @@ async function runAnimationEval(options) {
491
965
  const evaluated = [];
492
966
  const stripRows = [];
493
967
  for (const timing of evaluable) {
968
+ const siblings = timings.filter((t) => t.index >= 0 && t.index !== timing.index && t.selector === timing.selector);
494
969
  const frames = [];
495
970
  const rowFrames = [];
496
971
  let previous = baseline;
@@ -504,6 +979,7 @@ async function runAnimationEval(options) {
504
979
  const timeMs = timing.delayMs + Math.min(timing.durationMs * fraction, timing.durationMs - 1);
505
980
  const seekedTo = Math.max(timing.delayMs, timeMs);
506
981
  readback ??= await seek(timing.index, seekedTo);
982
+ for (const sib of siblings) await seek(sib.index, seekedTo);
507
983
  const frame = await shot(`anim-${timing.index}-${Math.round(fraction * 100)}`);
508
984
  firstSample ??= {
509
985
  timeMs: seekedTo,
@@ -526,6 +1002,7 @@ async function runAnimationEval(options) {
526
1002
  } : void 0;
527
1003
  if (!seekIneffective && firstSample && motionBbox && samples > 1) {
528
1004
  const replayReadback = await seek(timing.index, firstSample.timeMs);
1005
+ for (const sib of siblings) await seek(sib.index, firstSample.timeMs);
529
1006
  const again = await shot(`anim-${timing.index}-replay`);
530
1007
  const region = (f) => cropRegion(f, motionBbox.x, motionBbox.y, motionBbox.width, motionBbox.height);
531
1008
  const replay = frameDelta(region(firstSample.frame), region(again), tolerance);
@@ -535,6 +1012,7 @@ async function runAnimationEval(options) {
535
1012
  };
536
1013
  else if (replay.changedPixels >= minChangedPixels) {
537
1014
  await seek(timing.index, firstSample.timeMs);
1015
+ for (const sib of siblings) await seek(sib.index, firstSample.timeMs);
538
1016
  const third = await shot(`anim-${timing.index}-replay-2`);
539
1017
  const differs = (a, b) => frameDelta(region(a), region(b), tolerance).changedPixels >= minChangedPixels;
540
1018
  if (differs(firstSample.frame, third) && differs(again, third)) seekIneffective = {
@@ -544,12 +1022,42 @@ async function runAnimationEval(options) {
544
1022
  }
545
1023
  }
546
1024
  await seek(timing.index, restTimeForAnimation(timing));
1025
+ for (const sib of siblings) await seek(sib.index, restTimeForAnimation(sib));
1026
+ const elementBox = await page.evaluate((sel) => {
1027
+ const el = document.querySelector(sel);
1028
+ if (!el) return null;
1029
+ const r = el.getBoundingClientRect();
1030
+ const probe = document.createElement("style");
1031
+ probe.textContent = "[data-vlmkit-probe],[data-vlmkit-probe] *{pointer-events:auto!important}";
1032
+ (document.head ?? document.documentElement).append(probe);
1033
+ el.setAttribute("data-vlmkit-probe", "");
1034
+ let inView = 0;
1035
+ let hits = 0;
1036
+ for (let gy = 0; gy < 5; gy++) for (let gx = 0; gx < 5; gx++) {
1037
+ const x = r.x + (gx + .5) / 5 * r.width;
1038
+ const y = r.y + (gy + .5) / 5 * r.height;
1039
+ if (x < 0 || y < 0 || x >= innerWidth || y >= innerHeight) continue;
1040
+ inView++;
1041
+ const top = document.elementFromPoint(x, y);
1042
+ if (top && el.contains(top)) hits++;
1043
+ }
1044
+ el.removeAttribute("data-vlmkit-probe");
1045
+ probe.remove();
1046
+ return {
1047
+ x: Math.round(r.x),
1048
+ y: Math.round(r.y),
1049
+ width: Math.round(r.width),
1050
+ height: Math.round(r.height),
1051
+ topmost: inView === 0 ? 0 : hits / inView
1052
+ };
1053
+ }, timing.selector).catch(() => null);
547
1054
  if (options.stripPath && rowFrames.length > 0) stripRows.push(rowFrames);
548
1055
  evaluated.push({
549
1056
  ...timing,
550
1057
  frames,
551
1058
  visible: frames.some((f) => f.changedPixels >= minChangedPixels),
552
1059
  motionBbox,
1060
+ ...elementBox ? { elementBox } : {},
553
1061
  totalChangedPixels,
554
1062
  maxFrameRatio: Number(maxFrameRatio.toFixed(4)),
555
1063
  ...seekIneffective ? { seekIneffective } : {}
@@ -573,8 +1081,8 @@ async function runAnimationEval(options) {
573
1081
  const rows = evaluated.filter((a) => a.motionBbox && (matched === null || matched.has(a.index)));
574
1082
  if (matched !== null && rows.length === 0) throw new UsageError(`--strip-selector \`${wanted}\` matched no animated element. Animated elements on this page: ${evaluated.map((a) => a.selector).join(", ")}`);
575
1083
  const finiteEnds = rows.filter((a) => a.iterations !== null).map((a) => a.delayMs + a.durationMs * (a.iterations ?? 1));
576
- const windowMs = options.stripWindowMs ?? (finiteEnds.length > 0 ? Math.max(1, ...finiteEnds) : Math.max(1, ...rows.map((a) => a.delayMs + a.durationMs)));
577
- const times = Array.from({ length: samples }, (_, i) => Math.round(windowMs * (i + 1) / samples));
1084
+ const windowMs = (options.at && options.at.length > 0 ? Math.max(...options.at) : void 0) ?? options.stripWindowMs ?? (finiteEnds.length > 0 ? Math.max(1, ...finiteEnds) : Math.max(1, ...rows.map((a) => a.delayMs + a.durationMs)));
1085
+ const times = options.at && options.at.length > 0 ? [...options.at] : Array.from({ length: samples }, (_, i) => Math.round(windowMs * (i + 1) / samples));
578
1086
  const PAD = 8;
579
1087
  const columns = [];
580
1088
  for (const timeMs of times) {
@@ -590,11 +1098,10 @@ async function runAnimationEval(options) {
590
1098
  const cap = options.stripMaxWidth ?? 1600;
591
1099
  const factor = cap > 0 && columns[0].width > cap ? Math.ceil(columns[0].width / cap) : 1;
592
1100
  const played = factor === 1 ? columns : columns.map((frame) => scalePngData(frame, factor));
593
- const gaps = times.slice(1).map((t, i) => t - times[i]);
594
- const holdMs = gaps.length > 0 ? Math.round(gaps.reduce((a, b) => a + b, 0) / gaps.length) : 200;
1101
+ const delaysMs = playbackDelays(times);
595
1102
  const bytes = encodeApng(played, {
596
- delaysMs: [...gaps, holdMs],
597
- delayMs: holdMs
1103
+ delaysMs,
1104
+ delayMs: delaysMs.at(-1)
598
1105
  });
599
1106
  await mkdir(dirname(resolve(options.stripPath)), { recursive: true });
600
1107
  await writeFile(resolve(options.stripPath), bytes);
@@ -612,13 +1119,14 @@ async function runAnimationEval(options) {
612
1119
  animated: true
613
1120
  };
614
1121
  } else {
615
- const sheet = composeFilmstrip(rows.flatMap((anim) => {
1122
+ const cells = rows.flatMap((anim) => {
616
1123
  const bbox = anim.motionBbox;
617
- return columns.map((frame) => cropRegion(frame, Math.max(0, bbox.x - PAD), Math.max(0, bbox.y - PAD), bbox.width + PAD * 2, bbox.height + PAD * 2));
618
- }), {
619
- columns: samples,
1124
+ return columns.map((frame) => cropRegion(frame, Math.max(0, bbox.x - PAD), Math.max(0, bbox.y - PAD), bbox.width + 16, bbox.height + 16));
1125
+ });
1126
+ const sheet = composeFilmstrip(cells, {
1127
+ columns: times.length,
620
1128
  maxWidth: options.stripMaxWidth ?? 1600,
621
- columnLabels: times.map((t) => `${t}ms`),
1129
+ columnLabels: times.map((t) => `${formatInstant(t)}ms`),
622
1130
  rowLabels: rows.map((anim) => `${anim.selector} ${anim.name}`)
623
1131
  });
624
1132
  await mkdir(dirname(resolve(options.stripPath)), { recursive: true });
@@ -639,20 +1147,75 @@ async function runAnimationEval(options) {
639
1147
  }
640
1148
  }
641
1149
  await page.close();
1150
+ let frames;
1151
+ if (options.framesDir) {
1152
+ const framesPage = await browser.newPage({ viewport });
1153
+ try {
1154
+ const written = await captureTimelineFrames(framesPage, pageUrl, {
1155
+ ...options.waitUntil ? { waitUntil: options.waitUntil } : {},
1156
+ ...options.timeout !== void 0 ? { timeout: options.timeout } : {},
1157
+ ...options.har ? { har: options.har } : {},
1158
+ dir: resolve(options.framesDir),
1159
+ tool: "check animation",
1160
+ ...options.at ? { instants: options.at } : {},
1161
+ ...options.framesReducedMotion ? { reducedMotion: true } : {}
1162
+ });
1163
+ const { dir, manifest, count, unstable, instants } = written;
1164
+ frames = {
1165
+ dir,
1166
+ manifest,
1167
+ count,
1168
+ unstable,
1169
+ instants,
1170
+ ...options.framesReducedMotion ? { reducedMotion: true } : {}
1171
+ };
1172
+ framePaths.push(...written.files);
1173
+ } finally {
1174
+ await framesPage.close();
1175
+ }
1176
+ }
642
1177
  let reducedMotion;
1178
+ let undefinedUnderReduce = [];
1179
+ let reducedHidden = [];
643
1180
  if (!options.skipReducedMotion && (timings.length > 0 || clockMotion?.visible)) {
644
1181
  const durationFloor = options.reducedMotionDurationFloorMs ?? 100;
645
1182
  const rmPage = await browser.newPage({ viewport });
646
1183
  await rmPage.emulateMedia({ reducedMotion: "reduce" });
647
1184
  await loadPage(rmPage);
648
1185
  const rmTimings = await collectAnimations(rmPage);
1186
+ {
1187
+ const restPage = await browser.newPage({ viewport });
1188
+ try {
1189
+ await loadPage(restPage);
1190
+ const seenPlain = (await restPage.evaluate(restStateScript(null))).filter((r) => r.opacity >= .5);
1191
+ if (seenPlain.length > 0) {
1192
+ const reduced = await rmPage.evaluate(restStateScript(seenPlain.map((r) => r.selector)));
1193
+ reducedHidden = seenPlain.flatMap((a) => {
1194
+ const b = reduced.find((r) => r.selector === a.selector);
1195
+ if (!b) return [];
1196
+ const offPx = Math.hypot(b.x - a.x, b.y - a.y);
1197
+ return b.opacity < .05 || offPx >= 8 ? [{
1198
+ selector: a.selector,
1199
+ opacity: a.opacity,
1200
+ reducedOpacity: b.opacity,
1201
+ offPx
1202
+ }] : [];
1203
+ });
1204
+ }
1205
+ } catch {
1206
+ reducedHidden = [];
1207
+ } finally {
1208
+ await restPage.close();
1209
+ }
1210
+ }
1211
+ undefinedUnderReduce = await rmPage.evaluate(UNDEFINED_KEYFRAMES_SCRIPT);
649
1212
  let rmClock;
650
1213
  if (options.virtualTime) {
651
1214
  const rmShot = async () => pngFromBuffer(await rmPage.screenshot({ animations: "allow" }));
652
1215
  rmClock = await sampleClock(rmPage, await rmShot(), rmShot, clockWindowMs, clockSamples, tolerance, minChangedPixels, "rm-clock");
653
1216
  }
654
1217
  await rmPage.close();
655
- const remaining = rmTimings.filter((t) => t.playState !== "paused" && t.playState !== "idle" && t.durationMs >= durationFloor).map((t) => ({
1218
+ const remaining = rmTimings.filter((t) => t.playState !== "paused" && t.playState !== "idle" && t.durationMs >= durationFloor).filter((t) => !t.properties || t.properties.length === 0 || t.properties.some((p) => !NOT_MOTION.has(p))).map((t) => ({
656
1219
  selector: t.selector,
657
1220
  name: t.name,
658
1221
  durationMs: t.durationMs
@@ -660,7 +1223,12 @@ async function runAnimationEval(options) {
660
1223
  if (rmClock?.visible && rmClock.motionBbox) {
661
1224
  const b = rmClock.motionBbox;
662
1225
  const lasted = rmClock.settledAtMs ?? rmClock.windowMs;
663
- if (lasted >= durationFloor) remaining.push({
1226
+ 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)`,
1228
+ name: st.name,
1229
+ durationMs: st.durationMs ?? lasted
1230
+ });
1231
+ else if (lasted >= durationFloor && !clockUpdatesOnly(rmClock)) remaining.push({
664
1232
  selector: `(script-driven motion at ${b.x},${b.y} ${b.width}x${b.height})`,
665
1233
  name: "requestAnimationFrame / timers",
666
1234
  durationMs: lasted
@@ -671,6 +1239,15 @@ async function runAnimationEval(options) {
671
1239
  remaining
672
1240
  };
673
1241
  }
1242
+ const key = (u) => `${u.selector}\u0000${u.name}`;
1243
+ const onPage = new Set(undefinedOnPage.map(key));
1244
+ const undefinedKeyframes = [...undefinedOnPage.map((u) => ({
1245
+ ...u,
1246
+ reducedMotion: false
1247
+ })), ...undefinedUnderReduce.filter((u) => !onPage.has(key(u))).map((u) => ({
1248
+ ...u,
1249
+ reducedMotion: true
1250
+ }))];
674
1251
  const issues = deriveAnimationIssues({
675
1252
  evaluated,
676
1253
  settleMs,
@@ -678,7 +1255,13 @@ async function runAnimationEval(options) {
678
1255
  ...reducedMotion ? { reducedMotion } : {},
679
1256
  ...uncontrolledMotion ? { uncontrolledMotion } : {},
680
1257
  ...options.virtualTime ? { virtualTime: true } : {},
681
- ...clockMotion ? { clockMotion } : {}
1258
+ ...clockMotion ? { clockMotion } : {},
1259
+ ...undefinedKeyframes.length > 0 ? { undefinedKeyframes } : {},
1260
+ ...unknownTransitions.length > 0 ? { unknownTransitions } : {},
1261
+ ...discreteTransitions.length > 0 ? { discreteTransitions } : {},
1262
+ ...zeroDuration.length > 0 ? { zeroDuration } : {},
1263
+ ...reducedHidden.length > 0 ? { reducedHidden } : {},
1264
+ shapes
682
1265
  }, {
683
1266
  settleThresholdMs: options.settleThresholdMs,
684
1267
  reducedMotionDurationFloorMs: options.reducedMotionDurationFloorMs
@@ -687,6 +1270,7 @@ async function runAnimationEval(options) {
687
1270
  source: options.source,
688
1271
  viewport,
689
1272
  animationCount: timings.length,
1273
+ ...scrollDriven.length > 0 ? { scrollDriven } : {},
690
1274
  evaluated,
691
1275
  settleMs,
692
1276
  infinite,
@@ -694,8 +1278,10 @@ async function runAnimationEval(options) {
694
1278
  ...uncontrolledMotion ? { uncontrolledMotion } : {},
695
1279
  ...options.virtualTime ? { virtualTime: true } : {},
696
1280
  ...clockMotion ? { clockMotion } : {},
1281
+ ...undefinedKeyframes.length > 0 ? { undefinedKeyframes } : {},
697
1282
  issues,
698
1283
  ...framePaths.length > 0 ? { framePaths } : {},
1284
+ ...frames ? { frames } : {},
699
1285
  ...strip ? { strip } : {}
700
1286
  };
701
1287
  });
@@ -707,12 +1293,12 @@ function formatAnimationEvalReport(report, rules) {
707
1293
  lines.push(`${DIM}source: ${report.source} (${report.viewport.width}x${report.viewport.height})${report.virtualTime ? ", page clock held (--virtual-time)" : ""}${RESET}`);
708
1294
  lines.push("");
709
1295
  lines.push(`status: ${status}`);
710
- lines.push(`animations: ${report.animationCount} (evaluated ${report.evaluated.length}, infinite ${report.infinite.length})`);
1296
+ 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`] : []);
711
1297
  const firedKinds = new Set(shown.map((entry) => entry.row.kind));
712
1298
  const ruleTag = (kind) => firedKinds.has(kind) ? ` ${DIM}[${kind}]${RESET}` : "";
713
1299
  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}`));
714
1300
  else lines.push(`settle: ${Math.round(report.settleMs)}ms${ruleTag("long-settle")}`);
715
- if (report.reducedMotion) lines.push(report.reducedMotion.remainingCount === 0 ? `reduced-motion: honored` : `reduced-motion: ${report.reducedMotion.remainingCount} animation(s) still running${ruleTag("reduced-motion-ignored")}`);
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")}`);
716
1302
  if (report.uncontrolledMotion) {
717
1303
  const m = report.uncontrolledMotion;
718
1304
  const where = m.bbox ? ` at (${m.bbox.x},${m.bbox.y}) ${m.bbox.width}x${m.bbox.height}` : "";
@@ -721,7 +1307,8 @@ function formatAnimationEvalReport(report, rules) {
721
1307
  if (report.clockMotion) {
722
1308
  const c = report.clockMotion;
723
1309
  const where = c.motionBbox ? ` at (${c.motionBbox.x},${c.motionBbox.y}) ${c.motionBbox.width}x${c.motionBbox.height}` : "";
724
- lines.push(!c.visible ? `script-driven motion: none in ${c.windowMs}ms of virtual time` : c.settledAtMs === null ? `script-driven motion${where}: still moving at ${c.windowMs}ms of virtual time${ruleTag("clock-motion-unsettled")}` : `script-driven motion${where}: settles by ${c.settledAtMs}ms of virtual time${ruleTag("long-settle")}`);
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")}`);
1311
+ if (c.visible && (c.started ?? []).length > 0) lines.push(`${DIM} not a requestAnimationFrame loop: ${clockMotionSource(c)}${RESET}`);
725
1312
  if (c.errors.length > 0) lines.push(`${DIM} page callbacks threw while the clock advanced: ${c.errors.join(" | ")}${RESET}`);
726
1313
  }
727
1314
  if (report.evaluated.length > 0) {
@@ -731,8 +1318,8 @@ function formatAnimationEvalReport(report, rules) {
731
1318
  const bbox = anim.motionBbox ? `(${anim.motionBbox.x},${anim.motionBbox.y}) ${anim.motionBbox.width}x${anim.motionBbox.height}` : "none";
732
1319
  const visibility = anim.seekIneffective ? `${RED}not measured (seek ineffective)${RESET}` : anim.visible ? `${GREEN}visible${RESET}` : `${RED}no visible effect${RESET}`;
733
1320
  const osc = computeOscillation(anim);
734
- const oscLabel = osc.oscillating ? ` (${anim.direction.startsWith("alternate") ? anim.direction : "palindromic keyframes"}, leg ${Math.round(osc.legMs)}ms)` : "";
735
- lines.push(` - ${anim.selector} \`${anim.name}\` ${Math.round(anim.durationMs)}ms x${anim.iterations ?? "∞"}${oscLabel}: ${visibility}, motion region ${bbox}, peak frame delta ${(anim.maxFrameRatio * 100).toFixed(2)}%`);
1321
+ const oscLabel = osc.oscillating ? anim.direction.startsWith("alternate") ? ` (${anim.direction}, leg ${Math.round(osc.legMs)}ms)` : ` (palindromic keyframes: each ${Math.round(anim.durationMs)}ms run goes out and back, ${Math.round(osc.legMs)}ms each way)` : "";
1322
+ lines.push(` - ${anim.selector} \`${anim.name}\` ${Math.round(anim.durationMs)}ms${anim.delayMs ? ` after ${Math.round(anim.delayMs)}ms` : ""}${anim.easing ? ` ${anim.easing}` : ""} x${anim.iterations ?? "∞"}${oscLabel}: ${visibility}, motion region ${bbox}, peak frame delta ${(anim.maxFrameRatio * 100).toFixed(2)}%`);
736
1323
  }
737
1324
  }
738
1325
  if (shown.length > 0) {
@@ -747,20 +1334,25 @@ function formatAnimationEvalReport(report, rules) {
747
1334
  } else if (note === void 0) {
748
1335
  lines.push("");
749
1336
  lines.push(`${GREEN}No animation issues detected.${RESET}`);
1337
+ lines.push(`${DIM}Only motion that runs from load is evaluated: a transition or animation started by a click, a :hover or a scroll is not — \`vlmkit inspect motion <page> --selector <el> --click/--hover/--leave/--scroll <css>\` samples it.${RESET}`);
750
1338
  }
751
1339
  if (note) {
752
1340
  lines.push("");
753
1341
  lines.push(`${DIM}${note}${RESET}`);
754
1342
  }
755
- if (report.framePaths && report.framePaths.length > 0) {
1343
+ if (report.frames) {
1344
+ const f = report.frames;
756
1345
  lines.push("");
757
- lines.push(`Frames: ${report.framePaths.length} written`);
1346
+ const at = f.instants.length <= 12 ? f.instants.map(formatInstant).join("/") : `${formatInstant(f.instants[0])}–${formatInstant(f.instants.at(-1))}`;
1347
+ lines.push(`Frames: ${f.count} written to ${f.dir} at ${at}ms of page time (clock and animations held${f.reducedMotion ? ", prefers-reduced-motion: reduce" : ""}), ${report.viewport.width}x${report.viewport.height} (--viewport WxH to match a target), manifest ${f.manifest}`);
1348
+ lines.push(`${DIM} What they show happening: vlmkit snapshot storyboard ${f.manifest}${RESET}`);
1349
+ if (f.unstable > 0) lines.push(`${YELLOW} ${f.unstable} frame(s) never captured the same twice: something moves that the clock does not hold (video, animated image, worker)${RESET}`);
758
1350
  }
759
1351
  if (report.strip) {
760
1352
  const s = report.strip;
761
1353
  lines.push("");
762
1354
  lines.push(`Strip: ${s.path} (${s.width}x${s.height}, ${s.rows} animation(s) x ${s.columns} sample(s)${s.omitted > 0 ? `; ${s.omitted} omitted as no-visible-effect` : ""}${s.outOfScope > 0 ? `; ${s.outOfScope} outside --strip-selector` : ""})`);
763
- lines.push(`${DIM} caption: columns are ${s.times.map((ms) => `${ms}ms`).join(" / ")} on the page timeline (window ${s.windowMs}ms, one shared clock); rows top to bottom are ${s.rowSelectors.join(", ")}${RESET}`);
1355
+ lines.push(`${DIM} caption: columns are ${s.times.map((ms) => `${formatInstant(ms)}ms`).join(" / ")} on the page timeline (window ${formatInstant(s.windowMs)}ms, one shared clock); rows top to bottom are ${s.rowSelectors.join(", ")}${RESET}`);
764
1356
  }
765
1357
  return lines.join("\n");
766
1358
  }
@@ -771,4 +1363,4 @@ function formatAnimationEvalReport(report, rules) {
771
1363
  * `--json`, `--advisory`, the run ledger and the exit code.
772
1364
  */
773
1365
  //#endregion
774
- export { clockSettledAt, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox };
1366
+ export { DELAYED_ENTRANCE_MS, clockMotionSource, clockSettledAt, clockUpdatesOnly, computeOscillation, computeSettleMs, deriveAnimationIssues, formatAnimationEvalReport, frameDelta, restTimeForAnimation, runAnimationEval, unionBbox };