@ngbracket/a11y-devtools 0.8.0 → 0.9.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/CHANGELOG.md CHANGED
@@ -3,6 +3,31 @@
3
3
  All notable changes to `@ngbracket/a11y-devtools` are documented here.
4
4
  This project adheres to [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## 0.9.0
7
+
8
+ ### Added
9
+
10
+ - **Keyboard & Focus Mode, M3 (part 2): keyboard-trap detection with real Tab
11
+ presses.** New opt-in report-mode flag `--focus-traps` (`focusTraps: true` in
12
+ `scanPages`). It walks each route with real Tab key presses and reports
13
+ **`ngbr/focus-trap`** when focus cycles inside part of the page and never moves on
14
+ ([WCAG 2.1.2 No Keyboard Trap](https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap.html)).
15
+ The finding goes on the element holding the cycle and counts the controls that
16
+ were never reached. It's **serious** when Shift+Tab is trapped too, and
17
+ **moderate** when Shift+Tab escapes.
18
+ - Focus cycling inside an open `aria-modal` / `<dialog>` is containment, not a
19
+ trap, so it isn't reported. Repeated focus on an `<iframe>` (tabbing inside the
20
+ frame) isn't read as a trap.
21
+ - The walk runs after the scan, since pressing Tab can change page state.
22
+ - New public API: `detectTabTrap` (pure walk classifier), `createFocusWalkProbe`,
23
+ and the `FocusObservation` / `TabWalkVerdict` / `FocusWalkProbe` types.
24
+ - **Honesty guardrail:** a candidate, labelled "verify manually". A widget that
25
+ keeps Tab on purpose (a code editor) is fine if it documents another exit.
26
+ - **Real-browser E2E test.** `src/testing/e2e-report.spec.ts` drives the built
27
+ report-mode through Chromium over local fixture pages: axe, layout-dependent
28
+ tab order, and the trap walk. CI now installs Chromium so it runs there. It
29
+ skips itself when `dist/` or a Playwright Chromium is missing.
30
+
6
31
  ## 0.8.0
7
32
 
8
33
  ### Added
package/README.md CHANGED
@@ -194,8 +194,37 @@ It adds:
194
194
  npx ngbr-a11y-report --base http://localhost:4200 --route / --keyboard
195
195
  ```
196
196
 
197
- **Honesty guardrail:** `click-without-key` and `tab-order-mismatch` are
198
- *heuristics* — labelled "verify manually", never reported as confirmed failures.
197
+ **Honesty guardrail:** `click-without-key`, `tab-order-mismatch`,
198
+ `modal-focus-not-contained` and `focus-trap` are *heuristics*. They're labelled
199
+ "verify manually" and never reported as confirmed failures.
200
+
201
+ ### Keyboard traps (report-mode, M3)
202
+
203
+ A keyboard trap is focus you can Tab *into* but never Tab *out of*
204
+ ([WCAG 2.1.2](https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap.html)).
205
+ You can't find one by reading the DOM. Script makes the trap, by intercepting Tab or
206
+ re-focusing on blur, and synthetic key events don't move focus in a browser. So
207
+ report-mode presses the **real** Tab key through each route:
208
+
209
+ ```bash
210
+ npx ngbr-a11y-report --base http://localhost:4200 --route / --focus-traps
211
+ ```
212
+
213
+ - If focus laps the page (passes `<body>` and comes back round), there's no trap.
214
+ - If focus cycles inside part of the page without ever leaving, that's reported as
215
+ **`ngbr/focus-trap`**. The finding goes on the element that holds the cycle and
216
+ counts the tabbable controls that were never reached. The walk then tries
217
+ Shift+Tab: the finding is **serious** if that's stuck too, and **moderate** if
218
+ Shift+Tab gets out.
219
+ - Focus cycling inside an open `aria-modal` / `<dialog>` is containment working,
220
+ so it isn't reported. Consecutive focus on an `<iframe>` (Tab moving inside the
221
+ frame) isn't read as a trap either.
222
+
223
+ It's a separate flag (`focusTraps: true` in `scanPages`) because it's the one check
224
+ that *changes the page*. Pressing Tab can fire focus handlers and open menus, so
225
+ it runs after the scan. A widget that deliberately keeps Tab, like a code editor,
226
+ is fine if it tells users how to leave (Escape, for example). That's why the finding
227
+ says "verify manually".
199
228
 
200
229
  ### Accessibility-tree preview (M2)
201
230
 
@@ -248,22 +277,33 @@ static import (or adding a top-level side effect) fails the build.
248
277
 
249
278
  ```bash
250
279
  npm install --legacy-peer-deps
251
- npm test # vitest + jsdom + Angular TestBed (real axe)
280
+ npm test # vitest + jsdom + Angular TestBed (real axe); the real-browser
281
+ # E2E spec runs after a build, once `npx playwright install chromium`
252
282
  npm run build # tsc -> dist/ (ESM + .d.ts)
253
283
  ```
254
284
 
255
285
  ## Roadmap
256
286
 
257
- - Keyboard & Focus Mode **M3 (part 2)** — *bad-trap* detection ("you can Tab in but
258
- never Tab out") via real Tab presses in headless report-mode.
287
+ ### Planned
288
+
259
289
  - Headless "linear walkthrough" — the tab sequence as an SR-ish reading list per
260
290
  route in report-mode (M2's preview is currently overlay-only).
261
291
  - HTML report + baseline/diff mode for CI.
262
292
  - Per-component filtering and a violation-count badge.
263
293
 
264
- Done: component attribution (nearest app-owned, walking past UI primitives) ·
265
- directive / `hostDirectives` attribution · configurable framework prefixes · axe
266
- scan · grouped console reporter · dev-only provider · in-app overlay · headless
267
- report mode (CLI + `./report`) · **Keyboard & Focus Mode M1** (tab-order viz +
268
- keyboard-reachability findings) · **M2** (focus-follow accessibility-tree preview) ·
269
- **M3 part 1** (missing focus-trap: uncontained `aria-modal`) · CI prod-weight guard.
294
+ ### Done
295
+
296
+ - Component attribution — the nearest app-owned component, walking past UI primitives.
297
+ - Directive and `hostDirectives` attribution.
298
+ - Configurable framework prefixes.
299
+ - axe scan.
300
+ - Grouped console reporter.
301
+ - Dev-only provider.
302
+ - In-app overlay.
303
+ - Headless report mode (CLI + `./report`).
304
+ - **Keyboard & Focus Mode M1** — tab-order visualisation + keyboard-reachability findings.
305
+ - **Keyboard & Focus Mode M2** — focus-follow accessibility-tree preview.
306
+ - **Keyboard & Focus Mode M3** — missing focus-trap detection (uncontained
307
+ `aria-modal`) and the keyboard-trap walk with real Tab presses.
308
+ - CI production-weight guard.
309
+ - Real-browser E2E test.
@@ -26,6 +26,9 @@ Options:
26
26
  --keyboard Also run the keyboard layer: heuristic ngbr/* findings for
27
27
  keyboard-unreachable controls, click-without-keyboard
28
28
  handlers, and visual-vs-tab-order mismatches
29
+ --focus-traps Also walk each route with real Tab presses to find keyboard
30
+ traps — focus that cycles inside part of the page and
31
+ never moves on (ngbr/focus-trap). Runs after the scan
29
32
  --headed Launch a visible browser (debugging)
30
33
  -h, --help Show this help
31
34
  `;
@@ -50,6 +53,7 @@ function parseArgs(argv) {
50
53
  break;
51
54
  case '--no-skip-primitives': opts.frameworkPrefixes = []; break;
52
55
  case '--keyboard': opts.keyboard = true; break;
56
+ case '--focus-traps': opts.focusTraps = true; break;
53
57
  case '--headed': opts.headed = true; break;
54
58
  case '-h': case '--help': opts.help = true; break;
55
59
  default: console.error(`Unknown argument: ${arg}\n`); opts.help = true;
@@ -73,6 +77,7 @@ const report = await scanPages({
73
77
  headed: opts.headed,
74
78
  frameworkPrefixes: opts.frameworkPrefixes,
75
79
  keyboard: opts.keyboard,
80
+ focusTraps: opts.focusTraps,
76
81
  });
77
82
 
78
83
  const allFindings = report.pages.flatMap((p) => p.findings);
package/dist/index.d.ts CHANGED
@@ -6,5 +6,6 @@ export { resolveOwningComponentName, resolveComponentPath, appComponentFromPath,
6
6
  export { tabSequence, isTabbable, isNativelyFocusable, resolvedTabIndex, visualOrderJumps, type TabStop, type TabSequenceOptions, } from './keyboard/tab-sequence.js';
7
7
  export { scanKeyboard, type KeyboardScanOptions } from './keyboard/keyboard-scan.js';
8
8
  export { findUncontainedModals, type UncontainedModal } from './keyboard/focus-trap.js';
9
+ export { createFocusWalkProbe, detectTabTrap, type FocusObservation, type FocusWalkProbe, type TabWalkVerdict, } from './keyboard/focus-walk.js';
9
10
  export { describeElement, accessibleDescription, ariaStates, type AxDescription, } from './keyboard/accname.js';
10
11
  export { createOverlay, OVERLAY_ATTR, OVERLAY_EXCLUDE_SELECTOR, type A11yOverlay, type OverlayOptions, type AxPanelData, } from './overlay.js';
package/dist/index.js CHANGED
@@ -6,5 +6,6 @@ export { resolveOwningComponentName, resolveComponentPath, appComponentFromPath,
6
6
  export { tabSequence, isTabbable, isNativelyFocusable, resolvedTabIndex, visualOrderJumps, } from './keyboard/tab-sequence.js';
7
7
  export { scanKeyboard } from './keyboard/keyboard-scan.js';
8
8
  export { findUncontainedModals } from './keyboard/focus-trap.js';
9
+ export { createFocusWalkProbe, detectTabTrap, } from './keyboard/focus-walk.js';
9
10
  export { describeElement, accessibleDescription, ariaStates, } from './keyboard/accname.js';
10
11
  export { createOverlay, OVERLAY_ATTR, OVERLAY_EXCLUDE_SELECTOR, } from './overlay.js';
@@ -34222,6 +34222,336 @@
34222
34222
  return names;
34223
34223
  }
34224
34224
 
34225
+ // dist/keyboard/tab-sequence.js
34226
+ var FOCUSABLE_SELECTOR = [
34227
+ "a[href]",
34228
+ "area[href]",
34229
+ "button",
34230
+ "input",
34231
+ "select",
34232
+ "textarea",
34233
+ "audio[controls]",
34234
+ "video[controls]",
34235
+ "summary",
34236
+ "iframe",
34237
+ "object",
34238
+ "embed",
34239
+ "[contenteditable]",
34240
+ "[tabindex]"
34241
+ ].join(",");
34242
+ function nativeTabIndex(element) {
34243
+ return isNativelyFocusable(element) ? 0 : -1;
34244
+ }
34245
+ function isNativelyFocusable(element) {
34246
+ const tag = element.tagName.toLowerCase();
34247
+ switch (tag) {
34248
+ case "a":
34249
+ case "area":
34250
+ return element.hasAttribute("href");
34251
+ case "button":
34252
+ case "select":
34253
+ case "textarea":
34254
+ return true;
34255
+ case "input":
34256
+ return element.getAttribute("type")?.toLowerCase() !== "hidden";
34257
+ case "summary":
34258
+ return true;
34259
+ case "iframe":
34260
+ case "object":
34261
+ case "embed":
34262
+ return true;
34263
+ case "audio":
34264
+ case "video":
34265
+ return element.hasAttribute("controls");
34266
+ }
34267
+ const editable = element.getAttribute("contenteditable");
34268
+ return editable !== null && editable !== "false";
34269
+ }
34270
+ function resolvedTabIndex(element) {
34271
+ const attr = element.getAttribute("tabindex");
34272
+ if (attr === null)
34273
+ return nativeTabIndex(element);
34274
+ const parsed = Number.parseInt(attr, 10);
34275
+ return Number.isNaN(parsed) ? nativeTabIndex(element) : parsed;
34276
+ }
34277
+ function isDisabled(element) {
34278
+ if ("disabled" in element && element.disabled)
34279
+ return true;
34280
+ return element.closest("fieldset[disabled]") !== null && element.closest("legend") === null;
34281
+ }
34282
+ function isStructurallyHidden(element) {
34283
+ if (element.closest("[inert]") || element.closest("[hidden]"))
34284
+ return true;
34285
+ const closedDetails = element.closest("details:not([open])");
34286
+ return closedDetails !== null && element.closest("summary") === null && element !== closedDetails;
34287
+ }
34288
+ function defaultIsVisible(element) {
34289
+ const view = element.ownerDocument?.defaultView;
34290
+ if (!view?.getComputedStyle)
34291
+ return true;
34292
+ for (let node = element; node; node = node.parentElement) {
34293
+ const style = view.getComputedStyle(node);
34294
+ if (style.display === "none")
34295
+ return false;
34296
+ if (style.visibility === "hidden" || style.visibility === "collapse")
34297
+ return false;
34298
+ }
34299
+ return true;
34300
+ }
34301
+ function isTabbable(element, isVisible = defaultIsVisible) {
34302
+ if (resolvedTabIndex(element) < 0)
34303
+ return false;
34304
+ if (isDisabled(element))
34305
+ return false;
34306
+ if (isStructurallyHidden(element))
34307
+ return false;
34308
+ const editable = element.getAttribute("contenteditable");
34309
+ if (editable === "false" && !isNativelyFocusable(element) && !element.hasAttribute("tabindex")) {
34310
+ return false;
34311
+ }
34312
+ return isVisible(element);
34313
+ }
34314
+ function tabSequence(root = document, options = {}) {
34315
+ const isVisible = options.isVisible ?? defaultIsVisible;
34316
+ const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
34317
+ const candidates = [...root.querySelectorAll(FOCUSABLE_SELECTOR)].filter((el) => isTabbable(el, isVisible));
34318
+ const withMeta = candidates.map((element, domIndex) => ({
34319
+ element,
34320
+ domIndex,
34321
+ tabindex: resolvedTabIndex(element),
34322
+ positive: /^\d+$/.test(element.getAttribute("tabindex") ?? "") && resolvedTabIndex(element) > 0
34323
+ }));
34324
+ const positives = withMeta.filter((m) => m.tabindex > 0).sort((a, b) => a.tabindex - b.tabindex || a.domIndex - b.domIndex);
34325
+ const zeros = withMeta.filter((m) => m.tabindex === 0);
34326
+ return [...positives, ...zeros].map((m, i) => {
34327
+ const componentPath = resolveComponentPath(m.element);
34328
+ return {
34329
+ element: m.element,
34330
+ order: i + 1,
34331
+ tabindex: m.tabindex,
34332
+ positive: m.positive,
34333
+ component: appComponentFromPath(componentPath, prefixes),
34334
+ componentPath
34335
+ };
34336
+ });
34337
+ }
34338
+ function visualOrderJumps(stops, getRect = (el) => el.getBoundingClientRect(), rowThreshold = 8) {
34339
+ const jumps = [];
34340
+ for (let i = 1; i < stops.length; i++) {
34341
+ const prev = getRect(stops[i - 1].element);
34342
+ const curr = getRect(stops[i].element);
34343
+ const movedUp = curr.top < prev.top - rowThreshold;
34344
+ const sameRowMovedLeft = Math.abs(curr.top - prev.top) <= rowThreshold && curr.left < prev.left - rowThreshold;
34345
+ if (movedUp || sameRowMovedLeft)
34346
+ jumps.push(i);
34347
+ }
34348
+ return jumps;
34349
+ }
34350
+
34351
+ // dist/keyboard/focus-trap.js
34352
+ function findUncontainedModals(root = document, options = {}) {
34353
+ const stops = tabSequence(root, options);
34354
+ if (stops.length === 0)
34355
+ return [];
34356
+ const results = [];
34357
+ for (const modal of root.querySelectorAll('[aria-modal="true"]')) {
34358
+ let insideCount = 0;
34359
+ let outsideCount = 0;
34360
+ for (const stop of stops) {
34361
+ if (modal.contains(stop.element))
34362
+ insideCount++;
34363
+ else
34364
+ outsideCount++;
34365
+ }
34366
+ if (insideCount > 0 && outsideCount > 0)
34367
+ results.push({ element: modal, insideCount, outsideCount });
34368
+ }
34369
+ return results;
34370
+ }
34371
+
34372
+ // dist/keyboard/keyboard-scan.js
34373
+ var INTERACTIVE_ROLES = /* @__PURE__ */ new Set([
34374
+ "button",
34375
+ "link",
34376
+ "menuitem",
34377
+ "menuitemcheckbox",
34378
+ "menuitemradio",
34379
+ "tab",
34380
+ "switch",
34381
+ "checkbox",
34382
+ "radio",
34383
+ "option",
34384
+ "slider",
34385
+ "spinbutton",
34386
+ "combobox",
34387
+ "textbox",
34388
+ "searchbox",
34389
+ "treeitem"
34390
+ ]);
34391
+ var KEY_EVENTS = ["keydown", "keyup", "keypress"];
34392
+ var UNDERSTANDING = "https://www.w3.org/WAI/WCAG22/Understanding";
34393
+ var KEYBOARD_URL = `${UNDERSTANDING}/keyboard.html`;
34394
+ var FOCUS_ORDER_URL = `${UNDERSTANDING}/focus-order.html`;
34395
+ var DIALOG_MODAL_URL = "https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/";
34396
+ function shortSelector(element) {
34397
+ const tag = element.tagName.toLowerCase();
34398
+ if (element.id)
34399
+ return `${tag}#${element.id}`;
34400
+ const classes = (element.getAttribute("class") ?? "").trim().split(/\s+/).filter(Boolean).slice(0, 2);
34401
+ return classes.length ? `${tag}.${classes.join(".")}` : tag;
34402
+ }
34403
+ function shortHtml(element) {
34404
+ const html = element.outerHTML ?? "";
34405
+ return html.length > 160 ? `${html.slice(0, 159)}\u2026` : html;
34406
+ }
34407
+ function scanKeyboard(root = document, options = {}) {
34408
+ const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
34409
+ const isVisible = options.isVisible;
34410
+ const findings = [];
34411
+ const make = (element, id, impact, help, helpUrl) => {
34412
+ const componentPath = resolveComponentPath(element);
34413
+ return {
34414
+ id,
34415
+ impact,
34416
+ help,
34417
+ helpUrl,
34418
+ component: appComponentFromPath(componentPath, prefixes),
34419
+ componentPath,
34420
+ directives: resolveDirectiveNames(element),
34421
+ target: shortSelector(element),
34422
+ html: shortHtml(element)
34423
+ };
34424
+ };
34425
+ for (const element of root.querySelectorAll("*")) {
34426
+ if (isNativelyFocusable(element))
34427
+ continue;
34428
+ const role = element.getAttribute("role")?.toLowerCase() ?? "";
34429
+ const events = resolveListenerEvents(element);
34430
+ const hasClick = events.includes("click");
34431
+ const interactiveByRole = INTERACTIVE_ROLES.has(role);
34432
+ if (!hasClick && !interactiveByRole)
34433
+ continue;
34434
+ const focusable = isTabbable(element, isVisible);
34435
+ if (!focusable) {
34436
+ const reason = interactiveByRole ? `has role="${role}"` : "has a click handler";
34437
+ findings.push(make(element, "ngbr/unreachable-control", "serious", `Interactive element isn't reachable by keyboard \u2014 it ${reason} but is not a native control and has no tabindex >= 0, so keyboard and screen-reader users can't focus it. Add tabindex="0" (and a role, if missing), or use a <button>/<a>.`, KEYBOARD_URL));
34438
+ continue;
34439
+ }
34440
+ const hasKey = events.some((e) => KEY_EVENTS.includes(e));
34441
+ if (hasClick && !hasKey) {
34442
+ findings.push(make(element, "ngbr/click-without-key", "moderate", `Possible keyboard trap: this element has a (click) handler but no keyboard handler (keydown/keyup) and isn't a native button/link, so Enter/Space may not activate it. Verify by hand, then add a key handler or use a <button>.`, KEYBOARD_URL));
34443
+ }
34444
+ }
34445
+ for (const modal of findUncontainedModals(root, { frameworkPrefixes: prefixes, isVisible })) {
34446
+ findings.push(make(modal.element, "ngbr/modal-focus-not-contained", "moderate", `Possible missing focus trap: this element has aria-modal="true", but ${modal.outsideCount} tabbable element(s) outside it are still reachable, so a keyboard user can Tab out of the modal to the page behind. Mark the background inert or trap focus within the dialog. Heuristic \u2014 verify manually.`, DIALOG_MODAL_URL));
34447
+ }
34448
+ const stops = tabSequence(root, { frameworkPrefixes: prefixes, isVisible });
34449
+ for (const jump of visualOrderJumps(stops)) {
34450
+ const stop = stops[jump];
34451
+ findings.push(make(stop.element, "ngbr/tab-order-mismatch", "moderate", `Possible tab-order mismatch: Tab reaches this control (stop ${stop.order}) after one that sits below or to the right of it, so focus jumps against the visual reading order. Heuristic \u2014 verify the order makes sense for a sighted keyboard user.`, FOCUS_ORDER_URL));
34452
+ }
34453
+ return findings;
34454
+ }
34455
+
34456
+ // dist/keyboard/focus-walk.js
34457
+ function detectTabTrap(observations, collapsible = /* @__PURE__ */ new Set()) {
34458
+ const seq = [];
34459
+ for (const obs of observations) {
34460
+ const prev = seq[seq.length - 1];
34461
+ if (obs !== null && obs === prev && collapsible.has(obs))
34462
+ continue;
34463
+ seq.push(obs);
34464
+ }
34465
+ const lastSeen = /* @__PURE__ */ new Map();
34466
+ for (let i = 0; i < seq.length; i++) {
34467
+ const id = seq[i];
34468
+ if (id === null)
34469
+ continue;
34470
+ const before = lastSeen.get(id);
34471
+ if (before !== void 0) {
34472
+ const between = seq.slice(before, i);
34473
+ if (between.includes(null))
34474
+ return { kind: "complete" };
34475
+ return { kind: "trap", cycle: between };
34476
+ }
34477
+ lastSeen.set(id, i);
34478
+ }
34479
+ return { kind: "pending" };
34480
+ }
34481
+ var NO_KEYBOARD_TRAP_URL = "https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap.html";
34482
+ function deepActiveElement(doc) {
34483
+ let active = doc.activeElement;
34484
+ while (active?.shadowRoot?.activeElement)
34485
+ active = active.shadowRoot.activeElement;
34486
+ return active;
34487
+ }
34488
+ function containedByOpenModal(elements) {
34489
+ const modalOf = (el) => {
34490
+ const aria = el.closest('[aria-modal="true"]');
34491
+ if (aria)
34492
+ return aria;
34493
+ try {
34494
+ return el.closest("dialog:modal");
34495
+ } catch {
34496
+ return null;
34497
+ }
34498
+ };
34499
+ const first = elements[0] ? modalOf(elements[0]) : null;
34500
+ return first !== null && elements.every((el) => modalOf(el) === first);
34501
+ }
34502
+ function commonAncestor(elements) {
34503
+ let candidate = elements[0];
34504
+ while (candidate && !elements.every((el) => candidate.contains(el))) {
34505
+ candidate = candidate.parentElement;
34506
+ }
34507
+ return candidate ?? elements[0];
34508
+ }
34509
+ function createFocusWalkProbe(doc = document, frameworkPrefixes = DEFAULT_FRAMEWORK_PREFIXES) {
34510
+ const ids = /* @__PURE__ */ new WeakMap();
34511
+ const byId = /* @__PURE__ */ new Map();
34512
+ return {
34513
+ probe() {
34514
+ const active = deepActiveElement(doc);
34515
+ if (!active || active === doc.body || active === doc.documentElement) {
34516
+ return { id: null, iframe: false };
34517
+ }
34518
+ let id = ids.get(active);
34519
+ if (id === void 0) {
34520
+ id = byId.size + 1;
34521
+ ids.set(active, id);
34522
+ byId.set(id, active);
34523
+ }
34524
+ return { id, iframe: active.tagName === "IFRAME" };
34525
+ },
34526
+ stopCount() {
34527
+ return tabSequence(doc, { frameworkPrefixes }).length;
34528
+ },
34529
+ trapFinding(cycle, shiftTabEscapes) {
34530
+ const elements = [...new Set(cycle)].map((id) => byId.get(id)).filter((el) => el !== void 0);
34531
+ if (elements.length === 0 || containedByOpenModal(elements))
34532
+ return null;
34533
+ const owner = elements.length === 1 ? elements[0] : commonAncestor(elements);
34534
+ const reachable = new Set(byId.values());
34535
+ const unreached = tabSequence(doc, { frameworkPrefixes }).filter((stop) => !reachable.has(stop.element)).length;
34536
+ const where = elements.length === 1 ? "focus stays on this element when Tab is pressed" : `Tab cycles through ${elements.length} controls inside this element and never leaves`;
34537
+ const reach = unreached > 0 ? `, so ${unreached} tabbable control(s) in the page are never reached` : "";
34538
+ const shift = shiftTabEscapes ? " Shift+Tab does get out, but Tab alone should too." : " Shift+Tab doesn't get out either.";
34539
+ const componentPath = resolveComponentPath(owner);
34540
+ return {
34541
+ id: "ngbr/focus-trap",
34542
+ impact: shiftTabEscapes ? "moderate" : "serious",
34543
+ help: `Possible keyboard trap: ${where}${reach}.${shift} If this widget deliberately keeps Tab (e.g. a code editor), it must tell users how to leave (such as Escape); otherwise let Tab move focus on. Found by real Tab presses \u2014 verify manually.`,
34544
+ helpUrl: NO_KEYBOARD_TRAP_URL,
34545
+ component: appComponentFromPath(componentPath, frameworkPrefixes),
34546
+ componentPath,
34547
+ directives: resolveDirectiveNames(owner),
34548
+ target: shortSelector(owner),
34549
+ html: shortHtml(owner)
34550
+ };
34551
+ }
34552
+ };
34553
+ }
34554
+
34225
34555
  // dist/overlay.js
34226
34556
  var SVG_NS = "http://www.w3.org/2000/svg";
34227
34557
  var TAB_ORDER_COLOR = "#0b8f8f";
@@ -34534,237 +34864,6 @@
34534
34864
  }, 600);
34535
34865
  }
34536
34866
 
34537
- // dist/keyboard/tab-sequence.js
34538
- var FOCUSABLE_SELECTOR = [
34539
- "a[href]",
34540
- "area[href]",
34541
- "button",
34542
- "input",
34543
- "select",
34544
- "textarea",
34545
- "audio[controls]",
34546
- "video[controls]",
34547
- "summary",
34548
- "iframe",
34549
- "object",
34550
- "embed",
34551
- "[contenteditable]",
34552
- "[tabindex]"
34553
- ].join(",");
34554
- function nativeTabIndex(element) {
34555
- return isNativelyFocusable(element) ? 0 : -1;
34556
- }
34557
- function isNativelyFocusable(element) {
34558
- const tag = element.tagName.toLowerCase();
34559
- switch (tag) {
34560
- case "a":
34561
- case "area":
34562
- return element.hasAttribute("href");
34563
- case "button":
34564
- case "select":
34565
- case "textarea":
34566
- return true;
34567
- case "input":
34568
- return element.getAttribute("type")?.toLowerCase() !== "hidden";
34569
- case "summary":
34570
- return true;
34571
- case "iframe":
34572
- case "object":
34573
- case "embed":
34574
- return true;
34575
- case "audio":
34576
- case "video":
34577
- return element.hasAttribute("controls");
34578
- }
34579
- const editable = element.getAttribute("contenteditable");
34580
- return editable !== null && editable !== "false";
34581
- }
34582
- function resolvedTabIndex(element) {
34583
- const attr = element.getAttribute("tabindex");
34584
- if (attr === null)
34585
- return nativeTabIndex(element);
34586
- const parsed = Number.parseInt(attr, 10);
34587
- return Number.isNaN(parsed) ? nativeTabIndex(element) : parsed;
34588
- }
34589
- function isDisabled(element) {
34590
- if ("disabled" in element && element.disabled)
34591
- return true;
34592
- return element.closest("fieldset[disabled]") !== null && element.closest("legend") === null;
34593
- }
34594
- function isStructurallyHidden(element) {
34595
- if (element.closest("[inert]") || element.closest("[hidden]"))
34596
- return true;
34597
- const closedDetails = element.closest("details:not([open])");
34598
- return closedDetails !== null && element.closest("summary") === null && element !== closedDetails;
34599
- }
34600
- function defaultIsVisible(element) {
34601
- const view = element.ownerDocument?.defaultView;
34602
- if (!view?.getComputedStyle)
34603
- return true;
34604
- for (let node = element; node; node = node.parentElement) {
34605
- const style = view.getComputedStyle(node);
34606
- if (style.display === "none")
34607
- return false;
34608
- if (style.visibility === "hidden" || style.visibility === "collapse")
34609
- return false;
34610
- }
34611
- return true;
34612
- }
34613
- function isTabbable(element, isVisible = defaultIsVisible) {
34614
- if (resolvedTabIndex(element) < 0)
34615
- return false;
34616
- if (isDisabled(element))
34617
- return false;
34618
- if (isStructurallyHidden(element))
34619
- return false;
34620
- const editable = element.getAttribute("contenteditable");
34621
- if (editable === "false" && !isNativelyFocusable(element) && !element.hasAttribute("tabindex")) {
34622
- return false;
34623
- }
34624
- return isVisible(element);
34625
- }
34626
- function tabSequence(root = document, options = {}) {
34627
- const isVisible = options.isVisible ?? defaultIsVisible;
34628
- const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
34629
- const candidates = [...root.querySelectorAll(FOCUSABLE_SELECTOR)].filter((el) => isTabbable(el, isVisible));
34630
- const withMeta = candidates.map((element, domIndex) => ({
34631
- element,
34632
- domIndex,
34633
- tabindex: resolvedTabIndex(element),
34634
- positive: /^\d+$/.test(element.getAttribute("tabindex") ?? "") && resolvedTabIndex(element) > 0
34635
- }));
34636
- const positives = withMeta.filter((m) => m.tabindex > 0).sort((a, b) => a.tabindex - b.tabindex || a.domIndex - b.domIndex);
34637
- const zeros = withMeta.filter((m) => m.tabindex === 0);
34638
- return [...positives, ...zeros].map((m, i) => {
34639
- const componentPath = resolveComponentPath(m.element);
34640
- return {
34641
- element: m.element,
34642
- order: i + 1,
34643
- tabindex: m.tabindex,
34644
- positive: m.positive,
34645
- component: appComponentFromPath(componentPath, prefixes),
34646
- componentPath
34647
- };
34648
- });
34649
- }
34650
- function visualOrderJumps(stops, getRect = (el) => el.getBoundingClientRect(), rowThreshold = 8) {
34651
- const jumps = [];
34652
- for (let i = 1; i < stops.length; i++) {
34653
- const prev = getRect(stops[i - 1].element);
34654
- const curr = getRect(stops[i].element);
34655
- const movedUp = curr.top < prev.top - rowThreshold;
34656
- const sameRowMovedLeft = Math.abs(curr.top - prev.top) <= rowThreshold && curr.left < prev.left - rowThreshold;
34657
- if (movedUp || sameRowMovedLeft)
34658
- jumps.push(i);
34659
- }
34660
- return jumps;
34661
- }
34662
-
34663
- // dist/keyboard/focus-trap.js
34664
- function findUncontainedModals(root = document, options = {}) {
34665
- const stops = tabSequence(root, options);
34666
- if (stops.length === 0)
34667
- return [];
34668
- const results = [];
34669
- for (const modal of root.querySelectorAll('[aria-modal="true"]')) {
34670
- let insideCount = 0;
34671
- let outsideCount = 0;
34672
- for (const stop of stops) {
34673
- if (modal.contains(stop.element))
34674
- insideCount++;
34675
- else
34676
- outsideCount++;
34677
- }
34678
- if (insideCount > 0 && outsideCount > 0)
34679
- results.push({ element: modal, insideCount, outsideCount });
34680
- }
34681
- return results;
34682
- }
34683
-
34684
- // dist/keyboard/keyboard-scan.js
34685
- var INTERACTIVE_ROLES = /* @__PURE__ */ new Set([
34686
- "button",
34687
- "link",
34688
- "menuitem",
34689
- "menuitemcheckbox",
34690
- "menuitemradio",
34691
- "tab",
34692
- "switch",
34693
- "checkbox",
34694
- "radio",
34695
- "option",
34696
- "slider",
34697
- "spinbutton",
34698
- "combobox",
34699
- "textbox",
34700
- "searchbox",
34701
- "treeitem"
34702
- ]);
34703
- var KEY_EVENTS = ["keydown", "keyup", "keypress"];
34704
- var UNDERSTANDING = "https://www.w3.org/WAI/WCAG22/Understanding";
34705
- var KEYBOARD_URL = `${UNDERSTANDING}/keyboard.html`;
34706
- var FOCUS_ORDER_URL = `${UNDERSTANDING}/focus-order.html`;
34707
- var DIALOG_MODAL_URL = "https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/";
34708
- function shortSelector(element) {
34709
- const tag = element.tagName.toLowerCase();
34710
- if (element.id)
34711
- return `${tag}#${element.id}`;
34712
- const classes = (element.getAttribute("class") ?? "").trim().split(/\s+/).filter(Boolean).slice(0, 2);
34713
- return classes.length ? `${tag}.${classes.join(".")}` : tag;
34714
- }
34715
- function shortHtml(element) {
34716
- const html = element.outerHTML ?? "";
34717
- return html.length > 160 ? `${html.slice(0, 159)}\u2026` : html;
34718
- }
34719
- function scanKeyboard(root = document, options = {}) {
34720
- const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
34721
- const isVisible = options.isVisible;
34722
- const findings = [];
34723
- const make = (element, id, impact, help, helpUrl) => {
34724
- const componentPath = resolveComponentPath(element);
34725
- return {
34726
- id,
34727
- impact,
34728
- help,
34729
- helpUrl,
34730
- component: appComponentFromPath(componentPath, prefixes),
34731
- componentPath,
34732
- directives: resolveDirectiveNames(element),
34733
- target: shortSelector(element),
34734
- html: shortHtml(element)
34735
- };
34736
- };
34737
- for (const element of root.querySelectorAll("*")) {
34738
- if (isNativelyFocusable(element))
34739
- continue;
34740
- const role = element.getAttribute("role")?.toLowerCase() ?? "";
34741
- const events = resolveListenerEvents(element);
34742
- const hasClick = events.includes("click");
34743
- const interactiveByRole = INTERACTIVE_ROLES.has(role);
34744
- if (!hasClick && !interactiveByRole)
34745
- continue;
34746
- const focusable = isTabbable(element, isVisible);
34747
- if (!focusable) {
34748
- const reason = interactiveByRole ? `has role="${role}"` : "has a click handler";
34749
- findings.push(make(element, "ngbr/unreachable-control", "serious", `Interactive element isn't reachable by keyboard \u2014 it ${reason} but is not a native control and has no tabindex >= 0, so keyboard and screen-reader users can't focus it. Add tabindex="0" (and a role, if missing), or use a <button>/<a>.`, KEYBOARD_URL));
34750
- continue;
34751
- }
34752
- const hasKey = events.some((e) => KEY_EVENTS.includes(e));
34753
- if (hasClick && !hasKey) {
34754
- findings.push(make(element, "ngbr/click-without-key", "moderate", `Possible keyboard trap: this element has a (click) handler but no keyboard handler (keydown/keyup) and isn't a native button/link, so Enter/Space may not activate it. Verify by hand, then add a key handler or use a <button>.`, KEYBOARD_URL));
34755
- }
34756
- }
34757
- for (const modal of findUncontainedModals(root, { frameworkPrefixes: prefixes, isVisible })) {
34758
- findings.push(make(modal.element, "ngbr/modal-focus-not-contained", "moderate", `Possible missing focus trap: this element has aria-modal="true", but ${modal.outsideCount} tabbable element(s) outside it are still reachable, so a keyboard user can Tab out of the modal to the page behind. Mark the background inert or trap focus within the dialog. Heuristic \u2014 verify manually.`, DIALOG_MODAL_URL));
34759
- }
34760
- const stops = tabSequence(root, { frameworkPrefixes: prefixes, isVisible });
34761
- for (const jump of visualOrderJumps(stops)) {
34762
- const stop = stops[jump];
34763
- findings.push(make(stop.element, "ngbr/tab-order-mismatch", "moderate", `Possible tab-order mismatch: Tab reaches this control (stop ${stop.order}) after one that sits below or to the right of it, so focus jumps against the visual reading order. Heuristic \u2014 verify the order makes sense for a sighted keyboard user.`, FOCUS_ORDER_URL));
34764
- }
34765
- return findings;
34766
- }
34767
-
34768
34867
  // dist/scan.js
34769
34868
  var runChain = Promise.resolve();
34770
34869
  function scan(root = document, options, scanOptions) {
@@ -34811,6 +34910,7 @@
34811
34910
  // dist/inpage.js
34812
34911
  var run = (options, scanOptions) => scan(document, options, scanOptions);
34813
34912
  globalThis.__ngbA11yScan = run;
34913
+ globalThis.__ngbA11yCreateFocusProbe = (prefixes) => createFocusWalkProbe(document, prefixes);
34814
34914
  })();
34815
34915
  /*! Bundled license information:
34816
34916
 
package/dist/inpage.js CHANGED
@@ -1,3 +1,7 @@
1
+ import { createFocusWalkProbe } from './keyboard/focus-walk.js';
1
2
  import { scan } from './scan.js';
2
3
  const run = (options, scanOptions) => scan(document, options, scanOptions);
3
4
  globalThis.__ngbA11yScan = run;
5
+ // The in-page half of the focus-trap walk: the driver creates a probe, presses
6
+ // real Tab keys, and asks the probe what has focus after each one.
7
+ globalThis.__ngbA11yCreateFocusProbe = (prefixes) => createFocusWalkProbe(document, prefixes);
@@ -0,0 +1,55 @@
1
+ import type { A11yFinding } from '../scan.js';
2
+ /** One observation from the walk: a focused element's id, or null when focus is on `<body>`/nothing. */
3
+ export type FocusObservation = number | null;
4
+ /** Outcome of {@link detectTabTrap} over the observations so far. */
5
+ export type TabWalkVerdict =
6
+ /** Focus wrapped past the end of the page and came back round — no trap. */
7
+ {
8
+ kind: 'complete';
9
+ }
10
+ /** Focus is cycling through `cycle` (element ids, in order) without ever leaving. */
11
+ | {
12
+ kind: 'trap';
13
+ cycle: number[];
14
+ }
15
+ /** Not enough evidence yet — keep pressing Tab. */
16
+ | {
17
+ kind: 'pending';
18
+ };
19
+ /**
20
+ * Classify a Tab walk. Browsers pass focus through `<body>` (null here) when Tab
21
+ * wraps off the end of the page, so an element seen again *after* a null means
22
+ * focus made a full lap; seen again with no null in between means it looped
23
+ * inside part of the page — a trap. The walk may start mid-page (wherever the
24
+ * browser's navigation starting point is), which this handles for free.
25
+ *
26
+ * Consecutive repeats of an `iframe` are the browser tabbing *inside* the frame
27
+ * (the parent document only ever sees the frame element), so callers pass
28
+ * `collapsible` ids to skip those rather than read them as a trap.
29
+ */
30
+ export declare function detectTabTrap(observations: readonly FocusObservation[], collapsible?: ReadonlySet<number>): TabWalkVerdict;
31
+ /** In-page half of the walk; installed on `window` by the report-mode bundle. */
32
+ export interface FocusWalkProbe {
33
+ /**
34
+ * The currently focused element's walk id (drilling into open shadow roots),
35
+ * or null when focus is on `<body>`/nothing. `iframe` is true when the focused
36
+ * element is a frame, whose inner Tab stops the parent can't see.
37
+ */
38
+ probe(): {
39
+ id: FocusObservation;
40
+ iframe: boolean;
41
+ };
42
+ /** Number of tabbable stops in the page, for sizing the walk. */
43
+ stopCount(): number;
44
+ /**
45
+ * Build the finding for a detected cycle, or null when the cycle is focus
46
+ * correctly contained in an open modal. `shiftTabEscapes` records whether
47
+ * Shift+Tab got out (it lowers the impact but it's still a problem).
48
+ */
49
+ trapFinding(cycle: readonly number[], shiftTabEscapes: boolean): A11yFinding | null;
50
+ }
51
+ /**
52
+ * Create the in-page probe. Ids are assigned on first sight and held in page
53
+ * memory only — the walk never writes to the DOM.
54
+ */
55
+ export declare function createFocusWalkProbe(doc?: Document, frameworkPrefixes?: readonly string[]): FocusWalkProbe;
@@ -0,0 +1,147 @@
1
+ /**
2
+ * The keyboard layer, part D (M3 part 2): *bad* focus-trap detection — "you can
3
+ * Tab in, but never Tab out" (WCAG 2.1.2 No Keyboard Trap). Unlike the other
4
+ * keyboard checks this can't be read off the DOM: a trap is made by script that
5
+ * intercepts Tab or re-focuses on blur, and synthetic key events don't move focus
6
+ * in a browser. So report-mode drives **real** Tab presses (Playwright) and the
7
+ * walk is split in two:
8
+ *
9
+ * - {@link detectTabTrap} — pure: given the sequence of focused elements the walk
10
+ * observed, decide whether focus completed a full lap, is still going, or is
11
+ * cycling inside a subset of the page (a trap). Runs in Node; unit-tested.
12
+ * - {@link createFocusWalkProbe} — in-page: gives each focused element a stable
13
+ * id for the walk, and turns a detected cycle into an attributed finding.
14
+ *
15
+ * HONESTY GUARDRAIL: a candidate, not a verdict. Some widgets legitimately keep
16
+ * Tab (a code editor, a modal) and are fine if they document another exit — so
17
+ * the finding says "verify manually", and focus cycling inside an open modal is
18
+ * not reported at all (that's containment working; the missing-trap check covers
19
+ * a modal that leaks).
20
+ */
21
+ import { appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, resolveComponentPath, resolveDirectiveNames, } from '../attribution.js';
22
+ import { shortHtml, shortSelector } from './keyboard-scan.js';
23
+ import { tabSequence } from './tab-sequence.js';
24
+ /**
25
+ * Classify a Tab walk. Browsers pass focus through `<body>` (null here) when Tab
26
+ * wraps off the end of the page, so an element seen again *after* a null means
27
+ * focus made a full lap; seen again with no null in between means it looped
28
+ * inside part of the page — a trap. The walk may start mid-page (wherever the
29
+ * browser's navigation starting point is), which this handles for free.
30
+ *
31
+ * Consecutive repeats of an `iframe` are the browser tabbing *inside* the frame
32
+ * (the parent document only ever sees the frame element), so callers pass
33
+ * `collapsible` ids to skip those rather than read them as a trap.
34
+ */
35
+ export function detectTabTrap(observations, collapsible = new Set()) {
36
+ const seq = [];
37
+ for (const obs of observations) {
38
+ const prev = seq[seq.length - 1];
39
+ if (obs !== null && obs === prev && collapsible.has(obs))
40
+ continue;
41
+ seq.push(obs);
42
+ }
43
+ const lastSeen = new Map();
44
+ for (let i = 0; i < seq.length; i++) {
45
+ const id = seq[i];
46
+ if (id === null)
47
+ continue;
48
+ const before = lastSeen.get(id);
49
+ if (before !== undefined) {
50
+ const between = seq.slice(before, i);
51
+ if (between.includes(null))
52
+ return { kind: 'complete' };
53
+ return { kind: 'trap', cycle: between };
54
+ }
55
+ lastSeen.set(id, i);
56
+ }
57
+ return { kind: 'pending' };
58
+ }
59
+ const NO_KEYBOARD_TRAP_URL = 'https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap.html';
60
+ /** The element that really has focus, through open shadow roots. */
61
+ function deepActiveElement(doc) {
62
+ let active = doc.activeElement;
63
+ while (active?.shadowRoot?.activeElement)
64
+ active = active.shadowRoot.activeElement;
65
+ return active;
66
+ }
67
+ /** True when focus cycling among `elements` is an open modal containing focus (fine). */
68
+ function containedByOpenModal(elements) {
69
+ const modalOf = (el) => {
70
+ const aria = el.closest('[aria-modal="true"]');
71
+ if (aria)
72
+ return aria;
73
+ try {
74
+ return el.closest('dialog:modal');
75
+ }
76
+ catch {
77
+ return null; // engine without :modal
78
+ }
79
+ };
80
+ const first = elements[0] ? modalOf(elements[0]) : null;
81
+ return first !== null && elements.every((el) => modalOf(el) === first);
82
+ }
83
+ /** Nearest element containing every element of the cycle. */
84
+ function commonAncestor(elements) {
85
+ let candidate = elements[0];
86
+ while (candidate && !elements.every((el) => candidate.contains(el))) {
87
+ candidate = candidate.parentElement;
88
+ }
89
+ return candidate ?? elements[0];
90
+ }
91
+ /**
92
+ * Create the in-page probe. Ids are assigned on first sight and held in page
93
+ * memory only — the walk never writes to the DOM.
94
+ */
95
+ export function createFocusWalkProbe(doc = document, frameworkPrefixes = DEFAULT_FRAMEWORK_PREFIXES) {
96
+ const ids = new WeakMap();
97
+ const byId = new Map();
98
+ return {
99
+ probe() {
100
+ const active = deepActiveElement(doc);
101
+ if (!active || active === doc.body || active === doc.documentElement) {
102
+ return { id: null, iframe: false };
103
+ }
104
+ let id = ids.get(active);
105
+ if (id === undefined) {
106
+ id = byId.size + 1;
107
+ ids.set(active, id);
108
+ byId.set(id, active);
109
+ }
110
+ return { id, iframe: active.tagName === 'IFRAME' };
111
+ },
112
+ stopCount() {
113
+ return tabSequence(doc, { frameworkPrefixes }).length;
114
+ },
115
+ trapFinding(cycle, shiftTabEscapes) {
116
+ const elements = [...new Set(cycle)]
117
+ .map((id) => byId.get(id))
118
+ .filter((el) => el !== undefined);
119
+ if (elements.length === 0 || containedByOpenModal(elements))
120
+ return null;
121
+ const owner = elements.length === 1 ? elements[0] : commonAncestor(elements);
122
+ const reachable = new Set(byId.values());
123
+ const unreached = tabSequence(doc, { frameworkPrefixes }).filter((stop) => !reachable.has(stop.element)).length;
124
+ const where = elements.length === 1
125
+ ? 'focus stays on this element when Tab is pressed'
126
+ : `Tab cycles through ${elements.length} controls inside this element and never leaves`;
127
+ const reach = unreached > 0 ? `, so ${unreached} tabbable control(s) in the page are never reached` : '';
128
+ const shift = shiftTabEscapes
129
+ ? ' Shift+Tab does get out, but Tab alone should too.'
130
+ : ' Shift+Tab doesn\'t get out either.';
131
+ const componentPath = resolveComponentPath(owner);
132
+ return {
133
+ id: 'ngbr/focus-trap',
134
+ impact: shiftTabEscapes ? 'moderate' : 'serious',
135
+ help: `Possible keyboard trap: ${where}${reach}.${shift} If this widget deliberately keeps ` +
136
+ `Tab (e.g. a code editor), it must tell users how to leave (such as Escape); otherwise ` +
137
+ `let Tab move focus on. Found by real Tab presses — verify manually.`,
138
+ helpUrl: NO_KEYBOARD_TRAP_URL,
139
+ component: appComponentFromPath(componentPath, frameworkPrefixes),
140
+ componentPath,
141
+ directives: resolveDirectiveNames(owner),
142
+ target: shortSelector(owner),
143
+ html: shortHtml(owner),
144
+ };
145
+ },
146
+ };
147
+ }
@@ -5,6 +5,10 @@ export interface KeyboardScanOptions {
5
5
  /** Visibility predicate override (tests); see {@link tabSequence}. */
6
6
  isVisible?: (element: Element) => boolean;
7
7
  }
8
+ /** A short, human CSS-ish selector for our own findings (not an axe target). */
9
+ export declare function shortSelector(element: Element): string;
10
+ /** Truncated outerHTML for a finding's `html`. */
11
+ export declare function shortHtml(element: Element): string;
8
12
  /**
9
13
  * Scan `root` for keyboard-operability problems and return them as findings.
10
14
  * Runs entirely in the page (needs the live `window.ng` for listeners and
@@ -39,7 +39,7 @@ const KEYBOARD_URL = `${UNDERSTANDING}/keyboard.html`;
39
39
  const FOCUS_ORDER_URL = `${UNDERSTANDING}/focus-order.html`;
40
40
  const DIALOG_MODAL_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/';
41
41
  /** A short, human CSS-ish selector for our own findings (not an axe target). */
42
- function shortSelector(element) {
42
+ export function shortSelector(element) {
43
43
  const tag = element.tagName.toLowerCase();
44
44
  if (element.id)
45
45
  return `${tag}#${element.id}`;
@@ -50,7 +50,8 @@ function shortSelector(element) {
50
50
  .slice(0, 2);
51
51
  return classes.length ? `${tag}.${classes.join('.')}` : tag;
52
52
  }
53
- function shortHtml(element) {
53
+ /** Truncated outerHTML for a finding's `html`. */
54
+ export function shortHtml(element) {
54
55
  const html = element.outerHTML ?? '';
55
56
  return html.length > 160 ? `${html.slice(0, 159)}…` : html;
56
57
  }
@@ -33,6 +33,14 @@ export interface ScanPagesOptions {
33
33
  * Default false.
34
34
  */
35
35
  keyboard?: boolean;
36
+ /**
37
+ * Also walk each route with **real** Tab presses to find keyboard traps —
38
+ * focus that cycles inside part of the page and never moves on (WCAG 2.1.2),
39
+ * reported as `ngbr/focus-trap`. Runs after the scan, since pressing Tab can
40
+ * change page state (focus handlers, menus). Focus cycling inside an open
41
+ * modal is containment, not a trap, and isn't reported. Default false.
42
+ */
43
+ focusTraps?: boolean;
36
44
  }
37
45
  /**
38
46
  * Drive a real headless browser over a running Angular **dev** build and return
@@ -1,6 +1,7 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { dirname, resolve } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { detectTabTrap } from '../keyboard/focus-walk.js';
4
5
  async function loadPlaywright() {
5
6
  try {
6
7
  return await import('playwright');
@@ -14,6 +15,46 @@ async function loadPlaywright() {
14
15
  function inPageScriptPath() {
15
16
  return resolve(dirname(fileURLToPath(import.meta.url)), '..', 'inpage.global.js');
16
17
  }
18
+ /**
19
+ * Press Tab through the page until focus either laps the page (no trap) or
20
+ * cycles inside part of it (a trap), then check whether Shift+Tab gets out.
21
+ * Needs the in-page bundle already injected. Returns null when there's no trap,
22
+ * or when the press budget runs out before a verdict (inconclusive — e.g. focus
23
+ * stuck inside an iframe the parent can't see into).
24
+ */
25
+ async function walkForFocusTrap(page, frameworkPrefixes) {
26
+ const stops = await page.evaluate((prefixes) => {
27
+ const w = window;
28
+ w.__ngbA11yFocusProbe = w.__ngbA11yCreateFocusProbe(prefixes);
29
+ return w.__ngbA11yFocusProbe.stopCount();
30
+ }, frameworkPrefixes);
31
+ const probe = () => page.evaluate(() => window.__ngbA11yFocusProbe.probe());
32
+ // Enough for two laps of the page, capped so a huge page can't run forever.
33
+ const budget = Math.min(stops * 2 + 10, 400);
34
+ const observations = [];
35
+ const frames = new Set();
36
+ for (let i = 0; i < budget; i++) {
37
+ await page.keyboard.press('Tab');
38
+ const { id, iframe } = await probe();
39
+ if (iframe && id !== null)
40
+ frames.add(id);
41
+ observations.push(id);
42
+ const verdict = detectTabTrap(observations, frames);
43
+ if (verdict.kind === 'complete')
44
+ return null;
45
+ if (verdict.kind === 'trap') {
46
+ const inCycle = new Set(verdict.cycle);
47
+ let shiftTabEscapes = false;
48
+ for (let j = 0; j < verdict.cycle.length + 2 && !shiftTabEscapes; j++) {
49
+ await page.keyboard.press('Shift+Tab');
50
+ const { id: back } = await probe();
51
+ shiftTabEscapes = back === null || !inCycle.has(back);
52
+ }
53
+ return page.evaluate(([cycle, escapes]) => window.__ngbA11yFocusProbe.trapFinding(cycle, escapes), [verdict.cycle, shiftTabEscapes]);
54
+ }
55
+ }
56
+ return null;
57
+ }
17
58
  /**
18
59
  * Drive a real headless browser over a running Angular **dev** build and return
19
60
  * component-attributed findings per route. The scan runs *in the page* (via the
@@ -21,7 +62,7 @@ function inPageScriptPath() {
21
62
  * to the component that rendered it — with no change to the target app.
22
63
  */
23
64
  export async function scanPages(options) {
24
- const { baseUrl, routes, tags, waitMs = 1500, labels = {}, setup, headed = false, frameworkPrefixes, keyboard, } = options;
65
+ const { baseUrl, routes, tags, waitMs = 1500, labels = {}, setup, headed = false, frameworkPrefixes, keyboard, focusTraps, } = options;
25
66
  const axeOptions = tags
26
67
  ? { runOnly: { type: 'tag', values: tags } }
27
68
  : undefined;
@@ -49,6 +90,18 @@ export async function scanPages(options) {
49
90
  const w = window;
50
91
  return w.__ngbA11yScan(args.axe, args.scan);
51
92
  }, { axe: axeOptions, scan: { frameworkPrefixes, keyboard } }));
93
+ if (focusTraps) {
94
+ // A failed walk shouldn't throw away the scan's findings — warn and move on.
95
+ try {
96
+ const trap = await walkForFocusTrap(page, frameworkPrefixes);
97
+ if (trap)
98
+ findings.push(trap);
99
+ }
100
+ catch (err) {
101
+ const message = err instanceof Error ? err.message : String(err);
102
+ console.warn(`ngbr-a11y-report: focus-trap walk failed on ${label}: ${message}`);
103
+ }
104
+ }
52
105
  pages.push({ label, url: page.url(), findings });
53
106
  }
54
107
  catch (err) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngbracket/a11y-devtools",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Dev-only in-app accessibility auditing for Angular that maps each axe violation back to the component that rendered it — the attribution React overlay tools can't do.",
5
5
  "license": "MIT",
6
6
  "author": "Duncan Faulkner",