@ngbracket/a11y-devtools 0.4.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.
@@ -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
  }
@@ -34146,9 +34165,16 @@
34146
34165
  return null;
34147
34166
  return cleanName(instance.constructor.name ?? null);
34148
34167
  }
34149
- var PRIMITIVE_COMPONENT = /^(Nb|Mat|Cdk|Mdc)[A-Z]/;
34150
- function isPrimitiveComponent(name) {
34151
- return PRIMITIVE_COMPONENT.test(name);
34168
+ var DEFAULT_FRAMEWORK_PREFIXES = ["Nb", "Mat", "Cdk", "Mdc"];
34169
+ function isPrimitiveComponent(name, prefixes) {
34170
+ for (const prefix of prefixes) {
34171
+ if (!prefix || name.length <= prefix.length || !name.startsWith(prefix))
34172
+ continue;
34173
+ const next = name.charCodeAt(prefix.length);
34174
+ if (next >= 65 && next <= 90)
34175
+ return true;
34176
+ }
34177
+ return false;
34152
34178
  }
34153
34179
  function resolveComponentPath(node) {
34154
34180
  const ng = ngDebug();
@@ -34171,11 +34197,11 @@
34171
34197
  }
34172
34198
  return path;
34173
34199
  }
34174
- function appComponentFromPath(path) {
34175
- return path.find((name) => !isPrimitiveComponent(name)) ?? path[0] ?? null;
34200
+ function appComponentFromPath(path, frameworkPrefixes = DEFAULT_FRAMEWORK_PREFIXES) {
34201
+ return path.find((name) => !isPrimitiveComponent(name, frameworkPrefixes)) ?? path[0] ?? null;
34176
34202
  }
34177
- function resolveOwningComponentName(node) {
34178
- return appComponentFromPath(resolveComponentPath(node));
34203
+ function resolveOwningComponentName(node, frameworkPrefixes = DEFAULT_FRAMEWORK_PREFIXES) {
34204
+ return appComponentFromPath(resolveComponentPath(node), frameworkPrefixes);
34179
34205
  }
34180
34206
  function resolveDirectiveNames(node) {
34181
34207
  const ng = ngDebug();
@@ -34197,6 +34223,9 @@
34197
34223
  }
34198
34224
 
34199
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";
34200
34229
  var OVERLAY_ATTR = "data-ngb-a11y-overlay";
34201
34230
  var OVERLAY_EXCLUDE_SELECTOR = `[${OVERLAY_ATTR}]`;
34202
34231
  var IMPACT_COLOR = {
@@ -34221,12 +34250,42 @@
34221
34250
  zIndex: "2147483646"
34222
34251
  });
34223
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);
34224
34271
  let highlights = [];
34272
+ let tabBadges = [];
34225
34273
  const reposition = () => {
34226
34274
  for (const { target, box } of highlights) {
34227
34275
  positionBox(box, target);
34228
34276
  }
34277
+ repositionTabOrder();
34229
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
+ }
34230
34289
  const raf = doc.defaultView?.requestAnimationFrame?.bind(doc.defaultView);
34231
34290
  let scheduled = false;
34232
34291
  const onViewportChange = () => {
@@ -34263,13 +34322,58 @@
34263
34322
  highlights.push({ finding, target, box });
34264
34323
  }
34265
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
+ }
34266
34343
  function destroy() {
34267
34344
  clear();
34345
+ clearTabOrder();
34268
34346
  win?.removeEventListener("scroll", onViewportChange, { capture: true });
34269
34347
  win?.removeEventListener("resize", onViewportChange);
34270
34348
  container.remove();
34271
34349
  }
34272
- 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;
34273
34377
  }
34274
34378
  function resolveTarget(doc, target) {
34275
34379
  try {
@@ -34327,15 +34431,222 @@
34327
34431
  }, 600);
34328
34432
  }
34329
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
+
34330
34640
  // dist/scan.js
34331
34641
  var runChain = Promise.resolve();
34332
- function scan(root = document, options) {
34333
- const result = runChain.then(() => runAxeOnce(root, options));
34642
+ function scan(root = document, options, scanOptions) {
34643
+ const result = runChain.then(() => runAxeOnce(root, options, scanOptions));
34334
34644
  runChain = result.catch(() => void 0);
34335
34645
  return result;
34336
34646
  }
34337
- async function runAxeOnce(root, options) {
34647
+ async function runAxeOnce(root, options, scanOptions) {
34338
34648
  const axe = (await Promise.resolve().then(() => __toESM(require_axe(), 1))).default;
34649
+ const frameworkPrefixes = scanOptions?.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
34339
34650
  const context = { include: root, exclude: [OVERLAY_EXCLUDE_SELECTOR] };
34340
34651
  const results = await axe.run(context, options ?? {});
34341
34652
  const doc = root instanceof Document ? root : root.ownerDocument ?? document;
@@ -34355,7 +34666,7 @@
34355
34666
  impact: violation.impact ?? null,
34356
34667
  help: violation.help,
34357
34668
  helpUrl: violation.helpUrl,
34358
- component: appComponentFromPath(componentPath),
34669
+ component: appComponentFromPath(componentPath, frameworkPrefixes),
34359
34670
  componentPath,
34360
34671
  directives: element ? resolveDirectiveNames(element) : [],
34361
34672
  target,
@@ -34363,11 +34674,14 @@
34363
34674
  });
34364
34675
  }
34365
34676
  }
34677
+ if (scanOptions?.keyboard) {
34678
+ findings.push(...scanKeyboard(root, { frameworkPrefixes }));
34679
+ }
34366
34680
  return findings;
34367
34681
  }
34368
34682
 
34369
34683
  // dist/inpage.js
34370
- var run = (options) => scan(document, options);
34684
+ var run = (options, scanOptions) => scan(document, options, scanOptions);
34371
34685
  globalThis.__ngbA11yScan = run;
34372
34686
  })();
34373
34687
  /*! Bundled license information:
package/dist/inpage.js CHANGED
@@ -1,3 +1,3 @@
1
1
  import { scan } from './scan.js';
2
- const run = (options) => scan(document, options);
2
+ const run = (options, scanOptions) => scan(document, options, scanOptions);
3
3
  globalThis.__ngbA11yScan = run;
@@ -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[];