@ngbracket/a11y-devtools 0.19.0 → 0.20.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.
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Focus lost between two moments: a route change or a re-render that leaves
3
+ * keyboard focus on `<body>`.
4
+ *
5
+ * A scan sees the page at one moment, so it can't see this. When the focused
6
+ * control is removed (the link that was clicked goes away with the old view,
7
+ * or an `@if` / `@for` re-renders it), the browser drops focus to `<body>` and
8
+ * the next Tab starts from the top of the page. This probe watches for that and
9
+ * reports it as an `ngbr/*` finding, attributed to the component the control
10
+ * belonged to. It also keeps a record of each route change: where focus went,
11
+ * whether the title changed, and what live regions announced.
12
+ *
13
+ * It knows nothing about the Angular Router: a route change is a change of
14
+ * `location.pathname + location.search`, checked when the host says the app has
15
+ * settled ({@link FocusLossProbe.notifyStable}).
16
+ */
17
+ import { appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, resolveComponentPath, resolveDirectiveNames, } from '../attribution.js';
18
+ import { OVERLAY_ATTR } from '../overlay.js';
19
+ import { deepActiveElement } from '../keyboard/focus-walk.js';
20
+ import { RULE_DOCS, shortHtml, shortSelector, uniqueLocator } from '../keyboard/keyboard-scan.js';
21
+ import { ngbrRuleCriteria } from '../report/wcag.js';
22
+ export { describeNavigation } from './record.js';
23
+ export const DEFAULT_FOCUS_TARGET = 'main, [role="main"], h1';
24
+ /** Live regions, and the hidden element Angular CDK's LiveAnnouncer writes into. */
25
+ const LIVE_REGION = [
26
+ '[aria-live]:not([aria-live="off"])',
27
+ '[role="status"]',
28
+ '[role="alert"]',
29
+ '[role="log"]',
30
+ '.cdk-live-announcer-element',
31
+ ].join(', ');
32
+ function safeClosest(el, selector) {
33
+ try {
34
+ return el.closest(selector);
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ /** Start watching `doc` for focus lost to a removal or a route change. */
41
+ export function createFocusLossProbe(doc = document, options = {}) {
42
+ const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
43
+ const graceMs = options.graceMs ?? 150;
44
+ const focusTarget = options.focusTarget ?? DEFAULT_FOCUS_TARGET;
45
+ // Hash routing (`#/orders`) counts; an in-page anchor (`#section`) doesn't.
46
+ const route = options.route ??
47
+ (() => location.pathname + location.search + (location.hash.startsWith('#/') ? location.hash : ''));
48
+ const records = [];
49
+ const findings = [];
50
+ /** Checks waiting out the grace period: each timer and the resolver of its promise. */
51
+ const pending = new Map();
52
+ let focused;
53
+ /** The element focused on each route, while it has focus, for "where was focus before the change". */
54
+ const focusByRoute = new Map();
55
+ let lastRoute = route();
56
+ let lastTitle = doc.title;
57
+ let navigating = false;
58
+ /** Live region text, with when it was announced. */
59
+ const announced = [];
60
+ /**
61
+ * How long before the app settles an announcement still counts as part of
62
+ * the route change: a router announcer may speak just before the URL updates.
63
+ */
64
+ const ANNOUNCE_WINDOW_MS = 2000;
65
+ const ours = (el) => el.closest(`[${OVERLAY_ATTR}]`) !== null;
66
+ const onBody = (el) => !el || el === doc.body || el === doc.documentElement;
67
+ function snapshot(element) {
68
+ const componentPath = resolveComponentPath(element);
69
+ const ancestors = [];
70
+ for (let el = element.parentElement; el && el !== doc.body; el = el.parentElement)
71
+ ancestors.push(el);
72
+ return {
73
+ element,
74
+ ancestors,
75
+ route: route(),
76
+ component: appComponentFromPath(componentPath, prefixes),
77
+ componentPath,
78
+ directives: resolveDirectiveNames(element),
79
+ target: shortSelector(element),
80
+ html: shortHtml(element),
81
+ };
82
+ }
83
+ /** Run `fn` after the grace period, tracked so `settled()` can wait for it. */
84
+ function later(fn) {
85
+ let done;
86
+ const promise = new Promise((resolve) => (done = resolve));
87
+ const timer = setTimeout(() => {
88
+ try {
89
+ fn();
90
+ }
91
+ finally {
92
+ pending.delete(promise);
93
+ done();
94
+ }
95
+ }, graceMs);
96
+ pending.set(promise, { timer, done });
97
+ }
98
+ function report(snap, id, help, page, box) {
99
+ // Draw the box on the nearest ancestor still in the page: the element is gone.
100
+ // Not after a route change: the whole view went, so that box would be most of the page.
101
+ const anchor = box ? snap.ancestors.find((el) => el.isConnected) : undefined;
102
+ const finding = {
103
+ id,
104
+ impact: 'moderate',
105
+ help,
106
+ helpUrl: `${RULE_DOCS}/${id.slice('ngbr/'.length)}`,
107
+ wcag: ngbrRuleCriteria(id),
108
+ component: snap.component,
109
+ componentPath: snap.componentPath,
110
+ directives: snap.directives,
111
+ target: snap.target,
112
+ locator: anchor ? (uniqueLocator(anchor) ?? shortSelector(anchor)) : undefined,
113
+ html: snap.html,
114
+ };
115
+ findings.push(finding);
116
+ options.onFinding?.(finding, page);
117
+ }
118
+ const onFocusIn = (event) => {
119
+ // The element itself, not its shadow host.
120
+ const el = event.composedPath()[0] ?? event.target;
121
+ if (!(el instanceof Element) || onBody(el) || ours(el))
122
+ return;
123
+ focused = snapshot(el);
124
+ focusByRoute.set(focused.route, focused);
125
+ };
126
+ // Focus moved to the page body while the element stays (a click on the
127
+ // background): it no longer has focus, so removing it later loses nothing.
128
+ // Checked a moment later, because a browser may blur an element as it's removed.
129
+ const onFocusOut = (event) => {
130
+ if (event.relatedTarget)
131
+ return; // focus moved to another element: focusin handles it
132
+ const snap = focused;
133
+ if (!snap)
134
+ return;
135
+ queueMicrotask(() => {
136
+ if (focused !== snap || !snap.element.isConnected || !onBody(deepActiveElement(doc)))
137
+ return;
138
+ focused = undefined;
139
+ if (focusByRoute.get(snap.route) === snap)
140
+ focusByRoute.delete(snap.route);
141
+ });
142
+ };
143
+ function checkRemoval() {
144
+ const snap = focused;
145
+ if (!snap || snap.element.isConnected)
146
+ return;
147
+ focused = undefined;
148
+ later(() => {
149
+ // A route change took the element away: the navigation check reports that.
150
+ if (route() !== snap.route || navigating)
151
+ return;
152
+ if (!onBody(deepActiveElement(doc)))
153
+ return; // focus was put somewhere: fine
154
+ snap.reported = true;
155
+ report(snap, 'ngbr/focus-lost-on-rerender', `Focus was lost when this element was removed: it had focus, a re-render ` +
156
+ `took it out of the page, and focus fell back to the page body, so the next ` +
157
+ `Tab starts from the top. Move focus to a sensible place before removing it ` +
158
+ `(the next item, the list, or a heading). Heuristic — verify manually.`, snap.route, true);
159
+ });
160
+ }
161
+ function logAnnouncements(mutations) {
162
+ const regions = new Set();
163
+ for (const m of mutations) {
164
+ const el = m.target instanceof Element ? m.target : m.target.parentElement;
165
+ if (!el || ours(el))
166
+ continue;
167
+ const region = safeClosest(el, LIVE_REGION);
168
+ // A region added with its text already in it is usually not announced.
169
+ if (region && !(m.type === 'childList' && [...m.addedNodes].some((n) => n === region || n.contains(region)))) {
170
+ regions.add(region);
171
+ }
172
+ }
173
+ for (const region of regions) {
174
+ const text = region.textContent?.replace(/\s+/g, ' ').trim();
175
+ if (text)
176
+ announced.push({ text: text.length > 200 ? `${text.slice(0, 199)}…` : text, time: Date.now() });
177
+ }
178
+ if (announced.length > 50)
179
+ announced.splice(0, announced.length - 50);
180
+ }
181
+ const observer = new MutationObserver((mutations) => {
182
+ logAnnouncements(mutations);
183
+ checkRemoval();
184
+ });
185
+ observer.observe(doc.documentElement, { childList: true, subtree: true, characterData: true });
186
+ doc.addEventListener('focusin', onFocusIn, true);
187
+ doc.addEventListener('focusout', onFocusOut, true);
188
+ // Whatever has focus when the probe starts counts as focused.
189
+ const initial = deepActiveElement(doc);
190
+ if (initial && !onBody(initial) && !ours(initial)) {
191
+ focused = snapshot(initial);
192
+ focusByRoute.set(focused.route, focused);
193
+ }
194
+ function notifyStable() {
195
+ if (navigating)
196
+ return; // already checking a change; it reads the final state
197
+ if (route() === lastRoute) {
198
+ lastTitle = doc.title; // titles are often set after the first render
199
+ return;
200
+ }
201
+ navigating = true;
202
+ const from = lastRoute;
203
+ const titleBefore = lastTitle;
204
+ const before = focusByRoute.get(from);
205
+ const since = Date.now() - ANNOUNCE_WINDOW_MS;
206
+ later(() => {
207
+ navigating = false;
208
+ const to = route();
209
+ lastRoute = to;
210
+ lastTitle = doc.title;
211
+ for (const key of [...focusByRoute.keys()])
212
+ if (key !== to)
213
+ focusByRoute.delete(key);
214
+ if (to === from)
215
+ return; // went there and back
216
+ const active = deepActiveElement(doc);
217
+ const lost = onBody(active);
218
+ const focus = lost
219
+ ? 'body'
220
+ : active && safeClosest(active, focusTarget)
221
+ ? 'target'
222
+ : 'other';
223
+ const record = {
224
+ from,
225
+ to,
226
+ focus,
227
+ focusedTarget: lost || !active ? null : shortSelector(active),
228
+ focusedComponent: lost || !active ? null : appComponentFromPath(resolveComponentPath(active), prefixes),
229
+ focusBefore: before?.target ?? null,
230
+ titleBefore,
231
+ titleAfter: doc.title,
232
+ titleChanged: doc.title !== titleBefore,
233
+ // What was announced from just before the app settled. An announcer may
234
+ // speak just before the URL updates, so the route isn't checked.
235
+ announcements: announced.filter((a) => a.time >= since).map((a) => a.text),
236
+ };
237
+ announced.length = 0;
238
+ records.push(record);
239
+ options.onNavigation?.(record);
240
+ // Only when the element that had focus went away with the old view: one
241
+ // that is still in the page (a header link) didn't lose focus by leaving.
242
+ if (lost && before && !before.element.isConnected && !before.reported) {
243
+ report(before, 'ngbr/focus-lost-on-navigation', `Focus was lost on the route change from ${from} to ${to}: the element that ` +
244
+ `had focus went away with the old view, and focus fell back to the page ` +
245
+ `body, so the next Tab starts from the top and a screen reader may say ` +
246
+ `nothing. Move focus to the new view's heading or main region after ` +
247
+ `navigation. Heuristic — verify manually.`, to, false);
248
+ }
249
+ });
250
+ }
251
+ return {
252
+ notifyStable,
253
+ async settled() {
254
+ while (pending.size)
255
+ await Promise.all([...pending.keys()]);
256
+ },
257
+ records: () => [...records],
258
+ findings: () => [...findings],
259
+ stop() {
260
+ observer.disconnect();
261
+ doc.removeEventListener('focusin', onFocusIn, true);
262
+ doc.removeEventListener('focusout', onFocusOut, true);
263
+ for (const { timer, done } of pending.values()) {
264
+ clearTimeout(timer);
265
+ done();
266
+ }
267
+ pending.clear();
268
+ },
269
+ };
270
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * A route change as the focus-loss probe recorded it. Kept apart from the probe,
3
+ * with no imports, so the report formatters (which also run in Node) can use it.
4
+ */
5
+ /** Where focus ended up after a route change. */
6
+ export type NavigationFocus = 'body' | 'target' | 'other';
7
+ /** One route change, as the probe saw it. */
8
+ export interface NavigationRecord {
9
+ /** Route before (`pathname + search`, plus a `#/` hash). */
10
+ from: string;
11
+ /** Route after. */
12
+ to: string;
13
+ /**
14
+ * How the change was made, when the driver knows: `link` (a link was
15
+ * activated from the keyboard) or `history` (`history.pushState` and a
16
+ * `popstate` event). Unset in the app.
17
+ */
18
+ via?: 'link' | 'history';
19
+ /** `body`: focus was lost; `target`: inside the expected focus target; `other`: anywhere else. */
20
+ focus: NavigationFocus;
21
+ /** Short selector of the focused element after the change; null when focus is on `<body>`. */
22
+ focusedTarget: string | null;
23
+ /** Component that owns the focused element after the change. */
24
+ focusedComponent: string | null;
25
+ /** Short selector of the element that had focus before the change, if any. */
26
+ focusBefore: string | null;
27
+ titleBefore: string;
28
+ titleAfter: string;
29
+ titleChanged: boolean;
30
+ /** Text live regions announced after the change, in order. */
31
+ announcements: string[];
32
+ }
33
+ /** One line for a route change: "/a → /b: focus on body, title unchanged, nothing announced". */
34
+ export declare function describeNavigation(record: NavigationRecord): string;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * A route change as the focus-loss probe recorded it. Kept apart from the probe,
3
+ * with no imports, so the report formatters (which also run in Node) can use it.
4
+ */
5
+ /** One line for a route change: "/a → /b: focus on body, title unchanged, nothing announced". */
6
+ export function describeNavigation(record) {
7
+ const focus = record.focus === 'body'
8
+ ? 'focus on body'
9
+ : `focus on ${record.focusedTarget ?? 'an element'}`;
10
+ const title = record.titleChanged ? 'title changed' : 'title unchanged';
11
+ const said = record.announcements.length
12
+ ? `announced "${record.announcements.join(' / ')}"`
13
+ : 'nothing announced';
14
+ return `${record.from} → ${record.to}: ${focus}, ${title}, ${said}`;
15
+ }
@@ -26,6 +26,8 @@ export interface PillMenuStatus {
26
26
  }[];
27
27
  /** The component filter in force, or null for every component. */
28
28
  component?: string | null;
29
+ /** The latest route changes, newest first, one line each. */
30
+ routeChanges?: string[];
29
31
  }
30
32
  export interface PillMenu {
31
33
  /** The `⋯` button that opens the panel. */
package/dist/pill-menu.js CHANGED
@@ -163,8 +163,19 @@ export function createPillMenu(doc, options) {
163
163
  download.addEventListener('click', () => options.onDownload());
164
164
  const pagesNote = doc.createElement('p');
165
165
  Object.assign(pagesNote.style, { margin: '4px 0 0', fontSize: '12px', color: muted });
166
+ // The latest route changes: where focus went, the title, what was announced.
167
+ const routesHeading = doc.createElement('p');
168
+ routesHeading.id = `${id}-routes`;
169
+ routesHeading.textContent = 'Route changes';
170
+ Object.assign(routesHeading.style, { margin: '10px 0 4px', fontWeight: '700' });
171
+ const routesList = doc.createElement('ul');
172
+ routesList.setAttribute('aria-labelledby', routesHeading.id);
173
+ Object.assign(routesList.style, { margin: '0', padding: '0 0 0 16px', fontSize: '12px', color: muted });
174
+ const routes = doc.createElement('div');
175
+ routes.hidden = true;
176
+ routes.append(routesHeading, routesList);
166
177
  const componentControls = options.onComponentChange ? [componentLabel, componentSelect] : [];
167
- panel.append(status, fieldset, severityLabel, select, ...componentControls, download, pagesNote);
178
+ panel.append(status, fieldset, severityLabel, select, ...componentControls, download, pagesNote, routes);
168
179
  function update(patch) {
169
180
  settings = { ...settings, ...patch };
170
181
  options.onChange(settings);
@@ -206,9 +217,17 @@ export function createPillMenu(doc, options) {
206
217
  return {
207
218
  button,
208
219
  panel,
209
- setStatus({ found, shown, pages, components, component }) {
220
+ setStatus({ found, shown, pages, components, component, routeChanges }) {
210
221
  if (components)
211
222
  setComponentOptions(components, component ?? null);
223
+ if (routeChanges) {
224
+ routes.hidden = routeChanges.length === 0;
225
+ routesList.replaceChildren(...routeChanges.map((line) => {
226
+ const item = doc.createElement('li');
227
+ item.textContent = line;
228
+ return item;
229
+ }));
230
+ }
212
231
  const issues = `${found} ${found === 1 ? 'issue' : 'issues'} on this page`;
213
232
  status.textContent = shown === found ? issues : `${issues}, ${shown} shown`;
214
233
  pagesNote.textContent = `Covers ${pages} ${pages === 1 ? 'page' : 'pages'} visited since the app loaded.`;
@@ -66,6 +66,20 @@ export interface A11yDevtoolsOptions {
66
66
  * issue. Developers can change it from the pill's menu. Default `'minor'`.
67
67
  */
68
68
  minImpact?: MinImpact;
69
+ /**
70
+ * Watch for focus lost between scans: a route change, or an `@if` / `@for`
71
+ * re-render, that removes the focused element and leaves focus on the page
72
+ * body. Reported as `ngbr/focus-lost-on-navigation` and
73
+ * `ngbr/focus-lost-on-rerender`, and each route change is listed in the
74
+ * pill's menu. Default: follows `keyboard`.
75
+ */
76
+ navigation?: boolean;
77
+ /**
78
+ * Where focus is expected to go after a route change, as a CSS selector. Only
79
+ * labels the route-change list ("focus on the target" or elsewhere); focus
80
+ * left on the page body is the only finding. Default `'main, [role="main"], h1'`.
81
+ */
82
+ focusTarget?: string;
69
83
  }
70
84
  /**
71
85
  * Dev-only in-app accessibility auditing. Rescans whenever the application
package/dist/provider.js CHANGED
@@ -7,6 +7,8 @@ import { describeElement } from './keyboard/accname.js';
7
7
  import { resolveOwningComponentName } from './attribution.js';
8
8
  import { createTogglePill, DEFAULT_TOGGLE_SHORTCUT, matchesShortcut, parseShortcut, readStoredEnabled, writeStoredEnabled, } from './toggle.js';
9
9
  import { componentCounts, readStoredSettings, resolveSettings, visibleFindings, worstImpact, writeStoredSettings, } from './settings.js';
10
+ import { findingKey } from './report/baseline.js';
11
+ import { createFocusLossProbe, describeNavigation, } from './navigation/focus-loss.js';
10
12
  /**
11
13
  * Dev-only in-app accessibility auditing. Rescans whenever the application
12
14
  * settles (zoneless-aware, via `ApplicationRef.isStable`) and reports each
@@ -31,7 +33,7 @@ function devtoolsProviders(options) {
31
33
  if (!isDevMode()) {
32
34
  return makeEnvironmentProviders([]);
33
35
  }
34
- const { root, log = true, logger, overlay = false, debounceMs = 500, tags, frameworkPrefixes, keyboard = false, enabled: enabledByDefault = true, pill = 'bottom-left', shortcut: shortcutText = DEFAULT_TOGGLE_SHORTCUT, layers = {}, minImpact = 'minor', } = options;
36
+ const { root, log = true, logger, overlay = false, debounceMs = 500, tags, frameworkPrefixes, keyboard = false, enabled: enabledByDefault = true, pill = 'bottom-left', shortcut: shortcutText = DEFAULT_TOGGLE_SHORTCUT, layers = {}, minImpact = 'minor', navigation = keyboard, focusTarget, } = options;
35
37
  const defaultSettings = {
36
38
  highlights: layers.highlights ?? true,
37
39
  tabOrder: layers.tabOrder ?? keyboard,
@@ -57,23 +59,32 @@ function devtoolsProviders(options) {
57
59
  // and the latest findings per route visited, for the downloadable report.
58
60
  let lastFindings = [];
59
61
  const visited = new Map();
62
+ // Findings the focus-loss probe reports as they happen, per route. A scan
63
+ // replaces lastFindings, so these are kept apart and added on top.
64
+ const eventFindings = new Map();
65
+ const routeChanges = [];
66
+ const currentRoute = () => location.pathname + location.search;
67
+ /** The last scan's findings plus the probe's findings for the current route. */
68
+ const pageFindings = () => [...lastFindings, ...(eventFindings.get(currentRoute()) ?? [])];
60
69
  // Show one component's issues only (null: all). Not remembered, and reset
61
70
  // on a route change: the components change from page to page.
62
71
  let componentFilter = null;
63
72
  let lastPath;
64
73
  /** Draw (or clear) each overlay layer from the last scan and the settings. */
65
74
  function draw() {
66
- const matching = visibleFindings(lastFindings, settings.minImpact, componentFilter);
75
+ const all = pageFindings();
76
+ const matching = visibleFindings(all, settings.minImpact, componentFilter);
67
77
  const shown = settings.highlights ? matching : [];
68
78
  pillView?.setStatus({
69
- found: lastFindings.length,
79
+ found: all.length,
70
80
  shown: shown.length,
71
81
  pages: visited.size,
72
82
  matching: matching.length,
73
83
  worst: worstImpact(matching),
74
84
  // Counted at the chosen severity, so an option's count matches the badge.
75
- components: componentCounts(visibleFindings(lastFindings, settings.minImpact)),
85
+ components: componentCounts(visibleFindings(all, settings.minImpact)),
76
86
  component: componentFilter,
87
+ routeChanges: routeChanges.slice(-5).reverse().map(describeNavigation),
77
88
  });
78
89
  if (!overlayView)
79
90
  return;
@@ -112,6 +123,7 @@ function devtoolsProviders(options) {
112
123
  enabled = next;
113
124
  writeStoredEnabled(storage, enabled);
114
125
  pillView?.setEnabled(enabled);
126
+ setProbe(enabled);
115
127
  if (enabled) {
116
128
  scanNow(); // don't wait for the app's next stable moment
117
129
  previewCurrentFocus();
@@ -246,7 +258,11 @@ function devtoolsProviders(options) {
246
258
  componentFilter = null;
247
259
  lastPath = location.pathname;
248
260
  // Label by route: a single-page app usually keeps one title on every route.
249
- visited.set(route, { label: route, url: location.href, findings });
261
+ visited.set(route, {
262
+ label: route,
263
+ url: location.href,
264
+ findings: [...findings, ...(eventFindings.get(route) ?? [])],
265
+ });
250
266
  draw();
251
267
  })
252
268
  .catch(() => undefined)
@@ -272,11 +288,62 @@ function devtoolsProviders(options) {
272
288
  };
273
289
  document.addEventListener('close', onTopLayerChange, true);
274
290
  document.addEventListener('toggle', onTopLayerChange, true);
291
+ // Focus lost between scans. Runs only while the tool is on, so off costs nothing.
292
+ let probe;
293
+ function onProbeFinding(finding, route) {
294
+ const list = eventFindings.get(route) ?? [];
295
+ const key = findingKey(route, finding);
296
+ if (list.some((f) => findingKey(route, f) === key))
297
+ return; // seen already
298
+ list.push(finding);
299
+ eventFindings.set(route, list);
300
+ const page = visited.get(route);
301
+ if (page)
302
+ visited.set(route, { ...page, findings: [...page.findings, finding] });
303
+ else
304
+ visited.set(route, { label: route, url: location.href, findings: [finding] });
305
+ if (log) {
306
+ (logger ?? console).warn(`♿ ${finding.component ?? 'unknown component'} · ${finding.impact} · ${finding.id}: ${finding.help}`, `\n ${finding.target}\n ${finding.helpUrl}`);
307
+ }
308
+ draw();
309
+ }
310
+ function onRouteChange(record) {
311
+ routeChanges.push(record);
312
+ if (routeChanges.length > 20)
313
+ routeChanges.shift();
314
+ if (log)
315
+ (logger ?? console).info(`♿ a11y-devtools: route change ${describeNavigation(record)}`);
316
+ draw();
317
+ }
318
+ function setProbe(on) {
319
+ if (!navigation)
320
+ return;
321
+ if (on && !probe) {
322
+ probe = createFocusLossProbe(document, {
323
+ frameworkPrefixes,
324
+ focusTarget,
325
+ onFinding: onProbeFinding,
326
+ onNavigation: onRouteChange,
327
+ });
328
+ }
329
+ else if (!on && probe) {
330
+ probe.stop();
331
+ probe = undefined;
332
+ }
333
+ }
334
+ setProbe(enabled);
335
+ // The probe checks for a route change as soon as the app settles, before
336
+ // the scan's quiet window.
337
+ const probeSubscription = appRef.isStable
338
+ .pipe(filter((stable) => stable))
339
+ .subscribe(() => probe?.notifyStable());
275
340
  const subscription = appRef.isStable
276
341
  .pipe(filter((stable) => stable), debounceTime(debounceMs))
277
342
  .subscribe(scanNow);
278
343
  destroyRef.onDestroy(() => {
279
344
  subscription.unsubscribe();
345
+ probeSubscription.unsubscribe();
346
+ probe?.stop();
280
347
  if (onFocusIn)
281
348
  document.removeEventListener('focusin', onFocusIn, true);
282
349
  if (onKeyDown)
@@ -22,6 +22,13 @@ const NGBR_RULES = {
22
22
  'ngbr/tab-order-mismatch': { criteria: NGBR_RULE_CRITERIA['ngbr/tab-order-mismatch'], ranWhen: 'keyboard' },
23
23
  'ngbr/modal-focus-not-contained': { criteria: NGBR_RULE_CRITERIA['ngbr/modal-focus-not-contained'], ranWhen: 'keyboard' },
24
24
  'ngbr/focus-trap': { criteria: NGBR_RULE_CRITERIA['ngbr/focus-trap'], ranWhen: 'focusTraps' },
25
+ 'ngbr/focus-lost-on-navigation': {
26
+ criteria: NGBR_RULE_CRITERIA['ngbr/focus-lost-on-navigation'],
27
+ ranWhen: 'navigation',
28
+ },
29
+ // Only the in-app overlay can see a re-render remove the focused element: no
30
+ // run checks for it, so it counts only when a report has its findings.
31
+ 'ngbr/focus-lost-on-rerender': { criteria: NGBR_RULE_CRITERIA['ngbr/focus-lost-on-rerender'] },
25
32
  };
26
33
  export function loadAxeRules() {
27
34
  const axe = createRequire(import.meta.url)('axe-core');
@@ -65,7 +72,7 @@ export function buildAcrWorksheet(report, axeRules = loadAxeRules()) {
65
72
  }
66
73
  for (const [rule, { criteria, ranWhen }] of Object.entries(NGBR_RULES)) {
67
74
  // A hand-built report has no `checks`: count a rule as run if it produced findings.
68
- const ran = report.checks ? report.checks[ranWhen] : allFindings.some((f) => f.id === rule);
75
+ const ran = report.checks && ranWhen ? report.checks[ranWhen] === true : allFindings.some((f) => f.id === rule);
69
76
  if (ran)
70
77
  criteria.forEach((id) => check(id, rule));
71
78
  }
@@ -1,6 +1,7 @@
1
1
  import type { A11yFinding, Impact } from '../scan.js';
2
2
  import type { BaselineDiff } from './baseline.js';
3
3
  import type { Walkthrough, WalkthroughStep } from '../keyboard/walkthrough.js';
4
+ import { type NavigationRecord } from '../navigation/record.js';
4
5
  /**
5
6
  * Pure formatting for report-mode: grouping + Markdown/JSON serialization. Kept
6
7
  * free of any Node or Playwright imports so the browser side (`report.ts`) can
@@ -24,6 +25,8 @@ export interface PageReport {
24
25
  darkOnly?: boolean;
25
26
  /** The tab order with each stop's computed role and name, when the run asked for it. */
26
27
  walkthrough?: Walkthrough;
28
+ /** How the route change into this page went, when the run moved between routes in the app. */
29
+ navigation?: NavigationRecord;
27
30
  }
28
31
  /** One-line explanation for a dark-only page, shared by the Markdown and HTML reports. */
29
32
  export declare const DARK_ONLY_NOTE = "Dark mode: lists only issues that don\u2019t also appear in light mode on this route.";
@@ -32,6 +35,10 @@ export declare const DARK_ONLY_NOTE = "Dark mode: lists only issues that don\u20
32
35
  * honesty rule as the overlay's Focus preview: computed, not a screen reader.
33
36
  */
34
37
  export declare const WALKTHROUGH_NOTE: string;
38
+ /** Heading note for the route change, shared by the Markdown and HTML reports. */
39
+ export declare const NAVIGATION_NOTE: string;
40
+ /** The route change as one line, saying how the run made it. */
41
+ export declare function formatNavigation(record: NavigationRecord): string;
35
42
  /** One walkthrough step as a single line, e.g. `button "Save" (disabled) — SaveBarComponent`. */
36
43
  export declare function formatStep(step: WalkthroughStep): string;
37
44
  /** "Showing the first 300 of 412 tab stops." when the list was capped, else ''. */
@@ -62,6 +69,8 @@ export interface ScanChecks {
62
69
  focusTraps: boolean;
63
70
  /** Each page lists its tab order with computed roles and names. */
64
71
  walkthrough?: boolean;
72
+ /** The run moved between the routes inside the app and checked focus each time. */
73
+ navigation?: boolean;
65
74
  }
66
75
  /** A whole report-mode run across one or more pages. */
67
76
  export interface ScanReport {
@@ -1,4 +1,5 @@
1
1
  import { findingCriteria, referenceUrl } from './wcag.js';
2
+ import { describeNavigation } from '../navigation/record.js';
2
3
  /** One-line explanation for a dark-only page, shared by the Markdown and HTML reports. */
3
4
  export const DARK_ONLY_NOTE = 'Dark mode: lists only issues that don’t also appear in light mode on this route.';
4
5
  /**
@@ -7,6 +8,18 @@ export const DARK_ONLY_NOTE = 'Dark mode: lists only issues that don’t also ap
7
8
  */
8
9
  export const WALKTHROUGH_NOTE = 'Each tab stop in order, with its computed role, name and states. A computed approximation, ' +
9
10
  'not what any one screen reader announces.';
11
+ /** Heading note for the route change, shared by the Markdown and HTML reports. */
12
+ export const NAVIGATION_NOTE = 'The run moved here from the previous route inside the app, the way a keyboard user would. ' +
13
+ 'Where focus went, whether the page title changed, and what live regions announced.';
14
+ /** The route change as one line, saying how the run made it. */
15
+ export function formatNavigation(record) {
16
+ const how = record.via === 'link'
17
+ ? ' (pressed Enter on a link)'
18
+ : record.via === 'history'
19
+ ? ' (no link to this route, so the run changed the URL with history.pushState)'
20
+ : '';
21
+ return `${describeNavigation(record)}${how}`;
22
+ }
10
23
  /** One walkthrough step as a single line, e.g. `button "Save" (disabled) — SaveBarComponent`. */
11
24
  export function formatStep(step) {
12
25
  const role = step.role ?? `<${step.tag}>`;
@@ -106,6 +119,7 @@ export function toJson(report, diff) {
106
119
  nodeInstances: p.findings.length,
107
120
  findings: p.findings,
108
121
  ...(p.walkthrough && { walkthrough: p.walkthrough }),
122
+ ...(p.navigation && { navigation: p.navigation }),
109
123
  })),
110
124
  }, null, 2);
111
125
  }
@@ -141,9 +155,17 @@ export function parseReport(json) {
141
155
  ...(p.colorScheme && { colorScheme: p.colorScheme }),
142
156
  ...(p.darkOnly && { darkOnly: true }),
143
157
  ...(isWalkthrough(p.walkthrough) && { walkthrough: p.walkthrough }),
158
+ ...(isNavigationRecord(p.navigation) && { navigation: p.navigation }),
144
159
  })),
145
160
  };
146
161
  }
162
+ function isNavigationRecord(n) {
163
+ const r = n;
164
+ return (typeof r?.from === 'string' &&
165
+ typeof r.to === 'string' &&
166
+ typeof r.focus === 'string' &&
167
+ Array.isArray(r.announcements));
168
+ }
147
169
  function isWalkthrough(w) {
148
170
  return Array.isArray(w?.steps) && typeof w.total === 'number';
149
171
  }
@@ -213,6 +235,7 @@ export function toMarkdown(report, diff) {
213
235
  if (page.findings.length === 0) {
214
236
  lines.push('No automated violations found. ✅');
215
237
  lines.push('');
238
+ lines.push(...markdownNavigation(page));
216
239
  lines.push(...markdownWalkthrough(page));
217
240
  continue;
218
241
  }
@@ -236,10 +259,19 @@ export function toMarkdown(report, diff) {
236
259
  }
237
260
  lines.push('');
238
261
  }
262
+ lines.push(...markdownNavigation(page));
239
263
  lines.push(...markdownWalkthrough(page));
240
264
  }
241
265
  return lines.join('\n');
242
266
  }
267
+ /** The route change into a page under its own heading, or nothing. */
268
+ function markdownNavigation(page) {
269
+ if (!page.navigation)
270
+ return [];
271
+ // Titles and announcements are page text: escape anything Markdown would read as markup.
272
+ const line = formatNavigation(page.navigation).replace(/([<>*_`[\]\\|&])/g, '\\$1');
273
+ return ['### Route change', '', `_${NAVIGATION_NOTE}_`, '', line, ''];
274
+ }
243
275
  /** A page's walkthrough as a numbered Markdown list under its own heading, or nothing. */
244
276
  function markdownWalkthrough(page) {
245
277
  const walkthrough = page.walkthrough;