@sloppy-ai/verify 1.1.0 → 1.4.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.
package/accessibility.mjs CHANGED
@@ -169,6 +169,16 @@ export function auditA11ySnapshot(snapshot, options = {}) {
169
169
  });
170
170
  }
171
171
 
172
+ const firstPaint = options.firstPaint;
173
+ if (firstPaint && firstPaint.withJsChars >= 200 && firstPaint.withoutJsChars < firstPaint.withJsChars * 0.5) {
174
+ push('motion.jsDependentFirstPaint', `Without JavaScript the page shows ${firstPaint.withoutJsChars} of ${firstPaint.withJsChars} characters; first paint must render the content, not wait for a script.`, { selector: 'document' }, {
175
+ severity: 'high',
176
+ confidence: 'medium',
177
+ objective: false,
178
+ kind: 'dom'
179
+ });
180
+ }
181
+
172
182
  if (options.reducedMotionIgnored) {
173
183
  push('a11y.reducedMotionIgnored', 'Infinite animation keeps running under prefers-reduced-motion: reduce.', { selector: 'document' }, {
174
184
  severity: 'low',
@@ -178,6 +188,24 @@ export function auditA11ySnapshot(snapshot, options = {}) {
178
188
  });
179
189
  }
180
190
 
191
+ for (const item of options.autoplayWithoutControl || []) {
192
+ push('motion.autoplayWithoutControl', `Automatically running motion has no visible pause control (${item.animationName || 'infinite animation'} on ${item.selector}).`, { selector: item.selector }, {
193
+ severity: 'high',
194
+ confidence: 'medium',
195
+ kind: 'computed-style',
196
+ criterion: 'WCAG 2.2.2 Pause, Stop, Hide'
197
+ });
198
+ }
199
+
200
+ for (const item of options.slowFeedback || []) {
201
+ push('motion.slowFeedback', `Interactive feedback takes ${Math.round(item.ms)}ms to transition (${item.selector}); keep hover, press, and focus responses inside roughly 300ms.`, { selector: item.selector }, {
202
+ severity: 'low',
203
+ confidence: 'medium',
204
+ objective: false,
205
+ kind: 'computed-style'
206
+ });
207
+ }
208
+
181
209
  return findings;
182
210
  }
183
211
 
@@ -194,7 +222,8 @@ export async function runAccessibilityAudit(target, options = {}) {
194
222
  };
195
223
  }
196
224
 
197
- const launchResult = await tryLaunch();
225
+ const ownsBrowser = !options.browser;
226
+ const launchResult = options.browser ? { browser: options.browser, reason: null } : await tryLaunch();
198
227
  if (!launchResult.browser) {
199
228
  return {
200
229
  target,
@@ -337,6 +366,88 @@ export async function runAccessibilityAudit(target, options = {}) {
337
366
  }
338
367
 
339
368
  const viewport = page.viewportSize();
369
+ let autoplayWithoutControl = [];
370
+ let slowFeedback = [];
371
+ if (options.checkMotionBudget !== false) {
372
+ try {
373
+ const motion = await page.evaluate(() => {
374
+ const label = (el) => {
375
+ const cls = [...(el.classList || [])].filter((value) => /^[A-Za-z0-9_-]+$/.test(value)).slice(0, 2);
376
+ return el.id ? `#${el.id}` : `${el.tagName.toLowerCase()}${cls.map((value) => `.${value}`).join('')}`;
377
+ };
378
+ const pauseControl = [...document.querySelectorAll('button, [role="button"], a')]
379
+ .some((el) => /pause|stop playback|stop animation/i.test(`${el.getAttribute('aria-label') || ''} ${el.getAttribute('title') || ''} ${el.textContent || ''}`));
380
+ const viewportArea = Math.max(1, window.innerWidth * window.innerHeight);
381
+ const autoplay = [];
382
+ for (const animation of document.getAnimations?.() || []) {
383
+ const timing = animation.effect?.getTiming?.();
384
+ if (!timing || timing.iterations !== Infinity || animation.playState !== 'running') continue;
385
+ if (pauseControl) continue;
386
+ const el = animation.effect?.target;
387
+ if (!el || el.nodeType !== 1) continue;
388
+ const rect = el.getBoundingClientRect();
389
+ const area = Math.max(0, rect.width) * Math.max(0, rect.height);
390
+ const name = `${animation.animationName || ''} ${el.className || ''} ${el.id || ''}`.toLowerCase();
391
+ const named = /marquee|ticker|carousel|autoplay|logo-scroll/.test(name);
392
+ if (!named && area < viewportArea * 0.25) continue;
393
+ autoplay.push({ selector: label(el), animationName: animation.animationName || 'infinite animation' });
394
+ if (autoplay.length >= 5) break;
395
+ }
396
+ const slow = [];
397
+ for (const el of document.querySelectorAll('a, button, input, select, textarea, summary, [role="button"]')) {
398
+ const style = getComputedStyle(el);
399
+ if (style.transitionProperty === 'none') continue;
400
+ const durations = style.transitionDuration.split(',').map((value) => {
401
+ const trimmed = value.trim();
402
+ const number = Number.parseFloat(trimmed);
403
+ if (!Number.isFinite(number)) return 0;
404
+ return /ms$/.test(trimmed) ? number : number * 1000;
405
+ });
406
+ const ms = Math.max(0, ...durations);
407
+ if (ms < 600) continue;
408
+ slow.push({ selector: label(el), ms });
409
+ if (slow.length >= 5) break;
410
+ }
411
+ return { autoplay, slow };
412
+ });
413
+ autoplayWithoutControl = motion.autoplay;
414
+ slowFeedback = motion.slow;
415
+ } catch {}
416
+ }
417
+
418
+ let firstPaint = null;
419
+ if (options.checkFirstPaint !== false) {
420
+ const visibleChars = () => {
421
+ const hidden = (el) => {
422
+ for (let node = el; node && node.nodeType === 1; node = node.parentElement) {
423
+ const style = getComputedStyle(node);
424
+ if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return true;
425
+ }
426
+ return false;
427
+ };
428
+ let total = 0;
429
+ for (const el of document.querySelectorAll('main, header, section, article, h1, h2, h3, p, li, blockquote, figcaption')) {
430
+ if (!hidden(el)) total += (el.innerText || '').trim().length;
431
+ }
432
+ return total;
433
+ };
434
+ const withJsChars = await page.evaluate(visibleChars);
435
+ let context;
436
+ let withoutJsChars = null;
437
+ try {
438
+ context = await browser.newContext({ javaScriptEnabled: false, viewport: viewport || { width: options.width || 1440, height: options.height || 900 } });
439
+ const staticPage = await context.newPage();
440
+ await staticPage.goto(target, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs || 8000 });
441
+ await staticPage.waitForTimeout(150);
442
+ withoutJsChars = await staticPage.evaluate(visibleChars);
443
+ } catch {
444
+ withoutJsChars = null;
445
+ } finally {
446
+ await context?.close().catch(() => {});
447
+ }
448
+ if (withoutJsChars !== null) firstPaint = { withJsChars, withoutJsChars };
449
+ }
450
+
340
451
  let reflowOverflow = null;
341
452
  let textResizeClipped = [];
342
453
  try {
@@ -388,6 +499,9 @@ export async function runAccessibilityAudit(target, options = {}) {
388
499
  reflowOverflow,
389
500
  textResizeClipped,
390
501
  reducedMotionIgnored,
502
+ firstPaint,
503
+ autoplayWithoutControl,
504
+ slowFeedback,
391
505
  viewport: { width: options.width || 1440, height: options.height || 900 }
392
506
  });
393
507
 
@@ -399,8 +513,8 @@ export async function runAccessibilityAudit(target, options = {}) {
399
513
  findings,
400
514
  summary: findings.length
401
515
  ? `Found ${findings.length} accessibility issue(s) in the rendered DOM.`
402
- : 'Rendered DOM passes the name, label, focus, target-size, reference, reflow, text-resize, and reduced-motion checks.',
403
- checked: ['accessible name', 'form labels', 'focus visibility', 'focus order', 'target size 24x24', 'aria references', 'reflow at 320px', '200% text resize', 'reduced motion']
516
+ : 'Rendered DOM passes the name, label, focus, target-size, reference, reflow, text-resize, reduced-motion, and motion-budget checks.',
517
+ checked: ['accessible name', 'form labels', 'focus visibility', 'focus order', 'target size 24x24', 'aria references', 'reflow at 320px', '200% text resize', 'reduced motion', 'first paint without JavaScript', 'autoplay pause control', 'interaction transition duration']
404
518
  };
405
519
  } catch (error) {
406
520
  const reason = String(error?.message || error).split('\n')[0];
@@ -415,6 +529,6 @@ export async function runAccessibilityAudit(target, options = {}) {
415
529
  };
416
530
  } finally {
417
531
  await page.close();
418
- await browser.close();
532
+ if (ownsBrowser) await browser.close();
419
533
  }
420
534
  }
@@ -0,0 +1,463 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Deterministic motion interaction audit.
4
+ *
5
+ * Source scanning can prove a rule exists; it cannot prove a transition lands,
6
+ * retargets, or leaves the layout at rest. This module runs declared interactions
7
+ * against a served page, samples frames and boxes, and reports only failures it
8
+ * observed. It never reports a pass when the browser or the spec is unavailable.
9
+ *
10
+ * Spec shape:
11
+ * {
12
+ * "interactions": [
13
+ * { "name": "menu", "trigger": "#open", "target": "#menu", "anchor": "header",
14
+ * "closeTrigger": "#close", "kind": "click", "waitMs": 600,
15
+ * "openKey": "Enter", "closeKey": "Escape",
16
+ * "precondition": [{ "click": "#tab-orders" }] }
17
+ * ]
18
+ * }
19
+ */
20
+
21
+ import { tryLaunch } from './browser.mjs';
22
+
23
+ const SETTLE_MS = 250;
24
+ const HANDOFF_TOLERANCE = 0.5;
25
+ const LONG_FRAME_MS = 32;
26
+ const BAD_FRAME_MS = 60;
27
+ const REDUCED_TRAVEL_TOLERANCE = 8;
28
+
29
+ const round = (value) => Math.round(value * 100) / 100;
30
+
31
+ function boxDelta(a, b) {
32
+ if (!a || !b) return null;
33
+ return Math.max(
34
+ Math.abs(a.x - b.x),
35
+ Math.abs(a.y - b.y),
36
+ Math.abs(a.width - b.width),
37
+ Math.abs(a.height - b.height)
38
+ );
39
+ }
40
+
41
+ export function auditMotionInteractionSamples(samples = [], options = {}) {
42
+ const findings = [];
43
+ const push = (rule, message, sample, extra = {}) => {
44
+ findings.push({
45
+ rule,
46
+ message,
47
+ severity: extra.severity || 'medium',
48
+ confidence: extra.confidence || 'medium',
49
+ objective: extra.objective !== false,
50
+ evidence: {
51
+ kind: 'interaction',
52
+ description: message,
53
+ selector: sample?.target || sample?.selector,
54
+ viewport: options.viewport,
55
+ criterion: extra.criterion
56
+ }
57
+ });
58
+ };
59
+
60
+ for (const sample of samples) {
61
+ if (!sample) continue;
62
+
63
+ const shift = boxDelta(sample.settled, sample.later);
64
+ if (shift !== null && shift > HANDOFF_TOLERANCE) {
65
+ push('motion.handoffShift', `${sample.name}: the element moves ${round(shift)}px after its transition has settled; motion must end on its resting box.`, sample, {
66
+ severity: 'medium',
67
+ confidence: 'high'
68
+ });
69
+ }
70
+
71
+ const anchorDrift = boxDelta(sample.before?.anchor, sample.after?.anchor);
72
+ if (anchorDrift !== null && anchorDrift > HANDOFF_TOLERANCE) {
73
+ push('motion.anchorDrift', `${sample.name}: the anchor moves ${round(anchorDrift)}px while the target changes; keep surrounding geometry steady.`, sample, {
74
+ severity: 'medium',
75
+ confidence: 'high'
76
+ });
77
+ }
78
+
79
+ const running = sample.runningAfterSettle || [];
80
+ if (running.length) {
81
+ const names = running.slice(0, 3).join(', ');
82
+ push('motion.stuckTransition', `${sample.name}: ${running.length} finite animation(s) still running after the settle window (${names}); the state change never comes to rest.`, sample, {
83
+ severity: 'medium',
84
+ confidence: 'high'
85
+ });
86
+ }
87
+
88
+ if (sample.openedByKeyboard && sample.after?.target && !sample.after.target.visible) {
89
+ push('motion.keyboardOpenIgnored', `${sample.name}: the trigger does not open the surface from the keyboard; mouse-only activation is not a path.`, sample, {
90
+ severity: 'high',
91
+ confidence: 'high',
92
+ criterion: 'WCAG 2.1.1 Keyboard'
93
+ });
94
+ }
95
+
96
+ if (sample.keyboardCloseChecked && sample.keyboardClosed === false) {
97
+ push('motion.keyboardCloseIgnored', `${sample.name}: the surface does not close when its key is pressed; every opened menu needs a keyboard exit.`, sample, {
98
+ severity: 'high',
99
+ confidence: 'high',
100
+ criterion: 'WCAG 2.1.1 Keyboard'
101
+ });
102
+ }
103
+
104
+ if (sample.interrupted && sample.interruptRecovered === false) {
105
+ push('motion.interruptNotRecovered', `${sample.name}: a reversed interaction is left in a half-open state after settling.`, sample, {
106
+ severity: 'high',
107
+ confidence: 'medium'
108
+ });
109
+ }
110
+
111
+ const reduced = sample.reduced;
112
+ if (reduced) {
113
+ // shortcut: travel is only measurable when the target is visible before and after;
114
+ // a hidden element's entrance is instead checked for the state change surviving.
115
+ if (reduced.visibleBefore && reduced.visibleAfter) {
116
+ const travel = Math.max(
117
+ Math.abs(reduced.after.x - reduced.before.x),
118
+ Math.abs(reduced.after.y - reduced.before.y)
119
+ );
120
+ if (travel > REDUCED_TRAVEL_TOLERANCE) {
121
+ push('motion.reducedMotionTravel', `${sample.name}: the target still travels ${round(travel)}px under prefers-reduced-motion: reduce; keep the state change, drop the movement.`, sample, {
122
+ severity: 'medium',
123
+ confidence: 'high',
124
+ criterion: 'WCAG 2.3.3'
125
+ });
126
+ }
127
+ }
128
+ if (sample.after?.target?.visible && reduced.after && !reduced.after.visible) {
129
+ push('motion.reducedMotionHidesContent', `${sample.name}: the result is missing under reduced motion; reduced motion may simplify a state change, never delete it.`, sample, {
130
+ severity: 'high',
131
+ confidence: 'high',
132
+ criterion: 'WCAG 2.3.3'
133
+ });
134
+ }
135
+ if (reduced.runningInfinite?.length) {
136
+ push('motion.reducedMotionKeepsLoop', `${sample.name}: ${reduced.runningInfinite.length} infinite animation(s) keep running under reduced motion (${reduced.runningInfinite.slice(0, 3).join(', ')}).`, sample, {
137
+ severity: 'medium',
138
+ confidence: 'high',
139
+ criterion: 'WCAG 2.3.3'
140
+ });
141
+ }
142
+ }
143
+
144
+ if (typeof sample.layoutShift === 'number' && sample.layoutShift > 0.005) {
145
+ push('motion.layoutShift', `${sample.name}: layout moved during the interaction (shift score ${round(sample.layoutShift)}); reserve space or animate a transform so neighbors stay put.`, sample, {
146
+ severity: 'medium',
147
+ confidence: 'medium',
148
+ objective: false
149
+ });
150
+ }
151
+
152
+ if (sample.missingSelector) {
153
+ push('motion.missingSelector', `${sample.name}: selector "${sample.missingSelector}" was not found, so the declared interaction never ran.`, sample, {
154
+ severity: 'high',
155
+ confidence: 'high'
156
+ });
157
+ }
158
+
159
+ if (sample.focusChecked && sample.focusReturned === false) {
160
+ push('motion.focusLoss', `${sample.name}: closing the surface does not return focus to its trigger; keyboard users are left without a position.`, sample, {
161
+ severity: 'high',
162
+ confidence: 'medium',
163
+ criterion: 'WCAG 2.4.3 Focus Order'
164
+ });
165
+ }
166
+
167
+ const frames = Array.isArray(sample.frames) ? sample.frames : [];
168
+ if (frames.length >= 5) {
169
+ const long = frames.filter((ms) => ms > LONG_FRAME_MS).length;
170
+ const ratio = long / frames.length;
171
+ const worst = Math.max(...frames);
172
+ if (ratio >= 0.25 || worst > BAD_FRAME_MS) {
173
+ push('motion.frameBudget', `${sample.name}: ${Math.round(ratio * 100)}% of sampled frames exceeded ${LONG_FRAME_MS}ms (worst ${Math.round(worst)}ms); the interaction drops frames on this machine.`, sample, {
174
+ severity: 'medium',
175
+ confidence: 'low',
176
+ objective: false
177
+ });
178
+ }
179
+ }
180
+ }
181
+
182
+ return findings;
183
+ }
184
+
185
+ export function stabilizeMotionRuns(results = []) {
186
+ const runs = results.length;
187
+ const byKey = new Map();
188
+ for (const result of results) {
189
+ for (const finding of result.findings || []) {
190
+ const key = `${finding.rule}|${finding.evidence?.selector || ''}`;
191
+ const entry = byKey.get(key) || { finding, count: 0 };
192
+ entry.count += 1;
193
+ byKey.set(key, entry);
194
+ }
195
+ }
196
+ const stable = [];
197
+ const unstable = [];
198
+ for (const entry of byKey.values()) {
199
+ if (entry.count === runs) stable.push(entry.finding);
200
+ else unstable.push({ ...entry.finding, seenIn: entry.count });
201
+ }
202
+ return { runs, stable, unstable };
203
+ }
204
+
205
+ function unavailableReason(target, spec) {
206
+ if (!/^https?:\/\//i.test(String(target))) return 'Motion interaction evidence needs a served http(s) URL.';
207
+ if (!spec || !Array.isArray(spec.interactions) || spec.interactions.length === 0) return 'No interactions were declared in the motion spec.';
208
+ for (const interaction of spec.interactions) {
209
+ if (!interaction?.trigger || !interaction?.target) return 'Every interaction needs a trigger and a target selector.';
210
+ if (interaction.openKey !== undefined && typeof interaction.openKey !== 'string') return 'openKey must be a key name such as "Enter".';
211
+ if (interaction.closeKey !== undefined && typeof interaction.closeKey !== 'string') return 'closeKey must be a key name such as "Escape".';
212
+ if (interaction.precondition !== undefined) {
213
+ if (!Array.isArray(interaction.precondition)) return 'precondition must be an array of click, hover, or press steps.';
214
+ for (const step of interaction.precondition) {
215
+ if (!step || (!step.click && !step.hover && !step.press)) return 'Every precondition step needs a click, hover, or press selector.';
216
+ }
217
+ }
218
+ }
219
+ return null;
220
+ }
221
+
222
+ async function applyPrecondition(page, steps = []) {
223
+ for (const step of steps) {
224
+ if (step.click) await page.click(step.click);
225
+ else if (step.hover) await page.hover(step.hover);
226
+ else await page.keyboard.press(step.press);
227
+ }
228
+ }
229
+
230
+ async function openInteraction(page, interaction) {
231
+ if (interaction.openKey) {
232
+ await page.focus(interaction.trigger);
233
+ await page.keyboard.press(interaction.openKey);
234
+ } else if (interaction.kind === 'hover') {
235
+ await page.hover(interaction.trigger);
236
+ } else {
237
+ await page.click(interaction.trigger);
238
+ }
239
+ }
240
+
241
+ export async function runMotionInteractionAudit(target, options = {}) {
242
+ const spec = options.spec;
243
+ const reason = unavailableReason(target, spec);
244
+ if (reason) {
245
+ return { target, ok: false, mode: 'unavailable', findings: [], checked: [], summary: reason, unavailable: reason };
246
+ }
247
+
248
+ const ownsBrowser = !options.browser;
249
+ const launch = options.browser ? { browser: options.browser } : await tryLaunch();
250
+ if (!launch.browser) {
251
+ return {
252
+ target,
253
+ ok: false,
254
+ mode: 'unavailable',
255
+ findings: [],
256
+ checked: spec.interactions.map((interaction) => interaction.name || interaction.trigger),
257
+ summary: 'Motion interaction evidence requires a browser.',
258
+ unavailable: launch.reason || 'No browser available.'
259
+ };
260
+ }
261
+
262
+ const browser = launch.browser;
263
+ const viewport = { width: options.width || 1280, height: options.height || 800 };
264
+ const page = await browser.newPage({ viewport });
265
+ await page.addInitScript(() => {
266
+ window.__sloppyBoxOf = (selector) => {
267
+ if (!selector) return null;
268
+ const el = document.querySelector(selector);
269
+ if (!el) return null;
270
+ const rect = el.getBoundingClientRect();
271
+ const style = getComputedStyle(el);
272
+ const opacity = Number.parseFloat(style.opacity || '1');
273
+ return {
274
+ x: rect.x,
275
+ y: rect.y,
276
+ width: rect.width,
277
+ height: rect.height,
278
+ visible: style.display !== 'none' && style.visibility !== 'hidden' && opacity > 0.05
279
+ };
280
+ };
281
+ window.__sloppyInfiniteAnimations = () => (document.getAnimations?.() || [])
282
+ .filter((animation) => {
283
+ if (animation.playState !== 'running') return false;
284
+ return animation.effect?.getTiming?.()?.iterations === Infinity;
285
+ })
286
+ .map((animation) => animation.animationName || animation.transitionProperty || 'animation');
287
+ window.__sloppyLayoutShifts = [];
288
+ try {
289
+ new PerformanceObserver((list) => {
290
+ for (const entry of list.getEntries()) {
291
+ window.__sloppyLayoutShifts.push(entry.value);
292
+ }
293
+ }).observe({ type: 'layout-shift', buffered: true });
294
+ } catch {}
295
+ });
296
+ const samples = [];
297
+ try {
298
+ for (const interaction of spec.interactions) {
299
+ const waitMs = Number.isFinite(interaction.waitMs) ? interaction.waitMs : 600;
300
+ await page.goto(target, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs || 12000 });
301
+ await page.waitForTimeout(200);
302
+ await applyPrecondition(page, interaction.precondition);
303
+
304
+ const sample = {
305
+ name: interaction.name || interaction.trigger,
306
+ target: interaction.target,
307
+ selector: interaction.target,
308
+ openedByKeyboard: Boolean(interaction.openKey),
309
+ interrupted: Boolean(interaction.closeTrigger)
310
+ };
311
+
312
+ const boxes = await page.evaluate(({ trigger, targetSelector, anchorSelector }) => ({
313
+ target: window.__sloppyBoxOf(targetSelector),
314
+ anchor: window.__sloppyBoxOf(anchorSelector),
315
+ trigger: window.__sloppyBoxOf(trigger),
316
+ targetFound: Boolean(document.querySelector(targetSelector)),
317
+ triggerFound: Boolean(document.querySelector(trigger))
318
+ }), { trigger: interaction.trigger, targetSelector: interaction.target, anchorSelector: interaction.anchor });
319
+
320
+ if (!boxes.targetFound || !boxes.triggerFound) {
321
+ sample.missingSelector = !boxes.triggerFound ? interaction.trigger : interaction.target;
322
+ sample.before = { anchor: boxes.anchor };
323
+ samples.push(sample);
324
+ continue;
325
+ }
326
+
327
+ sample.before = { target: boxes.target, anchor: boxes.anchor };
328
+ await page.evaluate(() => {
329
+ window.__sloppyMotionFrames = [];
330
+ window.__sloppyLayoutShifts = [];
331
+ window.__sloppyMotionSampling = true;
332
+ let last = performance.now();
333
+ const tick = (now) => {
334
+ window.__sloppyMotionFrames.push(now - last);
335
+ last = now;
336
+ if (window.__sloppyMotionSampling) requestAnimationFrame(tick);
337
+ };
338
+ requestAnimationFrame(tick);
339
+ });
340
+
341
+ await openInteraction(page, interaction);
342
+
343
+ await page.waitForTimeout(waitMs);
344
+
345
+ const after = await page.evaluate(({ targetSelector, anchorSelector }) => {
346
+ const running = (document.getAnimations?.() || [])
347
+ .filter((animation) => {
348
+ if (animation.playState !== 'running') return false;
349
+ const timing = animation.effect?.getTiming?.();
350
+ return timing && timing.iterations !== Infinity;
351
+ })
352
+ .map((animation) => animation.animationName || animation.transitionProperty || 'animation');
353
+ return {
354
+ target: window.__sloppyBoxOf(targetSelector),
355
+ anchor: window.__sloppyBoxOf(anchorSelector),
356
+ running
357
+ };
358
+ }, { targetSelector: interaction.target, anchorSelector: interaction.anchor });
359
+
360
+ sample.after = { target: after.target, anchor: after.anchor };
361
+ sample.settled = after.target;
362
+ sample.runningAfterSettle = after.running;
363
+
364
+ const frames = await page.evaluate(() => {
365
+ window.__sloppyMotionSampling = false;
366
+ return (window.__sloppyMotionFrames || []).slice(1);
367
+ });
368
+ sample.frames = frames;
369
+
370
+ await page.waitForTimeout(SETTLE_MS);
371
+ const settled = await page.evaluate((targetSelector) => ({
372
+ box: window.__sloppyBoxOf(targetSelector),
373
+ layoutShift: (window.__sloppyLayoutShifts || []).reduce((total, value) => total + value, 0)
374
+ }), interaction.target);
375
+ sample.later = settled.box;
376
+ sample.layoutShift = settled.layoutShift;
377
+
378
+ if (interaction.closeKey) {
379
+ await page.keyboard.press(interaction.closeKey);
380
+ await page.waitForTimeout(waitMs);
381
+ sample.keyboardCloseChecked = true;
382
+ sample.keyboardClosed = await page.evaluate((targetSelector) => {
383
+ const el = document.querySelector(targetSelector);
384
+ if (!el) return true;
385
+ const style = getComputedStyle(el);
386
+ return style.display === 'none' || style.visibility === 'hidden' || Number.parseFloat(style.opacity || '1') <= 0.05;
387
+ }, interaction.target);
388
+ }
389
+
390
+ await page.emulateMedia({ reducedMotion: 'reduce' });
391
+ await page.goto(target, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs || 12000 });
392
+ await page.waitForTimeout(200);
393
+ await applyPrecondition(page, interaction.precondition);
394
+ const reducedBefore = await page.evaluate(({ targetSelector }) => ({
395
+ target: window.__sloppyBoxOf(targetSelector),
396
+ found: Boolean(document.querySelector(targetSelector))
397
+ }), { targetSelector: interaction.target });
398
+ if (reducedBefore.found) {
399
+ await openInteraction(page, interaction);
400
+ await page.waitForTimeout(waitMs);
401
+ const reducedAfter = await page.evaluate(({ targetSelector }) => ({
402
+ target: window.__sloppyBoxOf(targetSelector),
403
+ runningInfinite: window.__sloppyInfiniteAnimations()
404
+ }), { targetSelector: interaction.target });
405
+ sample.reduced = {
406
+ before: reducedBefore.target,
407
+ after: reducedAfter.target,
408
+ visibleBefore: Boolean(reducedBefore.target?.visible),
409
+ visibleAfter: Boolean(reducedAfter.target?.visible),
410
+ runningInfinite: reducedAfter.runningInfinite
411
+ };
412
+ }
413
+ await page.emulateMedia({ reducedMotion: 'no-preference' });
414
+
415
+ if (interaction.closeTrigger) {
416
+ await page.goto(target, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs || 12000 });
417
+ await page.waitForTimeout(150);
418
+ await applyPrecondition(page, interaction.precondition);
419
+ await openInteraction(page, interaction);
420
+ await page.waitForTimeout(80);
421
+ await page.click(interaction.closeTrigger);
422
+ await page.waitForTimeout(waitMs);
423
+ sample.focusChecked = true;
424
+ sample.focusReturned = await page.evaluate(({ targetSelector, triggerSelector }) => {
425
+ const trigger = document.querySelector(triggerSelector);
426
+ const active = document.activeElement;
427
+ if (!trigger || !active) return false;
428
+ return active === trigger || trigger.contains(active);
429
+ }, { targetSelector: interaction.target, triggerSelector: interaction.trigger });
430
+ sample.interruptRecovered = await page.evaluate((targetSelector) => {
431
+ const el = document.querySelector(targetSelector);
432
+ if (!el) return true;
433
+ const running = (document.getAnimations?.() || []).some((animation) => {
434
+ if (animation.playState !== 'running') return false;
435
+ const timing = animation.effect?.getTiming?.();
436
+ return timing && timing.iterations !== Infinity;
437
+ });
438
+ const style = getComputedStyle(el);
439
+ const closed = style.display === 'none' || style.visibility === 'hidden' || Number.parseFloat(style.opacity || '1') <= 0.05;
440
+ const open = Number.parseFloat(style.opacity || '1') >= 0.99;
441
+ return !running && (closed || open);
442
+ }, interaction.target);
443
+ }
444
+
445
+ samples.push(sample);
446
+ }
447
+ } finally {
448
+ await page.close().catch(() => {});
449
+ if (ownsBrowser) await browser.close().catch(() => {});
450
+ }
451
+
452
+ const findings = auditMotionInteractionSamples(samples, { viewport });
453
+ return {
454
+ target,
455
+ ok: findings.length === 0,
456
+ mode: 'browser',
457
+ findings,
458
+ checked: spec.interactions.map((interaction) => interaction.name || interaction.trigger),
459
+ summary: findings.length
460
+ ? `Found ${findings.length} motion interaction issue(s) across ${spec.interactions.length} declared interaction(s).`
461
+ : `${spec.interactions.length} declared interaction(s) settled, held their anchors, and came to rest.`
462
+ };
463
+ }