@a11y-pulse/moving-content-audit 0.0.0-stage → 0.2.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/dist/index.js ADDED
@@ -0,0 +1,1076 @@
1
+ // src/audit.ts
2
+ import {
3
+ captureElementScreenshot,
4
+ releaseStashedElements,
5
+ stashedElementHandle,
6
+ stashedElementSelectors
7
+ } from "@a11y-pulse/browser-adaptor";
8
+ import { truncateHtml } from "@a11y-pulse/browser-adaptor/dom";
9
+
10
+ // src/browser-scripts.ts
11
+ function startObservationScript(stateKey, pollMs, durationLimitMs, trackLimit, quietGapMs) {
12
+ const TIMES_LIMIT = 400;
13
+ const SVG_ATTRIBUTES = [
14
+ "transform",
15
+ "d",
16
+ "points",
17
+ "x",
18
+ "y",
19
+ "x1",
20
+ "y1",
21
+ "x2",
22
+ "y2",
23
+ "cx",
24
+ "cy",
25
+ "r",
26
+ "rx",
27
+ "ry",
28
+ "width",
29
+ "height",
30
+ "viewBox"
31
+ ];
32
+ const ENTRANCE_GAPS = 2;
33
+ const EVICT_GAPS = 3;
34
+ const store = window;
35
+ store[stateKey]?.stop();
36
+ const start = performance.now();
37
+ const tracked = /* @__PURE__ */ new Map();
38
+ const starts = /* @__PURE__ */ new Map();
39
+ const shownOnce = /* @__PURE__ */ new WeakSet();
40
+ const added = /* @__PURE__ */ new WeakMap();
41
+ const seenAnimations = /* @__PURE__ */ new WeakSet();
42
+ const videos = /* @__PURE__ */ new Map();
43
+ const signatureOf = (el) => {
44
+ const rect = el.getBoundingClientRect();
45
+ const style = getComputedStyle(el);
46
+ return [
47
+ Math.round(rect.left + window.scrollX),
48
+ Math.round(rect.top + window.scrollY),
49
+ Math.round(rect.width),
50
+ Math.round(rect.height),
51
+ Math.round(Number.parseFloat(style.opacity) * 20),
52
+ style.visibility,
53
+ style.transform,
54
+ Math.round(el.scrollLeft),
55
+ Math.round(el.scrollTop),
56
+ style.backgroundPosition,
57
+ style.backgroundImage.slice(0, 120),
58
+ el.currentSrc ?? "",
59
+ // A rotation about its own centre leaves a shape's box where it was.
60
+ el instanceof SVGElement ? el.getAttribute("transform") ?? "" : ""
61
+ ].join("|");
62
+ };
63
+ const isFixed = (el) => {
64
+ for (let node = el; node; node = node.parentElement) {
65
+ if (getComputedStyle(node).position === "fixed") {
66
+ return true;
67
+ }
68
+ }
69
+ return false;
70
+ };
71
+ const isShown = (el, fixed) => {
72
+ if (!el.isConnected) {
73
+ return false;
74
+ }
75
+ if (typeof el.checkVisibility === "function") {
76
+ if (!el.checkVisibility({
77
+ opacityProperty: true,
78
+ visibilityProperty: true,
79
+ contentVisibilityAuto: true
80
+ })) {
81
+ return false;
82
+ }
83
+ } else {
84
+ const style = getComputedStyle(el);
85
+ if (style.visibility !== "visible" || Number.parseFloat(style.opacity) === 0) {
86
+ return false;
87
+ }
88
+ }
89
+ const rect = el.getBoundingClientRect();
90
+ if (rect.width <= 0 || rect.height <= 0) {
91
+ return false;
92
+ }
93
+ if (fixed) {
94
+ return rect.right > 0 && rect.bottom > 0 && rect.left < window.innerWidth && rect.top < window.innerHeight;
95
+ }
96
+ const root = document.documentElement;
97
+ return rect.right + window.scrollX > 0 && rect.bottom + window.scrollY > 0 && rect.left + window.scrollX < Math.max(root.scrollWidth, root.clientWidth) && rect.top + window.scrollY < Math.max(root.scrollHeight, root.clientHeight);
98
+ };
99
+ const addedAt = (el) => {
100
+ for (let node = el; node; node = node.parentElement) {
101
+ const time = added.get(node);
102
+ if (time !== void 0) {
103
+ return time;
104
+ }
105
+ }
106
+ return null;
107
+ };
108
+ const makeRoom = (now) => {
109
+ let settled = null;
110
+ for (const [el, record] of tracked) {
111
+ const idle = now - record.lastActivity;
112
+ if (!el.isConnected || record.times.length === 0 && idle > quietGapMs) {
113
+ tracked.delete(el);
114
+ return true;
115
+ }
116
+ if (settled === null && idle > quietGapMs * EVICT_GAPS) {
117
+ settled = el;
118
+ }
119
+ }
120
+ return settled !== null && tracked.delete(settled);
121
+ };
122
+ const track = (el, how) => {
123
+ if (tracked.has(el) || el === document.documentElement || el === document.body) {
124
+ return;
125
+ }
126
+ const now = performance.now() - start;
127
+ if (tracked.size >= trackLimit && !makeRoom(now)) {
128
+ return;
129
+ }
130
+ const fixed = isFixed(el);
131
+ const shown = isShown(el, fixed);
132
+ const inserted = addedAt(el);
133
+ const entering = !shown || inserted !== null && now - inserted <= quietGapMs;
134
+ if (shown) {
135
+ shownOnce.add(el);
136
+ }
137
+ tracked.set(el, {
138
+ signature: signatureOf(el),
139
+ // Touching an element that is showing is the first sign of a change to it. Gaining
140
+ // children is content arriving, which is not.
141
+ initial: how === "changed" && !entering ? now : null,
142
+ times: [],
143
+ appearedAt: inserted ?? (how === "filled" ? now : null),
144
+ entering,
145
+ lastActivity: now,
146
+ wasShown: shown,
147
+ fixed
148
+ });
149
+ };
150
+ const observer = new MutationObserver((records) => {
151
+ const now = performance.now() - start;
152
+ for (const record of records) {
153
+ const target = record.target instanceof Element ? record.target : record.target.parentElement;
154
+ if (!target) {
155
+ continue;
156
+ }
157
+ if (record.type !== "childList") {
158
+ track(target, "changed");
159
+ continue;
160
+ }
161
+ const addedElements = [...record.addedNodes].filter((node) => node instanceof Element);
162
+ const removedElements = [...record.removedNodes].filter((node) => node instanceof Element);
163
+ for (const el of addedElements) {
164
+ added.set(el, now);
165
+ }
166
+ if (addedElements.length === 0 && removedElements.length === 0) {
167
+ continue;
168
+ }
169
+ const filled = removedElements.length === 0 && [...target.children].every((child) => added.has(child));
170
+ track(target, filled ? "filled" : "children");
171
+ }
172
+ });
173
+ const observe = (root) => {
174
+ observer.observe(root, {
175
+ subtree: true,
176
+ childList: true,
177
+ attributes: true,
178
+ attributeFilter: [
179
+ "style",
180
+ "class",
181
+ "hidden",
182
+ "src",
183
+ "srcset",
184
+ "aria-hidden",
185
+ "open",
186
+ ...SVG_ATTRIBUTES
187
+ ]
188
+ });
189
+ };
190
+ observe(document);
191
+ for (const el of document.querySelectorAll("*")) {
192
+ if (el.shadowRoot) {
193
+ observe(el.shadowRoot);
194
+ }
195
+ }
196
+ const onScroll = (event) => {
197
+ if (event.target instanceof Element) {
198
+ track(event.target, "changed");
199
+ }
200
+ };
201
+ document.addEventListener("scroll", onScroll, { capture: true, passive: true });
202
+ for (const video of document.querySelectorAll("video")) {
203
+ videos.set(video, { time: video.currentTime, playing: !video.paused && !video.ended });
204
+ }
205
+ const poll = () => {
206
+ const now = performance.now() - start;
207
+ for (const [el, record] of tracked) {
208
+ if (!el.isConnected) {
209
+ continue;
210
+ }
211
+ const signature = signatureOf(el);
212
+ const shown = isShown(el, record.fixed);
213
+ if (shown) {
214
+ shownOnce.add(el);
215
+ }
216
+ if (signature !== record.signature) {
217
+ record.signature = signature;
218
+ if (record.entering) {
219
+ if (shown && record.appearedAt === null) {
220
+ record.appearedAt = now;
221
+ }
222
+ } else if ((shown || record.wasShown) && record.times.length < TIMES_LIMIT) {
223
+ record.times.push(now);
224
+ }
225
+ record.lastActivity = now;
226
+ }
227
+ if (record.entering && shown) {
228
+ record.appearedAt ??= now;
229
+ if (now - record.lastActivity > quietGapMs || now - record.appearedAt > quietGapMs * ENTRANCE_GAPS) {
230
+ record.entering = false;
231
+ }
232
+ }
233
+ record.wasShown = shown;
234
+ }
235
+ for (const el of starts.keys()) {
236
+ if (isShown(el, false)) {
237
+ shownOnce.add(el);
238
+ }
239
+ }
240
+ const animations = typeof document.getAnimations === "function" ? document.getAnimations() : [];
241
+ for (const animation of animations) {
242
+ const effect = animation.effect;
243
+ const target = effect instanceof KeyframeEffect ? effect.target : null;
244
+ if (!target || animation.playState !== "running" || seenAnimations.has(animation)) {
245
+ continue;
246
+ }
247
+ if (Number(effect?.getComputedTiming().activeDuration) > durationLimitMs) {
248
+ continue;
249
+ }
250
+ seenAnimations.add(animation);
251
+ const times = starts.get(target) ?? [];
252
+ if (times.length < TIMES_LIMIT) {
253
+ times.push(now);
254
+ }
255
+ starts.set(target, times);
256
+ }
257
+ };
258
+ const timer = setInterval(poll, pollMs);
259
+ const stop = () => {
260
+ clearInterval(timer);
261
+ observer.disconnect();
262
+ document.removeEventListener("scroll", onScroll, { capture: true });
263
+ delete store[stateKey];
264
+ };
265
+ store[stateKey] = { start, tracked, starts, shownOnce, videos, poll, stop };
266
+ poll();
267
+ }
268
+ function stopObservationScript(stateKey) {
269
+ window[stateKey]?.stop();
270
+ }
271
+ function collectRegionsScript(stateKey, stashKey, options) {
272
+ const ESSENTIAL_ROLES = /* @__PURE__ */ new Set(["progressbar", "status", "alert", "timer", "log"]);
273
+ const CONTROL_SELECTOR = 'button, [role="button"], [role="switch"], input[type="button"], input[type="submit"], input[type="checkbox"], summary';
274
+ const PAGE_CONTROL_SELECTOR = `${CONTROL_SELECTOR}, a[href]`;
275
+ const SHOWS_AND_HIDES = /^(opacity|visibility)$/i;
276
+ const KEYFRAME_FIELDS = /* @__PURE__ */ new Set(["offset", "computedOffset", "easing", "composite"]);
277
+ const NAME_LIMIT = 40;
278
+ const RULE_LIMIT = 2e4;
279
+ const PAGE_CONTROL_LIMIT = 2e3;
280
+ const ANIMATION_LIMIT = 5;
281
+ const TIMES_LIMIT = 400;
282
+ const CONTROL_ANCESTORS = 3;
283
+ const CONTROL_SCOPE_GROWTH = 6;
284
+ const store = window;
285
+ const state = store[stateKey];
286
+ state?.poll();
287
+ state?.stop();
288
+ const elapsedMs = state ? performance.now() - state.start : 0;
289
+ const controlName = new RegExp(options.controlNamePattern, "iu");
290
+ const controlAttribute = new RegExp(options.controlAttributePattern, "i");
291
+ const pageControl = new RegExp(options.pageControlPattern, "i");
292
+ const essentialHint = new RegExp(options.essentialPattern, "i");
293
+ const isRoot = (el) => !el || el === document.body || el === document.documentElement;
294
+ const isRendered = (el) => {
295
+ if (!el.isConnected) {
296
+ return false;
297
+ }
298
+ if (typeof el.checkVisibility === "function" && !el.checkVisibility()) {
299
+ return false;
300
+ }
301
+ const rect = el.getBoundingClientRect();
302
+ return rect.width > 0 && rect.height > 0;
303
+ };
304
+ const isVisible = (el) => {
305
+ if (!isRendered(el)) {
306
+ return false;
307
+ }
308
+ if (typeof el.checkVisibility === "function") {
309
+ return el.checkVisibility({
310
+ opacityProperty: true,
311
+ visibilityProperty: true,
312
+ contentVisibilityAuto: true
313
+ });
314
+ }
315
+ for (let node = el; node; node = node.parentElement) {
316
+ const style = getComputedStyle(node);
317
+ if (Number.parseFloat(style.opacity) === 0 || node === el && style.visibility !== "visible") {
318
+ return false;
319
+ }
320
+ }
321
+ return true;
322
+ };
323
+ const wasVisible = (candidate, el) => isVisible(el) || state?.shownOnce.has(candidate.el) === true || isRendered(el) && (isRoot(el.parentElement) || isVisible(el.parentElement)) && candidate.animations.some(
324
+ (animation) => animation.pseudoElement === null && animation.properties.some((property) => SHOWS_AND_HIDES.test(property))
325
+ );
326
+ const boxOf = (el) => {
327
+ const rect = el.getBoundingClientRect();
328
+ return {
329
+ left: rect.left + window.scrollX,
330
+ top: rect.top + window.scrollY,
331
+ right: rect.right + window.scrollX,
332
+ bottom: rect.bottom + window.scrollY
333
+ };
334
+ };
335
+ const areaOf = (box) => Math.max(0, box.right - box.left) * Math.max(0, box.bottom - box.top);
336
+ const intersect = (a, b) => ({
337
+ left: Math.max(a.left, b.left),
338
+ top: Math.max(a.top, b.top),
339
+ right: Math.min(a.right, b.right),
340
+ bottom: Math.min(a.bottom, b.bottom)
341
+ });
342
+ const clips = (el) => {
343
+ const style = getComputedStyle(el);
344
+ return style.overflowX !== "visible" || style.overflowY !== "visible";
345
+ };
346
+ const visibleBox = (el) => {
347
+ const root = document.documentElement;
348
+ let box = intersect(boxOf(el), {
349
+ left: 0,
350
+ top: 0,
351
+ right: Math.max(root.scrollWidth, root.clientWidth),
352
+ bottom: Math.max(root.scrollHeight, root.clientHeight)
353
+ });
354
+ for (let node = el; !isRoot(node); node = node.parentElement) {
355
+ if (node !== el && clips(node)) {
356
+ box = intersect(box, boxOf(node));
357
+ }
358
+ if (getComputedStyle(node).position === "fixed") {
359
+ box = intersect(box, {
360
+ left: window.scrollX,
361
+ top: window.scrollY,
362
+ right: window.scrollX + window.innerWidth,
363
+ bottom: window.scrollY + window.innerHeight
364
+ });
365
+ }
366
+ }
367
+ return box;
368
+ };
369
+ const regionElementFor = (el) => {
370
+ for (let parent = el.parentElement; !isRoot(parent); parent = parent.parentElement) {
371
+ if (clips(parent)) {
372
+ return areaOf(boxOf(parent)) < areaOf(boxOf(el)) - 1 ? parent : el;
373
+ }
374
+ }
375
+ return el;
376
+ };
377
+ const isEssential = (el) => {
378
+ let depth = 0;
379
+ for (let node = el; !isRoot(node); node = node.parentElement, depth++) {
380
+ const current = node;
381
+ if (ESSENTIAL_ROLES.has(current.getAttribute("role") ?? "") || current.getAttribute("aria-busy") === "true" || current.tagName === "PROGRESS" || current.tagName === "METER") {
382
+ return true;
383
+ }
384
+ if (depth < 3 && essentialHint.test(`${current.getAttribute("class") ?? ""} ${current.id}`)) {
385
+ return true;
386
+ }
387
+ }
388
+ return false;
389
+ };
390
+ const shallowHtml = (el) => el.cloneNode(false).outerHTML;
391
+ const candidates = /* @__PURE__ */ new Map();
392
+ const candidateFor = (el) => {
393
+ let candidate = candidates.get(el);
394
+ if (!candidate) {
395
+ candidate = {
396
+ el,
397
+ targets: [],
398
+ times: [],
399
+ observed: 0,
400
+ appeared: 0,
401
+ animations: [],
402
+ marquee: null,
403
+ video: null
404
+ };
405
+ candidates.set(el, candidate);
406
+ }
407
+ return candidate;
408
+ };
409
+ if (state) {
410
+ for (const [el, record] of state.tracked) {
411
+ if (record.times.length >= 1) {
412
+ const candidate = candidateFor(el);
413
+ candidate.targets.push(el);
414
+ candidate.times.push(...record.initial === null ? [] : [record.initial], ...record.times);
415
+ candidate.observed++;
416
+ candidate.appeared += record.appearedAt === null ? 0 : 1;
417
+ }
418
+ }
419
+ for (const [el, times] of state.starts) {
420
+ if (times.length >= 2) {
421
+ const candidate = candidateFor(el);
422
+ candidate.targets.push(el);
423
+ candidate.times.push(...times);
424
+ candidate.observed++;
425
+ }
426
+ }
427
+ }
428
+ const pseudoAreaOf = (el, pseudo) => {
429
+ const style = getComputedStyle(el, pseudo);
430
+ const width = Number.parseFloat(style.width);
431
+ const height = Number.parseFloat(style.height);
432
+ return Number.isFinite(width) && Number.isFinite(height) ? width * height : null;
433
+ };
434
+ const smallPseudoHosts = /* @__PURE__ */ new Set();
435
+ const running = typeof document.getAnimations === "function" ? document.getAnimations() : [];
436
+ for (const animation of running) {
437
+ const effect = animation.effect;
438
+ if (!(effect instanceof KeyframeEffect) || !effect.target) {
439
+ continue;
440
+ }
441
+ if (animation.playState !== "running") {
442
+ continue;
443
+ }
444
+ const activeDuration = Number(effect.getComputedTiming().activeDuration);
445
+ if (!(activeDuration > options.durationLimitMs)) {
446
+ continue;
447
+ }
448
+ let properties = [];
449
+ let readable = true;
450
+ try {
451
+ const keyframes = effect.getKeyframes();
452
+ const values = /* @__PURE__ */ new Map();
453
+ const counts = /* @__PURE__ */ new Map();
454
+ for (const keyframe of keyframes) {
455
+ for (const [property, value] of Object.entries(keyframe)) {
456
+ if (KEYFRAME_FIELDS.has(property)) {
457
+ continue;
458
+ }
459
+ values.set(property, (values.get(property) ?? /* @__PURE__ */ new Set()).add(String(value)));
460
+ counts.set(property, (counts.get(property) ?? 0) + 1);
461
+ }
462
+ }
463
+ properties = [...values.keys()].filter(
464
+ (property) => values.get(property).size > 1 || (counts.get(property) ?? 0) < keyframes.length
465
+ );
466
+ } catch {
467
+ readable = false;
468
+ }
469
+ if (readable && properties.length === 0) {
470
+ continue;
471
+ }
472
+ const pseudoElement = effect.pseudoElement ?? null;
473
+ const pseudoArea = pseudoElement === null ? null : pseudoAreaOf(effect.target, pseudoElement);
474
+ if (pseudoArea !== null && pseudoArea < options.minRegionArea) {
475
+ smallPseudoHosts.add(effect.target);
476
+ continue;
477
+ }
478
+ const css = "animationName" in animation;
479
+ const candidate = candidateFor(effect.target);
480
+ candidate.targets.push(effect.target);
481
+ if (candidate.animations.length < ANIMATION_LIMIT) {
482
+ candidate.animations.push({
483
+ name: css ? String(animation.animationName) : animation.id !== "" ? animation.id : null,
484
+ css,
485
+ infinite: !Number.isFinite(activeDuration),
486
+ activeDurationMs: Number.isFinite(activeDuration) ? Math.round(activeDuration) : null,
487
+ properties,
488
+ pseudoElement,
489
+ pseudoArea
490
+ });
491
+ }
492
+ }
493
+ for (const marquee of document.querySelectorAll("marquee")) {
494
+ if (marquee.getAttribute("scrollamount") === "0") {
495
+ continue;
496
+ }
497
+ const loop = Number.parseInt(marquee.getAttribute("loop") ?? "-1", 10);
498
+ const candidate = candidateFor(marquee);
499
+ candidate.targets.push(marquee);
500
+ candidate.marquee = { loop: Number.isNaN(loop) ? -1 : loop };
501
+ }
502
+ for (const video of document.querySelectorAll("video")) {
503
+ if (video.paused || video.ended) {
504
+ continue;
505
+ }
506
+ const before = state?.videos.get(video);
507
+ const candidate = candidateFor(video);
508
+ candidate.targets.push(video);
509
+ candidate.video = {
510
+ controls: video.controls,
511
+ endless: video.loop || video.duration === Number.POSITIVE_INFINITY,
512
+ durationS: Number.isFinite(video.duration) ? video.duration : null,
513
+ playingAtStart: before?.playing ?? false,
514
+ advanced: before !== void 0 && video.currentTime !== before.time
515
+ };
516
+ }
517
+ let essential = 0;
518
+ const lifted = /* @__PURE__ */ new Map();
519
+ const mergeInto = (into, from) => {
520
+ into.targets.push(...from.targets);
521
+ into.times.push(...from.times);
522
+ into.observed += from.observed;
523
+ into.appeared += from.appeared;
524
+ into.animations.push(...from.animations.slice(0, ANIMATION_LIMIT - into.animations.length));
525
+ into.marquee ??= from.marquee;
526
+ into.video ??= from.video;
527
+ };
528
+ for (const candidate of candidates.values()) {
529
+ const host = candidate.el.getRootNode().host;
530
+ const el = host?.tagName === "MARQUEE" ? host : candidate.el;
531
+ if (isRoot(el) || !wasVisible(candidate, el)) {
532
+ continue;
533
+ }
534
+ if (isEssential(el)) {
535
+ essential++;
536
+ continue;
537
+ }
538
+ const regionEl = regionElementFor(el);
539
+ const existing = lifted.get(regionEl);
540
+ if (existing) {
541
+ mergeInto(existing, candidate);
542
+ } else {
543
+ lifted.set(regionEl, { ...candidate, el: regionEl });
544
+ }
545
+ }
546
+ const depthOf = (el) => {
547
+ let depth = 0;
548
+ for (let node = el.parentElement; node; node = node.parentElement) {
549
+ depth++;
550
+ }
551
+ return depth;
552
+ };
553
+ let regions = [];
554
+ for (const candidate of [...lifted.values()].sort((a, b) => depthOf(a.el) - depthOf(b.el))) {
555
+ const outer = regions.find((region) => region.el.contains(candidate.el));
556
+ if (outer) {
557
+ mergeInto(outer, candidate);
558
+ } else {
559
+ regions.push(candidate);
560
+ }
561
+ }
562
+ const commonAncestor = (a, b) => {
563
+ for (let node = a; node; node = node.parentElement) {
564
+ if (node.contains(b)) {
565
+ return node;
566
+ }
567
+ }
568
+ return null;
569
+ };
570
+ for (let merged = true; merged; ) {
571
+ merged = false;
572
+ search: for (const a of regions) {
573
+ for (const b of regions) {
574
+ if (a === b) {
575
+ continue;
576
+ }
577
+ const boxA = visibleBox(a.el);
578
+ const boxB = visibleBox(b.el);
579
+ const smaller = Math.min(areaOf(boxA), areaOf(boxB));
580
+ if (smaller === 0 || areaOf(intersect(boxA, boxB)) < smaller / 2) {
581
+ continue;
582
+ }
583
+ const ancestor = commonAncestor(a.el, b.el);
584
+ const union = areaOf({
585
+ left: Math.min(boxA.left, boxB.left),
586
+ top: Math.min(boxA.top, boxB.top),
587
+ right: Math.max(boxA.right, boxB.right),
588
+ bottom: Math.max(boxA.bottom, boxB.bottom)
589
+ });
590
+ const [keep, drop] = areaOf(boxA) >= areaOf(boxB) ? [a, b] : [b, a];
591
+ mergeInto(keep, drop);
592
+ if (ancestor && !isRoot(ancestor) && areaOf(visibleBox(ancestor)) <= union * 4) {
593
+ keep.el = ancestor;
594
+ }
595
+ regions = regions.filter((region) => region !== drop);
596
+ merged = true;
597
+ break search;
598
+ }
599
+ }
600
+ }
601
+ const pauseRules = [];
602
+ const reducedMotionSelectors = [];
603
+ let rulesSeen = 0;
604
+ const walkRules = (rules, reduced) => {
605
+ for (const rule of rules) {
606
+ if (rulesSeen++ > RULE_LIMIT) {
607
+ return;
608
+ }
609
+ const condition = rule.media?.mediaText ?? rule.conditionText ?? "";
610
+ const nowReduced = reduced || condition.includes("prefers-reduced-motion");
611
+ const selector = rule.selectorText;
612
+ const style = rule.style;
613
+ if (selector && style) {
614
+ if (nowReduced && (style.animationName || style.animationDuration || style.animationPlayState || style.animationIterationCount || style.transitionDuration || style.transitionProperty)) {
615
+ reducedMotionSelectors.push(selector);
616
+ }
617
+ if (style.animationPlayState === "paused" || style.animationName === "none") {
618
+ if (selector.includes(":hover")) {
619
+ pauseRules.push({ selector, on: "hover" });
620
+ }
621
+ if (selector.includes(":focus")) {
622
+ pauseRules.push({ selector, on: "focus" });
623
+ }
624
+ }
625
+ }
626
+ const nested = rule.cssRules;
627
+ if (nested) {
628
+ walkRules(nested, nowReduced);
629
+ }
630
+ }
631
+ };
632
+ for (const sheet of [...document.styleSheets, ...document.adoptedStyleSheets ?? []]) {
633
+ try {
634
+ walkRules(sheet.cssRules, false);
635
+ } catch {
636
+ }
637
+ }
638
+ const matches = (el, selector) => {
639
+ try {
640
+ return el.matches(selector);
641
+ } catch {
642
+ return false;
643
+ }
644
+ };
645
+ const withoutState = (selector) => selector.replace(/(^|[\s>+~,(])(?::hover|:focus-within|:focus-visible|:focus)+/g, "$1*").replace(/:hover|:focus-within|:focus-visible|:focus/g, "");
646
+ const nameOf = (el) => {
647
+ const labelledBy = (el.getAttribute("aria-labelledby") ?? "").split(/\s+/).map((id) => id ? document.getElementById(id)?.textContent ?? "" : "").join(" ");
648
+ const labels = [...el.labels ?? []].map((label) => label.textContent ?? "").join(" ");
649
+ const name = el.getAttribute("aria-label") || labelledBy.trim() || labels.trim() || (el.textContent ?? "").trim() || el.getAttribute("title") || el.querySelector("img[alt]")?.getAttribute("alt") || el.value || "";
650
+ return String(name).replace(/\s+/g, " ").trim();
651
+ };
652
+ const stash = [];
653
+ const stashIndex = (el) => {
654
+ const index = stash.indexOf(el);
655
+ return index === -1 ? stash.push(el) - 1 : index;
656
+ };
657
+ const toControl = (el, foundBy) => ({
658
+ elementIndex: stashIndex(el),
659
+ html: shallowHtml(el),
660
+ name: nameOf(el).slice(0, NAME_LIMIT),
661
+ foundBy
662
+ });
663
+ let pageControlEl;
664
+ const findPageControl = () => {
665
+ if (pageControlEl === void 0) {
666
+ pageControlEl = null;
667
+ let seen = 0;
668
+ for (const el of document.querySelectorAll(PAGE_CONTROL_SELECTOR)) {
669
+ if (seen++ > PAGE_CONTROL_LIMIT) {
670
+ break;
671
+ }
672
+ if (pageControl.test(nameOf(el)) && isRendered(el)) {
673
+ pageControlEl = el;
674
+ break;
675
+ }
676
+ }
677
+ }
678
+ return pageControlEl;
679
+ };
680
+ const findControl = (regionEl, regionArea) => {
681
+ const scopes = [regionEl];
682
+ for (let parent = regionEl.parentElement, level = 0; !isRoot(parent) && level < CONTROL_ANCESTORS; parent = parent.parentElement, level++) {
683
+ if (areaOf(boxOf(parent)) > regionArea * CONTROL_SCOPE_GROWTH) {
684
+ break;
685
+ }
686
+ scopes.push(parent);
687
+ }
688
+ const outermost = scopes[scopes.length - 1];
689
+ const nearby = [...outermost.querySelectorAll(CONTROL_SELECTOR)];
690
+ if (regionEl.id) {
691
+ nearby.push(...document.querySelectorAll(`[aria-controls~="${CSS.escape(regionEl.id)}"]`));
692
+ }
693
+ const rendered = nearby.filter(isRendered);
694
+ const named = rendered.find((el) => {
695
+ const name = nameOf(el);
696
+ return name.length <= NAME_LIMIT && controlName.test(name);
697
+ });
698
+ if (named) {
699
+ return toControl(named, "name");
700
+ }
701
+ const hinted = rendered.find(
702
+ (el) => nameOf(el) === "" && controlAttribute.test(`${el.getAttribute("class") ?? ""} ${el.id}`)
703
+ );
704
+ if (hinted) {
705
+ return toControl(hinted, "attribute");
706
+ }
707
+ const pageWide = findPageControl();
708
+ return pageWide ? toControl(pageWide, "page-control") : null;
709
+ };
710
+ let tooSmall = [...smallPseudoHosts].filter(
711
+ (host) => isVisible(host) && !regions.some((region) => region.el.contains(host))
712
+ ).length;
713
+ const sized = [];
714
+ for (const candidate of regions) {
715
+ const box = visibleBox(candidate.el);
716
+ const area = areaOf(box);
717
+ if (area === 0) {
718
+ continue;
719
+ }
720
+ if (area < options.minRegionArea) {
721
+ tooSmall++;
722
+ continue;
723
+ }
724
+ sized.push({ candidate, box });
725
+ }
726
+ sized.sort((a, b) => areaOf(b.box) - areaOf(a.box));
727
+ const collected = sized.slice(0, options.regionLimit).map(({ candidate, box }) => {
728
+ const cssTargets = candidate.animations.some((animation) => animation.css) ? [...new Set(candidate.targets)] : [];
729
+ const pausesOn = ["hover", "focus"].filter(
730
+ (on) => pauseRules.some(
731
+ (rule) => rule.on === on && cssTargets.some((el) => matches(el, withoutState(rule.selector)))
732
+ )
733
+ );
734
+ return {
735
+ elementIndex: stashIndex(candidate.el),
736
+ html: shallowHtml(candidate.el),
737
+ rect: {
738
+ x: Math.round(box.left),
739
+ y: Math.round(box.top),
740
+ width: Math.round(box.right - box.left),
741
+ height: Math.round(box.bottom - box.top)
742
+ },
743
+ times: [...new Set(candidate.times.map((time) => Math.round(time)))].sort((a, b) => a - b).slice(0, TIMES_LIMIT),
744
+ appeared: candidate.observed > 0 && candidate.appeared === candidate.observed,
745
+ animations: candidate.animations,
746
+ marquee: candidate.marquee,
747
+ video: candidate.video,
748
+ control: findControl(candidate.el, areaOf(box)),
749
+ pausesOn,
750
+ reducedMotion: cssTargets.length === 0 ? null : cssTargets.some(
751
+ (el) => reducedMotionSelectors.some((selector) => matches(el, selector))
752
+ )
753
+ };
754
+ });
755
+ store[stashKey] = stash;
756
+ return {
757
+ elapsedMs: Math.round(elapsedMs),
758
+ regions: collected,
759
+ total: sized.length,
760
+ tooSmall,
761
+ essential
762
+ };
763
+ }
764
+ function scrollPositionScript() {
765
+ return { x: window.scrollX, y: window.scrollY };
766
+ }
767
+ function restoreScrollScript(position) {
768
+ window.scrollTo({ left: position.x, top: position.y, behavior: "instant" });
769
+ }
770
+
771
+ // src/classify.ts
772
+ var QUIET_GAP_FRACTION = 0.1;
773
+ var LATE_FRACTION = 0.6;
774
+ var CONTINUOUS_FRACTION = 0.4;
775
+ var MOTION_PROPERTY = /transform|translate|rotate|scale|^left$|^top$|^right$|^bottom$|inset|margin|padding|backgroundPosition|background-position|offset|width|height|opacity|visibility|clip|strokeDash|stroke-dash|^d$|^x$|^y$/i;
776
+ function videoEvidence(region, options) {
777
+ const video = region.video;
778
+ if (!video) {
779
+ return null;
780
+ }
781
+ const knownShort = !video.endless && video.durationS !== null && video.durationS * 1e3 <= options.durationLimitMs;
782
+ if (knownShort) {
783
+ return null;
784
+ }
785
+ const certain = video.playingAtStart && video.advanced && (video.endless || video.durationS !== null);
786
+ return {
787
+ motion: "video",
788
+ detectedBy: "media-element",
789
+ doubt: certain ? null : "uncertain-playback",
790
+ observedMs: options.observedMs
791
+ };
792
+ }
793
+ function marqueeEvidence(region, options) {
794
+ if (!region.marquee) {
795
+ return null;
796
+ }
797
+ return {
798
+ motion: "marquee",
799
+ detectedBy: "element",
800
+ doubt: region.marquee.loop > 0 ? "finite-loop" : null,
801
+ observedMs: options.observedMs
802
+ };
803
+ }
804
+ function animationEvidence(region, options) {
805
+ if (region.animations.length === 0) {
806
+ return null;
807
+ }
808
+ const onRegion = region.animations.filter(
809
+ (animation) => animation.pseudoElement === null || animation.pseudoArea !== null && animation.pseudoArea >= options.largeRegionArea
810
+ );
811
+ const moves = onRegion.some(
812
+ (animation) => animation.properties.some((property) => MOTION_PROPERTY.test(property))
813
+ );
814
+ return {
815
+ motion: region.animations.some((animation) => animation.css) ? "css-animation" : "web-animation",
816
+ detectedBy: "animation-api",
817
+ doubt: onRegion.length === 0 ? "pseudo-element" : moves ? null : "subtle-animation",
818
+ observedMs: options.observedMs
819
+ };
820
+ }
821
+ function burstsOf(times, quietGapMs) {
822
+ const bursts = [];
823
+ for (const time of times) {
824
+ const current = bursts.at(-1);
825
+ if (current && time - current.at(-1) <= quietGapMs) {
826
+ current.push(time);
827
+ } else {
828
+ bursts.push([time]);
829
+ }
830
+ }
831
+ return bursts;
832
+ }
833
+ function observationEvidence(region, options) {
834
+ const window2 = Math.max(options.observedMs, 1);
835
+ const times = [...region.times].sort((a, b) => a - b);
836
+ const last = times.at(-1);
837
+ if (last === void 0 || last < window2 * LATE_FRACTION) {
838
+ return null;
839
+ }
840
+ const bursts = burstsOf(times, options.quietGapMs ?? window2 * QUIET_GAP_FRACTION);
841
+ const latest = bursts.at(-1);
842
+ const sustained = bursts.length >= 2 || latest.at(-1) - latest[0] >= window2 * CONTINUOUS_FRACTION;
843
+ if (!sustained) {
844
+ if (latest.length < 2 || region.appeared) {
845
+ return null;
846
+ }
847
+ }
848
+ return {
849
+ motion: "script",
850
+ detectedBy: "dom-observation",
851
+ doubt: sustained ? null : "changed-once",
852
+ observedMs: Math.round(last)
853
+ };
854
+ }
855
+ function classifyRegion(region, options) {
856
+ const all = [
857
+ videoEvidence(region, options),
858
+ marqueeEvidence(region, options),
859
+ animationEvidence(region, options),
860
+ observationEvidence(region, options)
861
+ ].filter((evidence2) => evidence2 !== null);
862
+ const evidence = all.find(({ doubt }) => doubt === null) ?? all[0];
863
+ if (!evidence) {
864
+ return null;
865
+ }
866
+ const { motion, detectedBy, observedMs } = evidence;
867
+ const verdict = (verdict2, finding) => ({
868
+ verdict: verdict2,
869
+ finding,
870
+ motion,
871
+ detectedBy,
872
+ observedMs
873
+ });
874
+ if (region.control) {
875
+ return verdict("passed", "pause-control");
876
+ }
877
+ if (motion === "video" && region.video?.controls) {
878
+ return verdict("passed", "native-controls");
879
+ }
880
+ if (evidence.doubt) {
881
+ return verdict("needsReview", evidence.doubt);
882
+ }
883
+ if (motion === "css-animation" && region.pausesOn.includes("focus")) {
884
+ return verdict("needsReview", "pauses-on-focus");
885
+ }
886
+ if (motion === "css-animation" && region.pausesOn.includes("hover")) {
887
+ return verdict("needsReview", "pauses-on-hover");
888
+ }
889
+ if (region.rect.width * region.rect.height < options.largeRegionArea) {
890
+ return verdict("needsReview", "small-region");
891
+ }
892
+ return verdict("failed", "no-pause-control");
893
+ }
894
+
895
+ // src/audit.ts
896
+ var DURATION_LIMIT_MS = 5e3;
897
+ var DEFAULT_OBSERVATION_WINDOW = DURATION_LIMIT_MS;
898
+ var DEFAULT_MIN_REGION_AREA = 5e3;
899
+ var DEFAULT_LARGE_REGION_AREA = 2e4;
900
+ var DEFAULT_REGION_LIMIT = 20;
901
+ var DEFAULT_SCREENSHOT_LIMIT = 5;
902
+ var DEFAULT_SCREENSHOT_INTERVAL = 1e3;
903
+ var DEFAULT_CONTROL_NAME_PATTERN = "(^|[^\\p{L}])(pause|paused|unpause|stop|halt|freeze|hide|close|dismiss|pausar|pausa|detener|parar|pausieren|anhalten|stopp|stoppen|arr\xEAter|pauzeren|fermare|pausera|stoppa|play\\s*(/|\\||&|and|or)\\s*pause|play(ing)?\\s+(the\\s+)?(slideshow|slide\\s?show|slides|carousel|animations?|rotation|ticker|marquee|background\\s+video))($|[^\\p{L}])|^\\s*(play|playing)\\s*$";
904
+ var CONTROL_ATTRIBUTE_PATTERN = "(^|[-_\\s])(pause|playpause|play-pause|stop)($|[-_\\s])";
905
+ var PAGE_CONTROL_PATTERN = "\\b(pause|stop|turn off|disable|reduce)\\s+(\\S+\\s+){0,2}(animations?|motion|movement|moving|autoplay)\\b";
906
+ var ESSENTIAL_PATTERN = "(^|[-_\\s])(spinner|loader|loading|skeleton|shimmer|progress)($|[-_\\s])";
907
+ var STATE_KEY = "__a11yPulseMovingContentState";
908
+ var STASH_KEY = "__a11yPulseMovingContent";
909
+ var SCREENSHOT_CLIP_BUFFER = 10;
910
+ var SCREENSHOT_SETTLE_MS = 33;
911
+ var POLLS_PER_WINDOW = 50;
912
+ var MIN_POLL_MS = 20;
913
+ var MAX_POLL_MS = 250;
914
+ var TRACK_LIMIT = 150;
915
+ var QUIET_GAP_POLLS = 3;
916
+ function pollInterval(observationWindow) {
917
+ return Math.min(
918
+ MAX_POLL_MS,
919
+ Math.max(MIN_POLL_MS, Math.round(observationWindow / POLLS_PER_WINDOW))
920
+ );
921
+ }
922
+ function quietGap(observationWindow) {
923
+ return Math.max(
924
+ Math.round(observationWindow * QUIET_GAP_FRACTION),
925
+ pollInterval(observationWindow) * QUIET_GAP_POLLS
926
+ );
927
+ }
928
+ function sleep(ms) {
929
+ return new Promise((resolve) => setTimeout(resolve, ms));
930
+ }
931
+ async function screenshotRegion(adaptor, index) {
932
+ const handle = await stashedElementHandle(adaptor, STASH_KEY, index);
933
+ try {
934
+ return await captureElementScreenshot(adaptor, handle, {
935
+ clipBuffer: SCREENSHOT_CLIP_BUFFER,
936
+ settleDelay: SCREENSHOT_SETTLE_MS
937
+ });
938
+ } finally {
939
+ await adaptor.disposeRef(handle);
940
+ }
941
+ }
942
+ async function toRegions(adaptor, classified) {
943
+ const selectors = await stashedElementSelectors(
944
+ adaptor,
945
+ STASH_KEY,
946
+ classified.map(({ region }) => region.elementIndex)
947
+ );
948
+ const controls = classified.flatMap(({ region }) => region.control ? [region.control] : []);
949
+ const controlSelectors = await stashedElementSelectors(
950
+ adaptor,
951
+ STASH_KEY,
952
+ controls.map((control) => control.elementIndex)
953
+ );
954
+ return classified.map(({ region, classification }, i) => {
955
+ const control = region.control;
956
+ return {
957
+ selector: selectors[i],
958
+ html: truncateHtml(region.html),
959
+ rect: region.rect,
960
+ motion: classification.motion,
961
+ detectedBy: classification.detectedBy,
962
+ finding: classification.finding,
963
+ observedMs: classification.observedMs,
964
+ animations: region.animations.map(
965
+ ({ name, infinite, activeDurationMs, properties, pseudoElement }) => ({
966
+ name,
967
+ infinite,
968
+ activeDurationMs,
969
+ properties,
970
+ pseudoElement
971
+ })
972
+ ),
973
+ pauseControl: control ? {
974
+ selector: controlSelectors[controls.indexOf(control)],
975
+ html: truncateHtml(control.html),
976
+ name: control.name,
977
+ foundBy: control.foundBy
978
+ } : null,
979
+ pausesOn: region.pausesOn,
980
+ reducedMotion: region.reducedMotion
981
+ };
982
+ });
983
+ }
984
+ async function runMovingContentAudit(adaptor, options = {}) {
985
+ const observationWindow = options.observationWindow ?? DEFAULT_OBSERVATION_WINDOW;
986
+ const screenshotLimit = options.screenshotLimit ?? DEFAULT_SCREENSHOT_LIMIT;
987
+ const screenshotInterval = options.screenshotInterval ?? DEFAULT_SCREENSHOT_INTERVAL;
988
+ const pollMs = pollInterval(observationWindow);
989
+ const quietGapMs = quietGap(observationWindow);
990
+ const collectOptions = {
991
+ durationLimitMs: DURATION_LIMIT_MS,
992
+ minRegionArea: options.minRegionArea ?? DEFAULT_MIN_REGION_AREA,
993
+ regionLimit: options.regionLimit ?? DEFAULT_REGION_LIMIT,
994
+ controlNamePattern: options.controlNamePattern ?? DEFAULT_CONTROL_NAME_PATTERN,
995
+ controlAttributePattern: CONTROL_ATTRIBUTE_PATTERN,
996
+ pageControlPattern: PAGE_CONTROL_PATTERN,
997
+ essentialPattern: ESSENTIAL_PATTERN
998
+ };
999
+ await adaptor.evaluate(
1000
+ startObservationScript,
1001
+ STATE_KEY,
1002
+ pollMs,
1003
+ DURATION_LIMIT_MS,
1004
+ TRACK_LIMIT,
1005
+ quietGapMs
1006
+ );
1007
+ try {
1008
+ await sleep(observationWindow);
1009
+ const collection = await adaptor.evaluate(
1010
+ collectRegionsScript,
1011
+ STATE_KEY,
1012
+ STASH_KEY,
1013
+ collectOptions
1014
+ );
1015
+ const classified = collection.regions.flatMap((region) => {
1016
+ const classification = classifyRegion(region, {
1017
+ observedMs: collection.elapsedMs,
1018
+ durationLimitMs: DURATION_LIMIT_MS,
1019
+ largeRegionArea: options.largeRegionArea ?? DEFAULT_LARGE_REGION_AREA
1020
+ });
1021
+ return classification ? [{ region, classification }] : [];
1022
+ });
1023
+ const withVerdict = (verdict) => classified.filter(({ classification }) => classification.verdict === verdict);
1024
+ const failed = await toRegions(adaptor, withVerdict("failed"));
1025
+ const needsReview = await toRegions(adaptor, withVerdict("needsReview"));
1026
+ const passed = await toRegions(adaptor, withVerdict("passed"));
1027
+ const toScreenshot = [...withVerdict("failed"), ...withVerdict("needsReview")].slice(
1028
+ 0,
1029
+ screenshotLimit
1030
+ );
1031
+ if (toScreenshot.length > 0) {
1032
+ const reported = [...failed, ...needsReview];
1033
+ const scroll = await adaptor.evaluate(scrollPositionScript);
1034
+ try {
1035
+ for (const [i, { region }] of toScreenshot.entries()) {
1036
+ reported[i].screenshot = await screenshotRegion(adaptor, region.elementIndex);
1037
+ }
1038
+ await sleep(screenshotInterval);
1039
+ for (const [i, { region }] of toScreenshot.entries()) {
1040
+ reported[i].laterScreenshot = await screenshotRegion(adaptor, region.elementIndex);
1041
+ }
1042
+ } finally {
1043
+ await adaptor.evaluate(restoreScrollScript, scroll);
1044
+ }
1045
+ }
1046
+ return {
1047
+ failed,
1048
+ needsReview,
1049
+ passed,
1050
+ observedMs: collection.elapsedMs,
1051
+ summary: {
1052
+ checked: classified.length,
1053
+ failed: failed.length,
1054
+ needsReview: needsReview.length,
1055
+ passed: passed.length,
1056
+ unchecked: collection.total - collection.regions.length,
1057
+ ignored: { essential: collection.essential, tooSmall: collection.tooSmall }
1058
+ }
1059
+ };
1060
+ } finally {
1061
+ await adaptor.evaluate(stopObservationScript, STATE_KEY);
1062
+ await releaseStashedElements(adaptor, STASH_KEY);
1063
+ }
1064
+ }
1065
+ export {
1066
+ DEFAULT_CONTROL_NAME_PATTERN,
1067
+ DEFAULT_LARGE_REGION_AREA,
1068
+ DEFAULT_MIN_REGION_AREA,
1069
+ DEFAULT_OBSERVATION_WINDOW,
1070
+ DEFAULT_REGION_LIMIT,
1071
+ DEFAULT_SCREENSHOT_INTERVAL,
1072
+ DEFAULT_SCREENSHOT_LIMIT,
1073
+ DURATION_LIMIT_MS,
1074
+ runMovingContentAudit
1075
+ };
1076
+ //# sourceMappingURL=index.js.map