@ngbracket/a11y-devtools 0.5.0 → 0.6.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,34 @@
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.6.0
7
+
8
+ ### Added
9
+
10
+ - **Keyboard & Focus Mode — M1: the keyboard layer.** The first checks for the
11
+ ~2/3 of accessibility axe can't test — keyboard operability — attributed to the
12
+ owning component like everything else. Opt in with `keyboard: true` (provider /
13
+ `runA11yScan` / `scan` / `scanPages`) or `--keyboard` on the CLI.
14
+ - **Tab-order visualisation** (overlay): numbered badges at each tab stop plus a
15
+ connector path showing the order focus actually moves; a positive-`tabindex`
16
+ stop is flagged as a warning because it hijacks the natural order.
17
+ - **Keyboard findings** (`ngbr/*` rule ids, grouped and reported like axe
18
+ violations):
19
+ - `ngbr/unreachable-control` (serious) — an interactive element (ARIA role or a
20
+ runtime `click` listener) that isn't a native control and has no
21
+ `tabindex >= 0`, so it can't be reached by keyboard.
22
+ - `ngbr/click-without-key` (moderate, heuristic) — a focusable element with a
23
+ `(click)` handler but no keyboard handler, so Enter/Space may not activate it.
24
+ Read from `window.ng.getListeners`, a **runtime** signal a static template
25
+ lint can't see (e.g. a listener added via `hostDirectives`).
26
+ - `ngbr/tab-order-mismatch` (moderate, heuristic) — the tab path jumps against
27
+ the visual reading order. Needs real layout (report-mode / a real browser).
28
+ - New public API: `tabSequence`, `scanKeyboard`, `isTabbable`,
29
+ `isNativelyFocusable`, `resolvedTabIndex`, `visualOrderJumps`,
30
+ `resolveListenerEvents`, and the `TabStop` / `NgListener` types.
31
+ - **Honesty guardrail:** the heuristic findings are labelled "verify manually",
32
+ never reported as confirmed failures.
33
+
6
34
  ## 0.5.0
7
35
 
8
36
  ### Added
package/README.md CHANGED
@@ -18,7 +18,9 @@ Part of the `@ngbracket` Angular tooling family.
18
18
 
19
19
  Ships attribution — component **and** directive-level — + axe scan + grouped
20
20
  console reporter (with a summary line) + the dev-only provider + the visual in-app
21
- overlay (severity-coloured highlights, click-to-scroll).
21
+ overlay (severity-coloured highlights, click-to-scroll) + headless report mode +
22
+ **Keyboard & Focus Mode M1** (tab-order visualisation + keyboard-reachability
23
+ findings — the part of accessibility axe can't test).
22
24
 
23
25
  ## How the attribution works
24
26
 
@@ -63,6 +65,7 @@ provideA11yDevtools({
63
65
  debounceMs: 500, // quiet window after stabilization before scanning
64
66
  tags: ['wcag22aa'], // scope the ruleset; default = axe-core's full ruleset
65
67
  frameworkPrefixes: ['Nb', 'Mat', 'Cdk', 'Mdc'], // UI primitives to attribute past (default)
68
+ keyboard: true, // also run the keyboard layer (see below); default false
66
69
  });
67
70
  ```
68
71
 
@@ -152,6 +155,37 @@ owning component. When a flagged control is itself a third-party UI primitive
152
155
  (e.g. `<button nbButton>`), attribution walks past the primitive to the app
153
156
  component that placed it and notes the primitive as `(via …)`.
154
157
 
158
+ ## Keyboard & Focus Mode (the ~2/3 axe can't test)
159
+
160
+ axe covers the machine-testable third of WCAG. **Keyboard & Focus Mode** starts on
161
+ the rest — keyboard operability — still naming the component that owns each issue.
162
+ Turn it on with `keyboard: true` (provider / `runA11yScan` / `scan` / `scanPages`)
163
+ or `--keyboard` on the CLI. It adds:
164
+
165
+ - **Tab-order visualisation** (overlay): numbered badges at each tab stop and a
166
+ connector path showing the order focus actually moves. A positive-`tabindex` stop
167
+ is coloured as a warning, because it hijacks the natural order.
168
+ - **Keyboard findings**, grouped and reported exactly like the axe violations:
169
+ - `ngbr/unreachable-control` — an interactive element (an ARIA role, or a runtime
170
+ `click` listener) that isn't a native control and has no `tabindex >= 0`, so the
171
+ keyboard can't reach it.
172
+ - `ngbr/click-without-key` — a focusable element with a `(click)` handler but no
173
+ keyboard handler, so Enter/Space may not activate it. This is read from
174
+ `window.ng.getListeners` — a **runtime** signal a static template lint can't see
175
+ (e.g. a handler added via `hostDirectives`).
176
+ - `ngbr/tab-order-mismatch` — the tab path jumps against the visual reading order
177
+ (needs real layout, so it fires in report-mode / a real browser).
178
+
179
+ ```bash
180
+ # include the keyboard layer in a report-mode run
181
+ npx ngbr-a11y-report --base http://localhost:4200 --route / --keyboard
182
+ ```
183
+
184
+ **Honesty guardrail:** `click-without-key` and `tab-order-mismatch` are
185
+ *heuristics* — labelled "verify manually", never reported as confirmed failures.
186
+ (Next: M2 — an accessibility-tree preview, framed as a *computed approximation*,
187
+ never "what a screen reader says".)
188
+
155
189
  ## What it checks (and what it can't)
156
190
 
157
191
  Under the hood this is [axe-core](https://github.com/dequelabs/axe-core) — the
@@ -191,11 +225,14 @@ npm run build # tsc -> dist/ (ESM + .d.ts)
191
225
 
192
226
  ## Roadmap
193
227
 
194
- - Configurable framework-primitive prefixes (PrimeNG, Clarity, Ionic, …).
228
+ - Keyboard & Focus Mode **M2** — accessibility-tree preview (role + accessible
229
+ name + state as you Tab), framed as a *computed approximation*.
230
+ - Keyboard & Focus Mode **M3** — focus-trap *candidate* detection.
195
231
  - HTML report + baseline/diff mode for CI.
196
232
  - Per-component filtering and a violation-count badge.
197
233
 
198
234
  Done: component attribution (nearest app-owned, walking past UI primitives) ·
199
- directive / `hostDirectives` attribution · axe scan · grouped console reporter ·
200
- dev-only provider · in-app overlay · headless report mode (CLI + `./report`) ·
201
- CI prod-weight guard.
235
+ directive / `hostDirectives` attribution · configurable framework prefixes · axe
236
+ scan · grouped console reporter · dev-only provider · in-app overlay · headless
237
+ report mode (CLI + `./report`) · **Keyboard & Focus Mode M1** (tab-order viz +
238
+ keyboard-reachability findings) · CI prod-weight guard.
@@ -23,6 +23,9 @@ Options:
23
23
  --no-skip-primitives
24
24
  Attribute to the immediate owner (skip nothing) — use when
25
25
  scanning a component library's own code
26
+ --keyboard Also run the keyboard layer: heuristic ngbr/* findings for
27
+ keyboard-unreachable controls, click-without-keyboard
28
+ handlers, and visual-vs-tab-order mismatches
26
29
  --headed Launch a visible browser (debugging)
27
30
  -h, --help Show this help
28
31
  `;
@@ -46,6 +49,7 @@ function parseArgs(argv) {
46
49
  opts.frameworkPrefixes = next().split(',').map((s) => s.trim()).filter(Boolean);
47
50
  break;
48
51
  case '--no-skip-primitives': opts.frameworkPrefixes = []; break;
52
+ case '--keyboard': opts.keyboard = true; break;
49
53
  case '--headed': opts.headed = true; break;
50
54
  case '-h': case '--help': opts.help = true; break;
51
55
  default: console.error(`Unknown argument: ${arg}\n`); opts.help = true;
@@ -68,6 +72,7 @@ const report = await scanPages({
68
72
  waitMs: opts.wait,
69
73
  headed: opts.headed,
70
74
  frameworkPrefixes: opts.frameworkPrefixes,
75
+ keyboard: opts.keyboard,
71
76
  });
72
77
 
73
78
  const allFindings = report.pages.flatMap((p) => p.findings);
@@ -14,7 +14,29 @@ export interface NgDebugGlobal {
14
14
  getComponent(element: Element): unknown;
15
15
  getOwningComponent(element: Element | object): unknown;
16
16
  getDirectives(element: Element | object): unknown[];
17
+ /**
18
+ * Listeners Angular bound to a node — template `(event)` bindings plus
19
+ * `@HostListener`s. Present on the dev global alongside the other helpers; the
20
+ * keyboard scan uses it to see, at runtime, which elements have a `click`
21
+ * handler but no keyboard handler — a case a static template lint can't catch
22
+ * (e.g. a listener added by a directive via `hostDirectives`).
23
+ */
24
+ getListeners?(element: Element): NgListener[];
17
25
  }
26
+ /** Shape of an entry returned by `window.ng.getListeners`. */
27
+ export interface NgListener {
28
+ name: string;
29
+ type?: 'dom' | 'output';
30
+ callback?: unknown;
31
+ useCapture?: boolean;
32
+ }
33
+ /**
34
+ * The DOM event names Angular has a listener bound for on `node` (template
35
+ * `(event)` bindings and `@HostListener`s), lowercased and de-duplicated. Empty
36
+ * when the debug global is absent (prod) or the node has none. Output/`@Output`
37
+ * emitters are excluded — only real DOM events matter for keyboard operability.
38
+ */
39
+ export declare function resolveListenerEvents(node: Element): string[];
18
40
  export declare function ngDebug(): NgDebugGlobal | undefined;
19
41
  /**
20
42
  * Default component-name prefixes treated as third-party UI primitives (Nebular
@@ -1,3 +1,29 @@
1
+ /**
2
+ * The DOM event names Angular has a listener bound for on `node` (template
3
+ * `(event)` bindings and `@HostListener`s), lowercased and de-duplicated. Empty
4
+ * when the debug global is absent (prod) or the node has none. Output/`@Output`
5
+ * emitters are excluded — only real DOM events matter for keyboard operability.
6
+ */
7
+ export function resolveListenerEvents(node) {
8
+ const ng = ngDebug();
9
+ if (typeof ng?.getListeners !== 'function')
10
+ return [];
11
+ let listeners;
12
+ try {
13
+ listeners = ng.getListeners(node) ?? [];
14
+ }
15
+ catch {
16
+ return []; // node isn't part of a live view
17
+ }
18
+ const events = new Set();
19
+ for (const listener of listeners) {
20
+ if (listener?.type === 'output')
21
+ continue;
22
+ if (typeof listener?.name === 'string')
23
+ events.add(listener.name.toLowerCase());
24
+ }
25
+ return [...events];
26
+ }
1
27
  export function ngDebug() {
2
28
  return globalThis.ng;
3
29
  }
package/dist/index.d.ts CHANGED
@@ -2,5 +2,7 @@ export { provideA11yDevtools, type A11yDevtoolsOptions } from './provider.js';
2
2
  export { runA11yScan, type RunOptions } from './runner.js';
3
3
  export { scan, type A11yFinding, type Impact, type ScanOptions } from './scan.js';
4
4
  export { logFindings, type Logger } from './report.js';
5
- export { resolveOwningComponentName, resolveComponentPath, appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, ngDebug, type NgDebugGlobal, } from './attribution.js';
5
+ export { resolveOwningComponentName, resolveComponentPath, appComponentFromPath, resolveListenerEvents, DEFAULT_FRAMEWORK_PREFIXES, ngDebug, type NgDebugGlobal, type NgListener, } from './attribution.js';
6
+ export { tabSequence, isTabbable, isNativelyFocusable, resolvedTabIndex, visualOrderJumps, type TabStop, type TabSequenceOptions, } from './keyboard/tab-sequence.js';
7
+ export { scanKeyboard, type KeyboardScanOptions } from './keyboard/keyboard-scan.js';
6
8
  export { createOverlay, OVERLAY_ATTR, OVERLAY_EXCLUDE_SELECTOR, type A11yOverlay, type OverlayOptions, } from './overlay.js';
package/dist/index.js CHANGED
@@ -2,5 +2,7 @@ export { provideA11yDevtools } from './provider.js';
2
2
  export { runA11yScan } from './runner.js';
3
3
  export { scan } from './scan.js';
4
4
  export { logFindings } from './report.js';
5
- export { resolveOwningComponentName, resolveComponentPath, appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, ngDebug, } from './attribution.js';
5
+ export { resolveOwningComponentName, resolveComponentPath, appComponentFromPath, resolveListenerEvents, DEFAULT_FRAMEWORK_PREFIXES, ngDebug, } from './attribution.js';
6
+ export { tabSequence, isTabbable, isNativelyFocusable, resolvedTabIndex, visualOrderJumps, } from './keyboard/tab-sequence.js';
7
+ export { scanKeyboard } from './keyboard/keyboard-scan.js';
6
8
  export { createOverlay, OVERLAY_ATTR, OVERLAY_EXCLUDE_SELECTOR, } from './overlay.js';
@@ -12667,7 +12667,7 @@
12667
12667
  isMultiline: function isMultiline() {
12668
12668
  return _isMultiline;
12669
12669
  },
12670
- isNativelyFocusable: function isNativelyFocusable2() {
12670
+ isNativelyFocusable: function isNativelyFocusable3() {
12671
12671
  return is_natively_focusable_default;
12672
12672
  },
12673
12673
  isNode: function isNode2() {
@@ -16086,7 +16086,7 @@
16086
16086
  });
16087
16087
  return tabbableElements;
16088
16088
  }
16089
- function isNativelyFocusable(el) {
16089
+ function isNativelyFocusable2(el) {
16090
16090
  var _nodeLookup8 = _nodeLookup(el), vNode = _nodeLookup8.vNode;
16091
16091
  if (!vNode || focus_disabled_default(vNode)) {
16092
16092
  return false;
@@ -16110,7 +16110,7 @@
16110
16110
  }
16111
16111
  return false;
16112
16112
  }
16113
- var is_natively_focusable_default = isNativelyFocusable;
16113
+ var is_natively_focusable_default = isNativelyFocusable2;
16114
16114
  function _isFocusable(el) {
16115
16115
  var _nodeLookup9 = _nodeLookup(el), vNode = _nodeLookup9.vNode;
16116
16116
  if (vNode.props.nodeType !== 1) {
@@ -25398,7 +25398,7 @@
25398
25398
  isAriaTextbox: function isAriaTextbox2() {
25399
25399
  return is_aria_textbox_default;
25400
25400
  },
25401
- isDisabled: function isDisabled2() {
25401
+ isDisabled: function isDisabled3() {
25402
25402
  return is_disabled_default;
25403
25403
  },
25404
25404
  isNativeSelect: function isNativeSelect2() {
@@ -25409,7 +25409,7 @@
25409
25409
  }
25410
25410
  });
25411
25411
  var disabledNodeNames = ["fieldset", "button", "select", "input", "textarea"];
25412
- function isDisabled(virtualNode) {
25412
+ function isDisabled2(virtualNode) {
25413
25413
  var disabledState = virtualNode._isDisabled;
25414
25414
  if (typeof disabledState === "boolean") {
25415
25415
  return disabledState;
@@ -25421,14 +25421,14 @@
25421
25421
  } else if (ariaDisabled) {
25422
25422
  disabledState = ariaDisabled === "true";
25423
25423
  } else if (virtualNode.parent) {
25424
- disabledState = isDisabled(virtualNode.parent);
25424
+ disabledState = isDisabled2(virtualNode.parent);
25425
25425
  } else {
25426
25426
  disabledState = false;
25427
25427
  }
25428
25428
  virtualNode._isDisabled = disabledState;
25429
25429
  return disabledState;
25430
25430
  }
25431
- var is_disabled_default = isDisabled;
25431
+ var is_disabled_default = isDisabled2;
25432
25432
  function identicalLinksSamePurposeEvaluate(node, options, virtualNode) {
25433
25433
  var accText = text_exports.accessibleTextVirtual(virtualNode);
25434
25434
  var name = text_exports.sanitize(text_exports.removeUnicode(accText, {
@@ -34133,6 +34133,25 @@
34133
34133
  });
34134
34134
 
34135
34135
  // dist/attribution.js
34136
+ function resolveListenerEvents(node) {
34137
+ const ng = ngDebug();
34138
+ if (typeof ng?.getListeners !== "function")
34139
+ return [];
34140
+ let listeners;
34141
+ try {
34142
+ listeners = ng.getListeners(node) ?? [];
34143
+ } catch {
34144
+ return [];
34145
+ }
34146
+ const events = /* @__PURE__ */ new Set();
34147
+ for (const listener of listeners) {
34148
+ if (listener?.type === "output")
34149
+ continue;
34150
+ if (typeof listener?.name === "string")
34151
+ events.add(listener.name.toLowerCase());
34152
+ }
34153
+ return [...events];
34154
+ }
34136
34155
  function ngDebug() {
34137
34156
  return globalThis.ng;
34138
34157
  }
@@ -34204,6 +34223,9 @@
34204
34223
  }
34205
34224
 
34206
34225
  // dist/overlay.js
34226
+ var SVG_NS = "http://www.w3.org/2000/svg";
34227
+ var TAB_ORDER_COLOR = "#0b8f8f";
34228
+ var TAB_ORDER_WARN_COLOR = "#e8710a";
34207
34229
  var OVERLAY_ATTR = "data-ngb-a11y-overlay";
34208
34230
  var OVERLAY_EXCLUDE_SELECTOR = `[${OVERLAY_ATTR}]`;
34209
34231
  var IMPACT_COLOR = {
@@ -34228,12 +34250,42 @@
34228
34250
  zIndex: "2147483646"
34229
34251
  });
34230
34252
  doc.body.appendChild(container);
34253
+ const svg = doc.createElementNS(SVG_NS, "svg");
34254
+ svg.setAttribute(OVERLAY_ATTR, "");
34255
+ Object.assign(svg.style, {
34256
+ position: "fixed",
34257
+ inset: "0",
34258
+ width: "100%",
34259
+ height: "100%",
34260
+ pointerEvents: "none",
34261
+ overflow: "visible"
34262
+ });
34263
+ const connector = doc.createElementNS(SVG_NS, "polyline");
34264
+ connector.setAttribute("fill", "none");
34265
+ connector.setAttribute("stroke", TAB_ORDER_COLOR);
34266
+ connector.setAttribute("stroke-width", "2");
34267
+ connector.setAttribute("stroke-dasharray", "4 3");
34268
+ connector.setAttribute("opacity", "0.7");
34269
+ svg.appendChild(connector);
34270
+ container.appendChild(svg);
34231
34271
  let highlights = [];
34272
+ let tabBadges = [];
34232
34273
  const reposition = () => {
34233
34274
  for (const { target, box } of highlights) {
34234
34275
  positionBox(box, target);
34235
34276
  }
34277
+ repositionTabOrder();
34236
34278
  };
34279
+ function repositionTabOrder() {
34280
+ const points = [];
34281
+ for (const { target, badge } of tabBadges) {
34282
+ const rect = target.getBoundingClientRect();
34283
+ badge.style.top = `${rect.top}px`;
34284
+ badge.style.left = `${rect.left}px`;
34285
+ points.push(`${rect.left + rect.width / 2},${rect.top + rect.height / 2}`);
34286
+ }
34287
+ connector.setAttribute("points", points.join(" "));
34288
+ }
34237
34289
  const raf = doc.defaultView?.requestAnimationFrame?.bind(doc.defaultView);
34238
34290
  let scheduled = false;
34239
34291
  const onViewportChange = () => {
@@ -34270,13 +34322,58 @@
34270
34322
  highlights.push({ finding, target, box });
34271
34323
  }
34272
34324
  }
34325
+ function clearTabOrder() {
34326
+ for (const { badge } of tabBadges)
34327
+ badge.remove();
34328
+ tabBadges = [];
34329
+ connector.setAttribute("points", "");
34330
+ }
34331
+ function renderTabOrder(stops) {
34332
+ clearTabOrder();
34333
+ for (const stop of stops) {
34334
+ const target = stop.element;
34335
+ if (!target.isConnected)
34336
+ continue;
34337
+ const badge = buildBadge(doc, stop);
34338
+ container.appendChild(badge);
34339
+ tabBadges.push({ stop, target, badge });
34340
+ }
34341
+ repositionTabOrder();
34342
+ }
34273
34343
  function destroy() {
34274
34344
  clear();
34345
+ clearTabOrder();
34275
34346
  win?.removeEventListener("scroll", onViewportChange, { capture: true });
34276
34347
  win?.removeEventListener("resize", onViewportChange);
34277
34348
  container.remove();
34278
34349
  }
34279
- return { render, clear, destroy };
34350
+ return { render, renderTabOrder, clear, clearTabOrder, destroy };
34351
+ }
34352
+ function buildBadge(doc, stop) {
34353
+ const color = stop.positive ? TAB_ORDER_WARN_COLOR : TAB_ORDER_COLOR;
34354
+ const badge = doc.createElement("div");
34355
+ badge.setAttribute("data-ngb-tab-order", String(stop.order));
34356
+ const owner = stop.component ? ` \xB7 ${stop.component}` : "";
34357
+ const ti = stop.positive ? ` \xB7 tabindex=${stop.tabindex} (hijacks order)` : "";
34358
+ badge.title = `Tab stop ${stop.order}${owner}${ti}`;
34359
+ badge.textContent = String(stop.order);
34360
+ Object.assign(badge.style, {
34361
+ position: "fixed",
34362
+ transform: "translate(-50%, -50%)",
34363
+ minWidth: "16px",
34364
+ height: "16px",
34365
+ padding: "0 3px",
34366
+ boxSizing: "border-box",
34367
+ borderRadius: "8px",
34368
+ font: "10px/16px ui-monospace, monospace",
34369
+ fontWeight: "700",
34370
+ textAlign: "center",
34371
+ color: "#fff",
34372
+ background: color,
34373
+ border: "1px solid rgba(255,255,255,0.85)",
34374
+ pointerEvents: "none"
34375
+ });
34376
+ return badge;
34280
34377
  }
34281
34378
  function resolveTarget(doc, target) {
34282
34379
  try {
@@ -34334,6 +34431,212 @@
34334
34431
  }, 600);
34335
34432
  }
34336
34433
 
34434
+ // dist/keyboard/tab-sequence.js
34435
+ var FOCUSABLE_SELECTOR = [
34436
+ "a[href]",
34437
+ "area[href]",
34438
+ "button",
34439
+ "input",
34440
+ "select",
34441
+ "textarea",
34442
+ "audio[controls]",
34443
+ "video[controls]",
34444
+ "summary",
34445
+ "iframe",
34446
+ "object",
34447
+ "embed",
34448
+ "[contenteditable]",
34449
+ "[tabindex]"
34450
+ ].join(",");
34451
+ function nativeTabIndex(element) {
34452
+ return isNativelyFocusable(element) ? 0 : -1;
34453
+ }
34454
+ function isNativelyFocusable(element) {
34455
+ const tag = element.tagName.toLowerCase();
34456
+ switch (tag) {
34457
+ case "a":
34458
+ case "area":
34459
+ return element.hasAttribute("href");
34460
+ case "button":
34461
+ case "select":
34462
+ case "textarea":
34463
+ return true;
34464
+ case "input":
34465
+ return element.getAttribute("type")?.toLowerCase() !== "hidden";
34466
+ case "summary":
34467
+ return true;
34468
+ case "iframe":
34469
+ case "object":
34470
+ case "embed":
34471
+ return true;
34472
+ case "audio":
34473
+ case "video":
34474
+ return element.hasAttribute("controls");
34475
+ }
34476
+ const editable = element.getAttribute("contenteditable");
34477
+ return editable !== null && editable !== "false";
34478
+ }
34479
+ function resolvedTabIndex(element) {
34480
+ const attr = element.getAttribute("tabindex");
34481
+ if (attr === null)
34482
+ return nativeTabIndex(element);
34483
+ const parsed = Number.parseInt(attr, 10);
34484
+ return Number.isNaN(parsed) ? nativeTabIndex(element) : parsed;
34485
+ }
34486
+ function isDisabled(element) {
34487
+ if ("disabled" in element && element.disabled)
34488
+ return true;
34489
+ return element.closest("fieldset[disabled]") !== null && element.closest("legend") === null;
34490
+ }
34491
+ function isStructurallyHidden(element) {
34492
+ if (element.closest("[inert]") || element.closest("[hidden]"))
34493
+ return true;
34494
+ const closedDetails = element.closest("details:not([open])");
34495
+ return closedDetails !== null && element.closest("summary") === null && element !== closedDetails;
34496
+ }
34497
+ function defaultIsVisible(element) {
34498
+ const view = element.ownerDocument?.defaultView;
34499
+ if (!view?.getComputedStyle)
34500
+ return true;
34501
+ for (let node = element; node; node = node.parentElement) {
34502
+ const style = view.getComputedStyle(node);
34503
+ if (style.display === "none")
34504
+ return false;
34505
+ if (style.visibility === "hidden" || style.visibility === "collapse")
34506
+ return false;
34507
+ }
34508
+ return true;
34509
+ }
34510
+ function isTabbable(element, isVisible = defaultIsVisible) {
34511
+ if (resolvedTabIndex(element) < 0)
34512
+ return false;
34513
+ if (isDisabled(element))
34514
+ return false;
34515
+ if (isStructurallyHidden(element))
34516
+ return false;
34517
+ const editable = element.getAttribute("contenteditable");
34518
+ if (editable === "false" && !isNativelyFocusable(element) && !element.hasAttribute("tabindex")) {
34519
+ return false;
34520
+ }
34521
+ return isVisible(element);
34522
+ }
34523
+ function tabSequence(root = document, options = {}) {
34524
+ const isVisible = options.isVisible ?? defaultIsVisible;
34525
+ const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
34526
+ const candidates = [...root.querySelectorAll(FOCUSABLE_SELECTOR)].filter((el) => isTabbable(el, isVisible));
34527
+ const withMeta = candidates.map((element, domIndex) => ({
34528
+ element,
34529
+ domIndex,
34530
+ tabindex: resolvedTabIndex(element),
34531
+ positive: /^\d+$/.test(element.getAttribute("tabindex") ?? "") && resolvedTabIndex(element) > 0
34532
+ }));
34533
+ const positives = withMeta.filter((m) => m.tabindex > 0).sort((a, b) => a.tabindex - b.tabindex || a.domIndex - b.domIndex);
34534
+ const zeros = withMeta.filter((m) => m.tabindex === 0);
34535
+ return [...positives, ...zeros].map((m, i) => {
34536
+ const componentPath = resolveComponentPath(m.element);
34537
+ return {
34538
+ element: m.element,
34539
+ order: i + 1,
34540
+ tabindex: m.tabindex,
34541
+ positive: m.positive,
34542
+ component: appComponentFromPath(componentPath, prefixes),
34543
+ componentPath
34544
+ };
34545
+ });
34546
+ }
34547
+ function visualOrderJumps(stops, getRect = (el) => el.getBoundingClientRect(), rowThreshold = 8) {
34548
+ const jumps = [];
34549
+ for (let i = 1; i < stops.length; i++) {
34550
+ const prev = getRect(stops[i - 1].element);
34551
+ const curr = getRect(stops[i].element);
34552
+ const movedUp = curr.top < prev.top - rowThreshold;
34553
+ const sameRowMovedLeft = Math.abs(curr.top - prev.top) <= rowThreshold && curr.left < prev.left - rowThreshold;
34554
+ if (movedUp || sameRowMovedLeft)
34555
+ jumps.push(i);
34556
+ }
34557
+ return jumps;
34558
+ }
34559
+
34560
+ // dist/keyboard/keyboard-scan.js
34561
+ var INTERACTIVE_ROLES = /* @__PURE__ */ new Set([
34562
+ "button",
34563
+ "link",
34564
+ "menuitem",
34565
+ "menuitemcheckbox",
34566
+ "menuitemradio",
34567
+ "tab",
34568
+ "switch",
34569
+ "checkbox",
34570
+ "radio",
34571
+ "option",
34572
+ "slider",
34573
+ "spinbutton",
34574
+ "combobox",
34575
+ "textbox",
34576
+ "searchbox",
34577
+ "treeitem"
34578
+ ]);
34579
+ var KEY_EVENTS = ["keydown", "keyup", "keypress"];
34580
+ var UNDERSTANDING = "https://www.w3.org/WAI/WCAG22/Understanding";
34581
+ var KEYBOARD_URL = `${UNDERSTANDING}/keyboard.html`;
34582
+ var FOCUS_ORDER_URL = `${UNDERSTANDING}/focus-order.html`;
34583
+ function shortSelector(element) {
34584
+ const tag = element.tagName.toLowerCase();
34585
+ if (element.id)
34586
+ return `${tag}#${element.id}`;
34587
+ const classes = (element.getAttribute("class") ?? "").trim().split(/\s+/).filter(Boolean).slice(0, 2);
34588
+ return classes.length ? `${tag}.${classes.join(".")}` : tag;
34589
+ }
34590
+ function shortHtml(element) {
34591
+ const html = element.outerHTML ?? "";
34592
+ return html.length > 160 ? `${html.slice(0, 159)}\u2026` : html;
34593
+ }
34594
+ function scanKeyboard(root = document, options = {}) {
34595
+ const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
34596
+ const isVisible = options.isVisible;
34597
+ const findings = [];
34598
+ const make = (element, id, impact, help, helpUrl) => {
34599
+ const componentPath = resolveComponentPath(element);
34600
+ return {
34601
+ id,
34602
+ impact,
34603
+ help,
34604
+ helpUrl,
34605
+ component: appComponentFromPath(componentPath, prefixes),
34606
+ componentPath,
34607
+ directives: resolveDirectiveNames(element),
34608
+ target: shortSelector(element),
34609
+ html: shortHtml(element)
34610
+ };
34611
+ };
34612
+ for (const element of root.querySelectorAll("*")) {
34613
+ if (isNativelyFocusable(element))
34614
+ continue;
34615
+ const role = element.getAttribute("role")?.toLowerCase() ?? "";
34616
+ const events = resolveListenerEvents(element);
34617
+ const hasClick = events.includes("click");
34618
+ const interactiveByRole = INTERACTIVE_ROLES.has(role);
34619
+ if (!hasClick && !interactiveByRole)
34620
+ continue;
34621
+ const focusable = isTabbable(element, isVisible);
34622
+ if (!focusable) {
34623
+ const reason = interactiveByRole ? `has role="${role}"` : "has a click handler";
34624
+ 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));
34625
+ continue;
34626
+ }
34627
+ const hasKey = events.some((e) => KEY_EVENTS.includes(e));
34628
+ if (hasClick && !hasKey) {
34629
+ 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));
34630
+ }
34631
+ }
34632
+ const stops = tabSequence(root, { frameworkPrefixes: prefixes, isVisible });
34633
+ for (const jump of visualOrderJumps(stops)) {
34634
+ const stop = stops[jump];
34635
+ 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));
34636
+ }
34637
+ return findings;
34638
+ }
34639
+
34337
34640
  // dist/scan.js
34338
34641
  var runChain = Promise.resolve();
34339
34642
  function scan(root = document, options, scanOptions) {
@@ -34371,6 +34674,9 @@
34371
34674
  });
34372
34675
  }
34373
34676
  }
34677
+ if (scanOptions?.keyboard) {
34678
+ findings.push(...scanKeyboard(root, { frameworkPrefixes }));
34679
+ }
34374
34680
  return findings;
34375
34681
  }
34376
34682
 
@@ -0,0 +1,14 @@
1
+ import type { A11yFinding } from '../scan.js';
2
+ export interface KeyboardScanOptions {
3
+ /** UI-primitive prefixes to walk past during attribution; see the scan options. */
4
+ frameworkPrefixes?: readonly string[];
5
+ /** Visibility predicate override (tests); see {@link tabSequence}. */
6
+ isVisible?: (element: Element) => boolean;
7
+ }
8
+ /**
9
+ * Scan `root` for keyboard-operability problems and return them as findings.
10
+ * Runs entirely in the page (needs the live `window.ng` for listeners and
11
+ * attribution), so it's a no-op — empty result — in production where that global
12
+ * is absent.
13
+ */
14
+ export declare function scanKeyboard(root?: ParentNode, options?: KeyboardScanOptions): A11yFinding[];
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The keyboard layer, part B: findings axe can't produce, because they depend on
3
+ * runtime state axe never sees — which elements actually have a DOM `click`
4
+ * listener (read from Angular's `window.ng.getListeners`) and whether the tab
5
+ * path matches the visual order. These are emitted as {@link A11yFinding}s with
6
+ * synthetic `ngbr/*` rule ids, so they flow through the same grouped console
7
+ * output, overlay, and report as the axe violations — attributed to the owning
8
+ * component like everything else.
9
+ *
10
+ * Honesty guardrail: these are *heuristics*, not axe rules. `click-without-key`
11
+ * and `tab-order-mismatch` are flagged as candidates to verify by hand, never as
12
+ * confirmed failures.
13
+ */
14
+ import { appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, resolveComponentPath, resolveDirectiveNames, resolveListenerEvents, } from '../attribution.js';
15
+ import { isNativelyFocusable, isTabbable, tabSequence, visualOrderJumps, } from './tab-sequence.js';
16
+ /** WAI-ARIA roles that make a non-native element behave as an interactive control. */
17
+ const INTERACTIVE_ROLES = new Set([
18
+ 'button',
19
+ 'link',
20
+ 'menuitem',
21
+ 'menuitemcheckbox',
22
+ 'menuitemradio',
23
+ 'tab',
24
+ 'switch',
25
+ 'checkbox',
26
+ 'radio',
27
+ 'option',
28
+ 'slider',
29
+ 'spinbutton',
30
+ 'combobox',
31
+ 'textbox',
32
+ 'searchbox',
33
+ 'treeitem',
34
+ ]);
35
+ const KEY_EVENTS = ['keydown', 'keyup', 'keypress'];
36
+ const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';
37
+ const KEYBOARD_URL = `${UNDERSTANDING}/keyboard.html`;
38
+ const FOCUS_ORDER_URL = `${UNDERSTANDING}/focus-order.html`;
39
+ /** A short, human CSS-ish selector for our own findings (not an axe target). */
40
+ function shortSelector(element) {
41
+ const tag = element.tagName.toLowerCase();
42
+ if (element.id)
43
+ return `${tag}#${element.id}`;
44
+ const classes = (element.getAttribute('class') ?? '')
45
+ .trim()
46
+ .split(/\s+/)
47
+ .filter(Boolean)
48
+ .slice(0, 2);
49
+ return classes.length ? `${tag}.${classes.join('.')}` : tag;
50
+ }
51
+ function shortHtml(element) {
52
+ const html = element.outerHTML ?? '';
53
+ return html.length > 160 ? `${html.slice(0, 159)}…` : html;
54
+ }
55
+ /**
56
+ * Scan `root` for keyboard-operability problems and return them as findings.
57
+ * Runs entirely in the page (needs the live `window.ng` for listeners and
58
+ * attribution), so it's a no-op — empty result — in production where that global
59
+ * is absent.
60
+ */
61
+ export function scanKeyboard(root = document, options = {}) {
62
+ const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
63
+ const isVisible = options.isVisible;
64
+ const findings = [];
65
+ const make = (element, id, impact, help, helpUrl) => {
66
+ const componentPath = resolveComponentPath(element);
67
+ return {
68
+ id,
69
+ impact,
70
+ help,
71
+ helpUrl,
72
+ component: appComponentFromPath(componentPath, prefixes),
73
+ componentPath,
74
+ directives: resolveDirectiveNames(element),
75
+ target: shortSelector(element),
76
+ html: shortHtml(element),
77
+ };
78
+ };
79
+ for (const element of root.querySelectorAll('*')) {
80
+ // Native controls are keyboard-reachable and activate on Enter/Space on their
81
+ // own, so they can't be the subject of either finding — skip them outright.
82
+ if (isNativelyFocusable(element))
83
+ continue;
84
+ const role = element.getAttribute('role')?.toLowerCase() ?? '';
85
+ const events = resolveListenerEvents(element);
86
+ const hasClick = events.includes('click');
87
+ const interactiveByRole = INTERACTIVE_ROLES.has(role);
88
+ if (!hasClick && !interactiveByRole)
89
+ continue; // nothing marks this as interactive
90
+ const focusable = isTabbable(element, isVisible);
91
+ if (!focusable) {
92
+ const reason = interactiveByRole ? `has role="${role}"` : 'has a click handler';
93
+ findings.push(make(element, 'ngbr/unreachable-control', 'serious', `Interactive element isn't reachable by keyboard — it ${reason} but is not a ` +
94
+ `native control and has no tabindex >= 0, so keyboard and screen-reader users ` +
95
+ `can't focus it. Add tabindex="0" (and a role, if missing), or use a <button>/<a>.`, KEYBOARD_URL));
96
+ continue; // don't also report a weaker click-without-key on the same node
97
+ }
98
+ // Focusable, but a bare (click) never fires on Enter/Space the way a native
99
+ // button does — so a keyboard user can reach it and still not activate it.
100
+ const hasKey = events.some((e) => KEY_EVENTS.includes(e));
101
+ if (hasClick && !hasKey) {
102
+ findings.push(make(element, 'ngbr/click-without-key', 'moderate', `Possible keyboard trap: this element has a (click) handler but no keyboard ` +
103
+ `handler (keydown/keyup) and isn't a native button/link, so Enter/Space may not ` +
104
+ `activate it. Verify by hand, then add a key handler or use a <button>.`, KEYBOARD_URL));
105
+ }
106
+ }
107
+ // Visual-vs-tab-order mismatch: a heuristic over the resolved sequence. Needs
108
+ // real layout, so it no-ops where getBoundingClientRect returns zeros (jsdom).
109
+ const stops = tabSequence(root, { frameworkPrefixes: prefixes, isVisible });
110
+ for (const jump of visualOrderJumps(stops)) {
111
+ const stop = stops[jump];
112
+ findings.push(make(stop.element, 'ngbr/tab-order-mismatch', 'moderate', `Possible tab-order mismatch: Tab reaches this control (stop ${stop.order}) after ` +
113
+ `one that sits below or to the right of it, so focus jumps against the visual ` +
114
+ `reading order. Heuristic — verify the order makes sense for a sighted keyboard user.`, FOCUS_ORDER_URL));
115
+ }
116
+ return findings;
117
+ }
@@ -0,0 +1,58 @@
1
+ /** One element in the resolved tab sequence, with its owning component. */
2
+ export interface TabStop {
3
+ element: Element;
4
+ /** 1-based position in the resolved tab order. */
5
+ order: number;
6
+ /** Resolved tabindex: 0 for a native default or explicit `tabindex="0"`, else the positive value. */
7
+ tabindex: number;
8
+ /** True when an explicit positive `tabindex` puts this stop out of DOM order. */
9
+ positive: boolean;
10
+ /** Nearest app-owned component (walks past UI primitives); null in prod. */
11
+ component: string | null;
12
+ /** Owning components from the node up to the root, nearest first; [] in prod. */
13
+ componentPath: string[];
14
+ }
15
+ export interface TabSequenceOptions {
16
+ /** UI-primitive prefixes to walk past during attribution; see the scan options. */
17
+ frameworkPrefixes?: readonly string[];
18
+ /**
19
+ * Visibility predicate override — mainly for tests, where jsdom reports no
20
+ * layout. Defaults to a computed-style + `inert`/`hidden`/`<details>` check.
21
+ */
22
+ isVisible?: (element: Element) => boolean;
23
+ }
24
+ /**
25
+ * True when the element takes focus without an explicit `tabindex` — a link with
26
+ * an href, a form control, a `<summary>`, an editing host, and the embedded
27
+ * document elements. Disabled/hidden state is handled separately.
28
+ */
29
+ export declare function isNativelyFocusable(element: Element): boolean;
30
+ /**
31
+ * The tabindex the browser will use: the parsed attribute when present and
32
+ * numeric, otherwise the native default. A non-numeric `tabindex` (e.g.
33
+ * `tabindex="foo"`) is ignored by browsers, so it falls back to the native value.
34
+ */
35
+ export declare function resolvedTabIndex(element: Element): number;
36
+ /**
37
+ * True when `element` participates in sequential keyboard navigation: it's
38
+ * focusable, has a resolved `tabindex >= 0`, and is neither disabled nor hidden.
39
+ * `isVisible` overrides only the layout (computed-style) part of the check.
40
+ */
41
+ export declare function isTabbable(element: Element, isVisible?: (el: Element) => boolean): boolean;
42
+ /**
43
+ * The resolved tab order within `root`: positive-tabindex stops first (ascending,
44
+ * ties in DOM order), then `tabindex=0`/native stops in DOM order — the order a
45
+ * browser actually moves focus. Each stop carries its owning component.
46
+ */
47
+ export declare function tabSequence(root?: ParentNode, options?: TabSequenceOptions): TabStop[];
48
+ /**
49
+ * Indices (0-based, into the sequence) where the tab path jumps *backward against
50
+ * reading order* — a stop that sits clearly above, or well to the left on the
51
+ * same row, of the stop before it. A heuristic signal that DOM/tabindex order
52
+ * has drifted from the visual order a sighted keyboard user expects; always
53
+ * "verify manually". `getRect` is injectable for tests.
54
+ */
55
+ export declare function visualOrderJumps(stops: readonly TabStop[], getRect?: (el: Element) => {
56
+ top: number;
57
+ left: number;
58
+ }, rowThreshold?: number): number[];
@@ -0,0 +1,178 @@
1
+ /**
2
+ * The keyboard layer, part A: compute the order in which Tab moves through a
3
+ * page. This is the ~2/3 of accessibility axe can't test — keyboard operability
4
+ * — and, like the axe findings, every stop is attributed to the component that
5
+ * rendered it.
6
+ *
7
+ * The tabbable set and ordering mirror the browser's own algorithm (and the
8
+ * well-known `tabbable` element definition), implemented here with no runtime
9
+ * dependency: elements with a positive `tabindex` come first in ascending order
10
+ * (the anti-pattern that hijacks focus order), then everything with `tabindex=0`
11
+ * or a native default in DOM order.
12
+ */
13
+ import { appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, resolveComponentPath, } from '../attribution.js';
14
+ /** Elements that can hold focus and thus may appear in the tab order. */
15
+ const FOCUSABLE_SELECTOR = [
16
+ 'a[href]',
17
+ 'area[href]',
18
+ 'button',
19
+ 'input',
20
+ 'select',
21
+ 'textarea',
22
+ 'audio[controls]',
23
+ 'video[controls]',
24
+ 'summary',
25
+ 'iframe',
26
+ 'object',
27
+ 'embed',
28
+ '[contenteditable]',
29
+ '[tabindex]',
30
+ ].join(',');
31
+ /** A native default of 0 (focusable without a tabindex attribute), else -1. */
32
+ function nativeTabIndex(element) {
33
+ return isNativelyFocusable(element) ? 0 : -1;
34
+ }
35
+ /**
36
+ * True when the element takes focus without an explicit `tabindex` — a link with
37
+ * an href, a form control, a `<summary>`, an editing host, and the embedded
38
+ * document elements. Disabled/hidden state is handled separately.
39
+ */
40
+ export function isNativelyFocusable(element) {
41
+ const tag = element.tagName.toLowerCase();
42
+ switch (tag) {
43
+ case 'a':
44
+ case 'area':
45
+ return element.hasAttribute('href');
46
+ case 'button':
47
+ case 'select':
48
+ case 'textarea':
49
+ return true;
50
+ case 'input':
51
+ return element.getAttribute('type')?.toLowerCase() !== 'hidden';
52
+ case 'summary':
53
+ return true;
54
+ case 'iframe':
55
+ case 'object':
56
+ case 'embed':
57
+ return true;
58
+ case 'audio':
59
+ case 'video':
60
+ return element.hasAttribute('controls');
61
+ }
62
+ const editable = element.getAttribute('contenteditable');
63
+ return editable !== null && editable !== 'false';
64
+ }
65
+ /**
66
+ * The tabindex the browser will use: the parsed attribute when present and
67
+ * numeric, otherwise the native default. A non-numeric `tabindex` (e.g.
68
+ * `tabindex="foo"`) is ignored by browsers, so it falls back to the native value.
69
+ */
70
+ export function resolvedTabIndex(element) {
71
+ const attr = element.getAttribute('tabindex');
72
+ if (attr === null)
73
+ return nativeTabIndex(element);
74
+ const parsed = Number.parseInt(attr, 10);
75
+ return Number.isNaN(parsed) ? nativeTabIndex(element) : parsed;
76
+ }
77
+ /** True when `element` (or an ancestor) is disabled via a control or `<fieldset disabled>`. */
78
+ function isDisabled(element) {
79
+ if ('disabled' in element && element.disabled)
80
+ return true;
81
+ // A disabled fieldset disables its controls (except those inside its first legend).
82
+ return element.closest('fieldset[disabled]') !== null && element.closest('legend') === null;
83
+ }
84
+ /**
85
+ * Structurally hidden — removed from the tab order by markup, independent of any
86
+ * layout: inside an `[inert]` or `[hidden]` subtree, or non-summary content of a
87
+ * closed `<details>`. Kept separate from the layout check so the injectable
88
+ * visibility predicate only ever overrides computed-style visibility.
89
+ */
90
+ function isStructurallyHidden(element) {
91
+ if (element.closest('[inert]') || element.closest('[hidden]'))
92
+ return true;
93
+ const closedDetails = element.closest('details:not([open])');
94
+ return closedDetails !== null && element.closest('summary') === null && element !== closedDetails;
95
+ }
96
+ /** Layout-aware default visibility: computed `display`/`visibility` up the tree. */
97
+ function defaultIsVisible(element) {
98
+ const view = element.ownerDocument?.defaultView;
99
+ if (!view?.getComputedStyle)
100
+ return true; // no layout engine (e.g. jsdom) — assume visible
101
+ for (let node = element; node; node = node.parentElement) {
102
+ const style = view.getComputedStyle(node);
103
+ if (style.display === 'none')
104
+ return false;
105
+ if (style.visibility === 'hidden' || style.visibility === 'collapse')
106
+ return false;
107
+ }
108
+ return true;
109
+ }
110
+ /**
111
+ * True when `element` participates in sequential keyboard navigation: it's
112
+ * focusable, has a resolved `tabindex >= 0`, and is neither disabled nor hidden.
113
+ * `isVisible` overrides only the layout (computed-style) part of the check.
114
+ */
115
+ export function isTabbable(element, isVisible = defaultIsVisible) {
116
+ if (resolvedTabIndex(element) < 0)
117
+ return false;
118
+ if (isDisabled(element))
119
+ return false;
120
+ if (isStructurallyHidden(element))
121
+ return false;
122
+ // An element matched only by `[contenteditable]` with the value "false" isn't focusable.
123
+ const editable = element.getAttribute('contenteditable');
124
+ if (editable === 'false' && !isNativelyFocusable(element) && !element.hasAttribute('tabindex')) {
125
+ return false;
126
+ }
127
+ return isVisible(element);
128
+ }
129
+ /**
130
+ * The resolved tab order within `root`: positive-tabindex stops first (ascending,
131
+ * ties in DOM order), then `tabindex=0`/native stops in DOM order — the order a
132
+ * browser actually moves focus. Each stop carries its owning component.
133
+ */
134
+ export function tabSequence(root = document, options = {}) {
135
+ const isVisible = options.isVisible ?? defaultIsVisible;
136
+ const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
137
+ const candidates = [...root.querySelectorAll(FOCUSABLE_SELECTOR)].filter((el) => isTabbable(el, isVisible));
138
+ const withMeta = candidates.map((element, domIndex) => ({
139
+ element,
140
+ domIndex,
141
+ tabindex: resolvedTabIndex(element),
142
+ positive: /^\d+$/.test(element.getAttribute('tabindex') ?? '') && resolvedTabIndex(element) > 0,
143
+ }));
144
+ const positives = withMeta
145
+ .filter((m) => m.tabindex > 0)
146
+ .sort((a, b) => a.tabindex - b.tabindex || a.domIndex - b.domIndex);
147
+ const zeros = withMeta.filter((m) => m.tabindex === 0); // already in DOM order
148
+ return [...positives, ...zeros].map((m, i) => {
149
+ const componentPath = resolveComponentPath(m.element);
150
+ return {
151
+ element: m.element,
152
+ order: i + 1,
153
+ tabindex: m.tabindex,
154
+ positive: m.positive,
155
+ component: appComponentFromPath(componentPath, prefixes),
156
+ componentPath,
157
+ };
158
+ });
159
+ }
160
+ /**
161
+ * Indices (0-based, into the sequence) where the tab path jumps *backward against
162
+ * reading order* — a stop that sits clearly above, or well to the left on the
163
+ * same row, of the stop before it. A heuristic signal that DOM/tabindex order
164
+ * has drifted from the visual order a sighted keyboard user expects; always
165
+ * "verify manually". `getRect` is injectable for tests.
166
+ */
167
+ export function visualOrderJumps(stops, getRect = (el) => el.getBoundingClientRect(), rowThreshold = 8) {
168
+ const jumps = [];
169
+ for (let i = 1; i < stops.length; i++) {
170
+ const prev = getRect(stops[i - 1].element);
171
+ const curr = getRect(stops[i].element);
172
+ const movedUp = curr.top < prev.top - rowThreshold;
173
+ const sameRowMovedLeft = Math.abs(curr.top - prev.top) <= rowThreshold && curr.left < prev.left - rowThreshold;
174
+ if (movedUp || sameRowMovedLeft)
175
+ jumps.push(i);
176
+ }
177
+ return jumps;
178
+ }
package/dist/overlay.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { A11yFinding } from './scan.js';
2
+ import type { TabStop } from './keyboard/tab-sequence.js';
2
3
  /**
3
4
  * Attribute marking the overlay's own DOM. `scan()` excludes anything under it
4
5
  * so the tool never reports violations against its own highlights.
@@ -9,8 +10,15 @@ export declare const OVERLAY_EXCLUDE_SELECTOR = "[data-ngb-a11y-overlay]";
9
10
  export interface A11yOverlay {
10
11
  /** Draw a highlight over each finding's node, replacing the previous set. */
11
12
  render(findings: A11yFinding[]): void;
13
+ /**
14
+ * Draw the tab order as numbered badges plus a connector path, on a layer
15
+ * independent of the findings highlights. Replaces the previous tab-order set.
16
+ */
17
+ renderTabOrder(stops: TabStop[]): void;
12
18
  /** Remove all highlights but keep the overlay live. */
13
19
  clear(): void;
20
+ /** Remove the tab-order layer but keep the overlay live. */
21
+ clearTabOrder(): void;
14
22
  /** Tear down: remove the container and detach scroll/resize listeners. */
15
23
  destroy(): void;
16
24
  }
package/dist/overlay.js CHANGED
@@ -1,3 +1,7 @@
1
+ const SVG_NS = 'http://www.w3.org/2000/svg';
2
+ /** Tab-order path + badge colours: normal teal, warning orange for positive tabindex. */
3
+ const TAB_ORDER_COLOR = '#0b8f8f';
4
+ const TAB_ORDER_WARN_COLOR = '#e8710a';
1
5
  /**
2
6
  * Attribute marking the overlay's own DOM. `scan()` excludes anything under it
3
7
  * so the tool never reports violations against its own highlights.
@@ -35,12 +39,44 @@ export function createOverlay(options = {}) {
35
39
  zIndex: '2147483646',
36
40
  });
37
41
  doc.body.appendChild(container);
42
+ // The tab-order connector lives on its own SVG layer under the badges, so the
43
+ // findings highlights and the tab-order path render and clear independently.
44
+ const svg = doc.createElementNS(SVG_NS, 'svg');
45
+ svg.setAttribute(OVERLAY_ATTR, '');
46
+ Object.assign(svg.style, {
47
+ position: 'fixed',
48
+ inset: '0',
49
+ width: '100%',
50
+ height: '100%',
51
+ pointerEvents: 'none',
52
+ overflow: 'visible',
53
+ });
54
+ const connector = doc.createElementNS(SVG_NS, 'polyline');
55
+ connector.setAttribute('fill', 'none');
56
+ connector.setAttribute('stroke', TAB_ORDER_COLOR);
57
+ connector.setAttribute('stroke-width', '2');
58
+ connector.setAttribute('stroke-dasharray', '4 3');
59
+ connector.setAttribute('opacity', '0.7');
60
+ svg.appendChild(connector);
61
+ container.appendChild(svg); // under the badges, which are appended later
38
62
  let highlights = [];
63
+ let tabBadges = [];
39
64
  const reposition = () => {
40
65
  for (const { target, box } of highlights) {
41
66
  positionBox(box, target);
42
67
  }
68
+ repositionTabOrder();
43
69
  };
70
+ function repositionTabOrder() {
71
+ const points = [];
72
+ for (const { target, badge } of tabBadges) {
73
+ const rect = target.getBoundingClientRect();
74
+ badge.style.top = `${rect.top}px`;
75
+ badge.style.left = `${rect.left}px`;
76
+ points.push(`${rect.left + rect.width / 2},${rect.top + rect.height / 2}`);
77
+ }
78
+ connector.setAttribute('points', points.join(' '));
79
+ }
44
80
  // rAF-throttle so a stream of scroll events collapses to one layout read.
45
81
  const raf = doc.defaultView?.requestAnimationFrame?.bind(doc.defaultView);
46
82
  let scheduled = false;
@@ -78,13 +114,63 @@ export function createOverlay(options = {}) {
78
114
  highlights.push({ finding, target, box });
79
115
  }
80
116
  }
117
+ function clearTabOrder() {
118
+ for (const { badge } of tabBadges)
119
+ badge.remove();
120
+ tabBadges = [];
121
+ connector.setAttribute('points', '');
122
+ }
123
+ function renderTabOrder(stops) {
124
+ clearTabOrder();
125
+ for (const stop of stops) {
126
+ const target = stop.element;
127
+ if (!target.isConnected)
128
+ continue; // node gone since the sequence was computed
129
+ const badge = buildBadge(doc, stop);
130
+ container.appendChild(badge);
131
+ tabBadges.push({ stop, target, badge });
132
+ }
133
+ repositionTabOrder();
134
+ }
81
135
  function destroy() {
82
136
  clear();
137
+ clearTabOrder();
83
138
  win?.removeEventListener('scroll', onViewportChange, { capture: true });
84
139
  win?.removeEventListener('resize', onViewportChange);
85
140
  container.remove();
86
141
  }
87
- return { render, clear, destroy };
142
+ return { render, renderTabOrder, clear, clearTabOrder, destroy };
143
+ }
144
+ /**
145
+ * A numbered badge marking one tab stop, anchored at the target's top-left
146
+ * corner. A positive-tabindex stop is coloured as a warning, since an explicit
147
+ * positive tabindex hijacks the natural order.
148
+ */
149
+ function buildBadge(doc, stop) {
150
+ const color = stop.positive ? TAB_ORDER_WARN_COLOR : TAB_ORDER_COLOR;
151
+ const badge = doc.createElement('div');
152
+ badge.setAttribute('data-ngb-tab-order', String(stop.order));
153
+ const owner = stop.component ? ` · ${stop.component}` : '';
154
+ const ti = stop.positive ? ` · tabindex=${stop.tabindex} (hijacks order)` : '';
155
+ badge.title = `Tab stop ${stop.order}${owner}${ti}`;
156
+ badge.textContent = String(stop.order);
157
+ Object.assign(badge.style, {
158
+ position: 'fixed',
159
+ transform: 'translate(-50%, -50%)',
160
+ minWidth: '16px',
161
+ height: '16px',
162
+ padding: '0 3px',
163
+ boxSizing: 'border-box',
164
+ borderRadius: '8px',
165
+ font: '10px/16px ui-monospace, monospace',
166
+ fontWeight: '700',
167
+ textAlign: 'center',
168
+ color: '#fff',
169
+ background: color,
170
+ border: '1px solid rgba(255,255,255,0.85)',
171
+ pointerEvents: 'none',
172
+ });
173
+ return badge;
88
174
  }
89
175
  /** Resolve a finding's target selector to a node, tolerating a bad selector. */
90
176
  function resolveTarget(doc, target) {
@@ -26,6 +26,14 @@ export interface A11yDevtoolsOptions {
26
26
  * when auditing a component library's own code.
27
27
  */
28
28
  frameworkPrefixes?: readonly string[];
29
+ /**
30
+ * Turn on the **keyboard layer** — the ~2/3 of accessibility axe can't test.
31
+ * Adds heuristic `ngbr/*` findings (keyboard-unreachable controls,
32
+ * click-without-keyboard handlers, tab-order mismatches) to the report, and,
33
+ * when `overlay` is on, draws the numbered tab-order path over the page.
34
+ * Default false.
35
+ */
36
+ keyboard?: boolean;
29
37
  }
30
38
  /**
31
39
  * Dev-only in-app accessibility auditing. Rescans whenever the application
package/dist/provider.js CHANGED
@@ -2,6 +2,7 @@ import { ApplicationRef, DestroyRef, inject, isDevMode, makeEnvironmentProviders
2
2
  import { debounceTime, filter } from 'rxjs';
3
3
  import { runA11yScan } from './runner.js';
4
4
  import { createOverlay } from './overlay.js';
5
+ import { tabSequence } from './keyboard/tab-sequence.js';
5
6
  /**
6
7
  * Dev-only in-app accessibility auditing. Rescans whenever the application
7
8
  * settles (zoneless-aware, via `ApplicationRef.isStable`) and reports each
@@ -15,7 +16,7 @@ export function provideA11yDevtools(options = {}) {
15
16
  if (!isDevMode()) {
16
17
  return makeEnvironmentProviders([]);
17
18
  }
18
- const { root, log = true, logger, overlay = false, debounceMs = 500, tags, frameworkPrefixes } = options;
19
+ const { root, log = true, logger, overlay = false, debounceMs = 500, tags, frameworkPrefixes, keyboard = false, } = options;
19
20
  const axe = tags
20
21
  ? { runOnly: { type: 'tag', values: tags } }
21
22
  : undefined;
@@ -31,8 +32,15 @@ export function provideA11yDevtools(options = {}) {
31
32
  if (scanning)
32
33
  return; // don't stack rescans while one is in flight
33
34
  scanning = true;
34
- runA11yScan(root?.(), { log, logger, axe, frameworkPrefixes })
35
- .then((findings) => overlayView?.render(findings))
35
+ runA11yScan(root?.(), { log, logger, axe, frameworkPrefixes, keyboard })
36
+ .then((findings) => {
37
+ overlayView?.render(findings);
38
+ // Draw the tab-order path as its own overlay layer (independent of
39
+ // the findings highlights) when the keyboard layer is on.
40
+ if (overlayView && keyboard) {
41
+ overlayView.renderTabOrder(tabSequence(root?.() ?? document, { frameworkPrefixes }));
42
+ }
43
+ })
36
44
  .catch(() => undefined)
37
45
  .finally(() => {
38
46
  scanning = false;
@@ -26,6 +26,13 @@ export interface ScanPagesOptions {
26
26
  * library's own code (so it blames the library component, not a demo wrapper).
27
27
  */
28
28
  frameworkPrefixes?: readonly string[];
29
+ /**
30
+ * Also run the keyboard layer in-page — heuristic `ngbr/*` findings for
31
+ * keyboard-unreachable controls, click-without-keyboard handlers, and
32
+ * tab-order mismatches (the last needs real layout, which headless has).
33
+ * Default false.
34
+ */
35
+ keyboard?: boolean;
29
36
  }
30
37
  /**
31
38
  * Drive a real headless browser over a running Angular **dev** build and return
@@ -21,7 +21,7 @@ function inPageScriptPath() {
21
21
  * to the component that rendered it — with no change to the target app.
22
22
  */
23
23
  export async function scanPages(options) {
24
- const { baseUrl, routes, tags, waitMs = 1500, labels = {}, setup, headed = false, frameworkPrefixes } = options;
24
+ const { baseUrl, routes, tags, waitMs = 1500, labels = {}, setup, headed = false, frameworkPrefixes, keyboard, } = options;
25
25
  const axeOptions = tags
26
26
  ? { runOnly: { type: 'tag', values: tags } }
27
27
  : undefined;
@@ -48,7 +48,7 @@ export async function scanPages(options) {
48
48
  const findings = (await page.evaluate((args) => {
49
49
  const w = window;
50
50
  return w.__ngbA11yScan(args.axe, args.scan);
51
- }, { axe: axeOptions, scan: { frameworkPrefixes } }));
51
+ }, { axe: axeOptions, scan: { frameworkPrefixes, keyboard } }));
52
52
  pages.push({ label, url: page.url(), findings });
53
53
  }
54
54
  catch (err) {
package/dist/runner.d.ts CHANGED
@@ -20,6 +20,12 @@ export interface RunOptions {
20
20
  * attribute to the immediate owner (e.g. when scanning a library's own code).
21
21
  */
22
22
  frameworkPrefixes?: readonly string[];
23
+ /**
24
+ * Also run the keyboard layer — heuristic `ngbr/*` findings for
25
+ * keyboard-unreachable controls, click-without-keyboard handlers, and
26
+ * tab-order mismatches. Default false.
27
+ */
28
+ keyboard?: boolean;
23
29
  }
24
30
  /** Scan `root`, optionally report, and return the findings. */
25
31
  export declare function runA11yScan(root?: Element | Document, options?: RunOptions): Promise<A11yFinding[]>;
package/dist/runner.js CHANGED
@@ -4,6 +4,7 @@ import { logFindings } from './report.js';
4
4
  export async function runA11yScan(root, options = {}) {
5
5
  const findings = await scan(root ?? document, options.axe, {
6
6
  frameworkPrefixes: options.frameworkPrefixes,
7
+ keyboard: options.keyboard,
7
8
  });
8
9
  if (options.log !== false) {
9
10
  logFindings(findings, options.logger);
package/dist/scan.d.ts CHANGED
@@ -9,6 +9,13 @@ export interface ScanOptions {
9
9
  * immediate owner — useful when scanning a component library's own code.
10
10
  */
11
11
  frameworkPrefixes?: readonly string[];
12
+ /**
13
+ * Also run the keyboard layer (part B): heuristic, `window.ng`-driven checks
14
+ * axe can't do — keyboard-unreachable interactive controls, click handlers
15
+ * with no keyboard handler, and visual-vs-tab-order mismatches. Emitted as
16
+ * `ngbr/*` findings alongside the axe violations. Default false.
17
+ */
18
+ keyboard?: boolean;
12
19
  }
13
20
  /** One axe violation node, enriched with the component that rendered it. */
14
21
  export interface A11yFinding {
package/dist/scan.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, resolveComponentPath, resolveDirectiveNames, } from './attribution.js';
2
2
  import { OVERLAY_EXCLUDE_SELECTOR } from './overlay.js';
3
+ import { scanKeyboard } from './keyboard/keyboard-scan.js';
3
4
  // axe-core is a singleton and throws if a run starts while another is in flight.
4
5
  // Chain runs so overlapping callers (e.g. rapid rescans) serialize safely.
5
6
  let runChain = Promise.resolve();
@@ -46,5 +47,10 @@ async function runAxeOnce(root, options, scanOptions) {
46
47
  });
47
48
  }
48
49
  }
50
+ // The keyboard layer runs over the same root, in the page, and appends its own
51
+ // `ngbr/*` findings so they group and report exactly like the axe ones.
52
+ if (scanOptions?.keyboard) {
53
+ findings.push(...scanKeyboard(root, { frameworkPrefixes }));
54
+ }
49
55
  return findings;
50
56
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngbracket/a11y-devtools",
3
- "version": "0.5.0",
3
+ "version": "0.6.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",