@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.
@@ -89,6 +89,16 @@ export interface ScanPagesOptions {
89
89
  * light pass only. Default false.
90
90
  */
91
91
  walkthrough?: boolean;
92
+ /**
93
+ * Also move between the routes inside the app, in the order given, the way a
94
+ * keyboard user would: focus a link to the next route and press Enter, or
95
+ * when the page has no such link, change the URL with `history.pushState`.
96
+ * Each route then records where focus went, whether the title changed and
97
+ * what live regions announced, and focus left on the page body is reported
98
+ * as `ngbr/focus-lost-on-navigation`. Runs in its own browser session after
99
+ * the scan, once (in the light scheme with `colorScheme: 'both'`). Default false.
100
+ */
101
+ navigation?: boolean;
92
102
  }
93
103
  /**
94
104
  * Drive a real headless browser over a running Angular **dev** build and return
@@ -58,6 +58,147 @@ async function walkForFocusTrap(page, frameworkPrefixes) {
58
58
  }
59
59
  return null;
60
60
  }
61
+ /** A route as the focus-loss probe keys it: path and query, plus a `#/` hash. */
62
+ function routeKey(url) {
63
+ return url.pathname + url.search + (url.hash.startsWith('#/') ? url.hash : '');
64
+ }
65
+ /**
66
+ * Load the first route, then move to each next route inside the app and ask the
67
+ * in-page probe what happened to focus. Results are keyed by the route's index
68
+ * in `routes`. A full page load (a link outside the app's router) is not a
69
+ * route change inside the app, so it's skipped with a warning.
70
+ */
71
+ async function navigationPass(browser, colorScheme, config) {
72
+ const { baseUrl, routes, waitMs, inPageScript, frameworkPrefixes } = config;
73
+ const results = new Map();
74
+ if (routes.length < 2)
75
+ return results;
76
+ const context = await browser.newContext({
77
+ viewport: { width: 1280, height: 900 },
78
+ colorScheme,
79
+ bypassCSP: true,
80
+ });
81
+ try {
82
+ const page = await context.newPage();
83
+ if (config.setup) {
84
+ await page.goto(baseUrl, { waitUntil: 'domcontentloaded' });
85
+ await config.setup(page, { colorScheme });
86
+ }
87
+ const settle = async () => {
88
+ await page.waitForLoadState('networkidle').catch(() => undefined);
89
+ await page.waitForTimeout(waitMs);
90
+ };
91
+ // What the probe has reported so far, so each route takes only its own.
92
+ let recordCount = 0;
93
+ let findingCount = 0;
94
+ const startProbe = async () => {
95
+ recordCount = 0;
96
+ findingCount = 0;
97
+ await page.addStyleTag({ content: HIDE_OVERLAY_CSS });
98
+ await page.addScriptTag({ content: inPageScript });
99
+ await page.evaluate((prefixes) => {
100
+ const w = window;
101
+ w.__ngbA11yFocusLossProbe = w.__ngbA11yCreateFocusLossProbe(prefixes);
102
+ }, frameworkPrefixes);
103
+ };
104
+ const probeRunning = () => page.evaluate(() => window.__ngbA11yFocusLossProbe !== undefined);
105
+ const first = new URL(routes[0], baseUrl).toString();
106
+ await page.goto(first, { waitUntil: 'networkidle' }).catch(() => page.goto(first));
107
+ await page.waitForTimeout(waitMs);
108
+ await startProbe();
109
+ for (let i = 1; i < routes.length; i++) {
110
+ const route = routes[i];
111
+ const target = new URL(route, baseUrl);
112
+ try {
113
+ // Focus a visible link in the page that goes to this route, in the same
114
+ // tab. Without one, change the URL: the Angular Router (like most SPA
115
+ // routers) follows popstate.
116
+ const via = await page.evaluate((href) => {
117
+ const key = (u) => u.pathname + u.search + (u.hash.startsWith('#/') ? u.hash : '');
118
+ const wanted = key(new URL(href));
119
+ for (const link of document.querySelectorAll('a[href]')) {
120
+ if (!(link instanceof HTMLAnchorElement))
121
+ continue; // an SVG <a>
122
+ if (link.target && link.target !== '_self')
123
+ continue;
124
+ if (link.closest('[data-ngb-a11y-overlay], [inert], [aria-hidden="true"]'))
125
+ continue;
126
+ if (typeof link.checkVisibility === 'function' && !link.checkVisibility())
127
+ continue;
128
+ let url;
129
+ try {
130
+ url = new URL(link.href);
131
+ }
132
+ catch {
133
+ continue;
134
+ }
135
+ if (url.origin !== location.origin || key(url) !== wanted)
136
+ continue;
137
+ link.focus();
138
+ if (document.activeElement === link)
139
+ return 'link';
140
+ }
141
+ history.pushState(null, '', href);
142
+ dispatchEvent(new PopStateEvent('popstate', { state: null }));
143
+ return 'history';
144
+ }, target.toString());
145
+ if (via === 'link')
146
+ await page.keyboard.press('Enter');
147
+ await settle();
148
+ if (!(await probeRunning())) {
149
+ console.warn(`ngbr-a11y-report: moving to ${route} loaded a new page, so it wasn't a route change ` +
150
+ `inside the app; skipped the focus check.`);
151
+ await startProbe();
152
+ continue;
153
+ }
154
+ const seen = await page.evaluate(async () => {
155
+ const probe = window.__ngbA11yFocusLossProbe;
156
+ probe.notifyStable();
157
+ await probe.settled();
158
+ return { records: probe.records(), findings: probe.findings() };
159
+ });
160
+ const record = seen.records.length > recordCount ? seen.records.at(-1) : undefined;
161
+ recordCount = seen.records.length;
162
+ const findings = seen.findings.slice(findingCount);
163
+ findingCount = seen.findings.length;
164
+ if (!record) {
165
+ console.warn(`ngbr-a11y-report: moving to ${route} didn't change the route; skipped the focus check.`);
166
+ continue;
167
+ }
168
+ if (record.to !== routeKey(target)) {
169
+ console.warn(`ngbr-a11y-report: moving to ${route} ended on ${record.to} (a redirect?).`);
170
+ }
171
+ results.set(i, { record: { ...record, via }, findings });
172
+ }
173
+ catch (err) {
174
+ const message = err instanceof Error ? err.message : String(err);
175
+ console.warn(`ngbr-a11y-report: route change to ${route} failed: ${message}`);
176
+ // Start again from what's on the page now, so the next route takes only its own results.
177
+ try {
178
+ await settle();
179
+ if (!(await probeRunning())) {
180
+ await startProbe();
181
+ }
182
+ else {
183
+ const counts = await page.evaluate(() => {
184
+ const probe = window.__ngbA11yFocusLossProbe;
185
+ return { records: probe.records().length, findings: probe.findings().length };
186
+ });
187
+ recordCount = counts.records;
188
+ findingCount = counts.findings;
189
+ }
190
+ }
191
+ catch {
192
+ // The page is gone; the next route's own error says so.
193
+ }
194
+ }
195
+ }
196
+ }
197
+ finally {
198
+ await context.close();
199
+ }
200
+ return results;
201
+ }
61
202
  /** Settle time after switching a class/attribute theme, so colour transitions finish before axe reads them. */
62
203
  const THEME_SETTLE_MS = 300;
63
204
  /**
@@ -161,7 +302,7 @@ async function scanPass(browser, colorScheme, config) {
161
302
  * to the component that rendered it — with no change to the target app.
162
303
  */
163
304
  export async function scanPages(options) {
164
- const { baseUrl, routes, tags, waitMs = 1500, labels = {}, setup, beforeScan, headed = false, frameworkPrefixes, keyboard, focusTraps = false, walkthrough = false, darkClass, darkAttribute, } = options;
305
+ const { baseUrl, routes, tags, waitMs = 1500, labels = {}, setup, beforeScan, headed = false, frameworkPrefixes, keyboard, focusTraps = false, walkthrough = false, navigation = false, darkClass, darkAttribute, } = options;
165
306
  const colorScheme = options.colorScheme ?? (darkClass || darkAttribute ? 'both' : 'light');
166
307
  const config = {
167
308
  baseUrl,
@@ -174,6 +315,7 @@ export async function scanPages(options) {
174
315
  keyboard,
175
316
  focusTraps,
176
317
  walkthrough,
318
+ navigation,
177
319
  setup,
178
320
  beforeScan,
179
321
  darkClass,
@@ -182,12 +324,27 @@ export async function scanPages(options) {
182
324
  const { chromium } = await loadPlaywright();
183
325
  const browser = await chromium.launch({ headless: !headed });
184
326
  let pages;
327
+ let moves = new Map();
185
328
  try {
329
+ // Route changes don't depend on the theme: check them once.
330
+ if (navigation && routes.length < 2) {
331
+ console.warn('ngbr-a11y-report: --navigation needs 2 or more routes; skipped the route-change check.');
332
+ }
333
+ moves = navigation
334
+ ? await navigationPass(browser, colorScheme === 'both' ? 'light' : colorScheme, config)
335
+ : new Map();
336
+ // A route that failed to scan keeps only its error.
337
+ const withMoves = (scanned) => scanned.map((page, i) => {
338
+ const move = moves.get(i);
339
+ return move && !page.error
340
+ ? { ...page, findings: [...page.findings, ...move.findings], navigation: move.record }
341
+ : page;
342
+ });
186
343
  if (colorScheme !== 'both') {
187
- pages = await scanPass(browser, colorScheme, config);
344
+ pages = withMoves(await scanPass(browser, colorScheme, config));
188
345
  }
189
346
  else {
190
- const light = await scanPass(browser, 'light', config);
347
+ const light = withMoves(await scanPass(browser, 'light', config));
191
348
  // Keyboard traps and the tab order don't depend on the theme; doing them twice only costs time.
192
349
  const dark = await scanPass(browser, 'dark', { ...config, focusTraps: false, walkthrough: false });
193
350
  // Interleave per route (light, then its dark) and keep only what dark adds.
@@ -209,6 +366,8 @@ export async function scanPages(options) {
209
366
  keyboard: keyboard ?? false,
210
367
  focusTraps,
211
368
  ...(walkthrough && { walkthrough }),
369
+ // Only when at least one route change was checked, so the ACR doesn't count a check that didn't happen.
370
+ ...(moves.size > 0 && { navigation: true }),
212
371
  };
213
372
  return { generatedAt: new Date().toISOString(), checks, pages };
214
373
  }
@@ -1,4 +1,4 @@
1
- import { addedBySeverity, COVERAGE_URL, DARK_ONLY_NOTE, formatStep, REPORT_SCOPE_NOTE, REPORT_TITLE, bySeverity, distinctRuleCount, groupByComponent, viaNames, walkthroughCapNote, WALKTHROUGH_NOTE, } from './format.js';
1
+ import { addedBySeverity, COVERAGE_URL, DARK_ONLY_NOTE, formatNavigation, formatStep, NAVIGATION_NOTE, REPORT_SCOPE_NOTE, REPORT_TITLE, bySeverity, distinctRuleCount, groupByComponent, viaNames, walkthroughCapNote, WALKTHROUGH_NOTE, } from './format.js';
2
2
  import { findingCriteria, referenceUrl } from './wcag.js';
3
3
  /**
4
4
  * A single self-contained HTML report: inline CSS, no scripts, no external
@@ -139,6 +139,7 @@ export function toHtml(report, diff) {
139
139
  }
140
140
  if (page.findings.length === 0) {
141
141
  out.push('<p class="ok">No automated violations found.</p>');
142
+ out.push(...htmlNavigation(page));
142
143
  out.push(...htmlWalkthrough(page));
143
144
  out.push('</section>');
144
145
  return;
@@ -170,6 +171,7 @@ export function toHtml(report, diff) {
170
171
  out.push('</ul>');
171
172
  out.push('</div>');
172
173
  }
174
+ out.push(...htmlNavigation(page));
173
175
  out.push(...htmlWalkthrough(page));
174
176
  out.push('</section>');
175
177
  });
@@ -178,6 +180,18 @@ export function toHtml(report, diff) {
178
180
  out.push('</html>');
179
181
  return out.join('\n');
180
182
  }
183
+ /** The route change into a page under its own heading, or nothing. */
184
+ function htmlNavigation(page) {
185
+ if (!page.navigation)
186
+ return [];
187
+ return [
188
+ '<div class="walkthrough">',
189
+ '<h3>Route change</h3>',
190
+ `<p class="meta">${escapeHtml(NAVIGATION_NOTE)}</p>`,
191
+ `<p>${escapeHtml(formatNavigation(page.navigation))}</p>`,
192
+ '</div>',
193
+ ];
194
+ }
181
195
  /** A page's walkthrough as an ordered list under its own heading, or nothing. */
182
196
  function htmlWalkthrough(page) {
183
197
  const walkthrough = page.walkthrough;
@@ -92,6 +92,8 @@ export const NGBR_RULE_CRITERIA = {
92
92
  'ngbr/tab-order-mismatch': ['2.4.3'],
93
93
  'ngbr/modal-focus-not-contained': ['2.4.3'],
94
94
  'ngbr/focus-trap': ['2.1.2'],
95
+ 'ngbr/focus-lost-on-navigation': ['2.4.3'],
96
+ 'ngbr/focus-lost-on-rerender': ['2.4.3'],
95
97
  };
96
98
  /** The `wcag` list for an `ngbr/*` finding; [] for an unknown id. */
97
99
  export function ngbrRuleCriteria(id) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngbracket/a11y-devtools",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Finds accessibility problems in Angular apps and names the component behind each one. A dev overlay, or headless reports for CI.",
5
5
  "license": "MIT",
6
6
  "author": "Duncan Faulkner",
@@ -82,6 +82,7 @@
82
82
  "@angular/forms": "^22.2.1",
83
83
  "@angular/platform-browser": "^22.2.1",
84
84
  "@angular/platform-browser-dynamic": "^22.2.1",
85
+ "@angular/router": "^22.2.1",
85
86
  "@emnapi/core": "^1.11.3",
86
87
  "@emnapi/runtime": "^1.11.3",
87
88
  "@oxc-project/runtime": "^0.149.0",