@ngbracket/a11y-devtools 0.8.0 → 0.10.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.
@@ -1,6 +1,8 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { dirname, resolve } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { detectTabTrap } from '../keyboard/focus-walk.js';
5
+ import { findingsNotIn } from './baseline.js';
4
6
  async function loadPlaywright() {
5
7
  try {
6
8
  return await import('playwright');
@@ -15,49 +17,156 @@ function inPageScriptPath() {
15
17
  return resolve(dirname(fileURLToPath(import.meta.url)), '..', 'inpage.global.js');
16
18
  }
17
19
  /**
18
- * Drive a real headless browser over a running Angular **dev** build and return
19
- * component-attributed findings per route. The scan runs *in the page* (via the
20
- * injected in-page bundle), so `window.ng` is live and each violation is mapped
21
- * to the component that rendered it — with no change to the target app.
20
+ * Press Tab through the page until focus either laps the page (no trap) or
21
+ * cycles inside part of it (a trap), then check whether Shift+Tab gets out.
22
+ * Needs the in-page bundle already injected. Returns null when there's no trap,
23
+ * or when the press budget runs out before a verdict (inconclusive — e.g. focus
24
+ * stuck inside an iframe the parent can't see into).
22
25
  */
23
- export async function scanPages(options) {
24
- const { baseUrl, routes, tags, waitMs = 1500, labels = {}, setup, headed = false, frameworkPrefixes, keyboard, } = options;
25
- const axeOptions = tags
26
- ? { runOnly: { type: 'tag', values: tags } }
27
- : undefined;
28
- const inPageScript = readFileSync(inPageScriptPath(), 'utf8');
29
- const { chromium } = await loadPlaywright();
30
- const browser = await chromium.launch({ headless: !headed });
26
+ async function walkForFocusTrap(page, frameworkPrefixes) {
27
+ const stops = await page.evaluate((prefixes) => {
28
+ const w = window;
29
+ w.__ngbA11yFocusProbe = w.__ngbA11yCreateFocusProbe(prefixes);
30
+ return w.__ngbA11yFocusProbe.stopCount();
31
+ }, frameworkPrefixes);
32
+ const probe = () => page.evaluate(() => window.__ngbA11yFocusProbe.probe());
33
+ // Enough for two laps of the page, capped so a huge page can't run forever.
34
+ const budget = Math.min(stops * 2 + 10, 400);
35
+ const observations = [];
36
+ const frames = new Set();
37
+ for (let i = 0; i < budget; i++) {
38
+ await page.keyboard.press('Tab');
39
+ const { id, iframe } = await probe();
40
+ if (iframe && id !== null)
41
+ frames.add(id);
42
+ observations.push(id);
43
+ const verdict = detectTabTrap(observations, frames);
44
+ if (verdict.kind === 'complete')
45
+ return null;
46
+ if (verdict.kind === 'trap') {
47
+ const inCycle = new Set(verdict.cycle);
48
+ let shiftTabEscapes = false;
49
+ for (let j = 0; j < verdict.cycle.length + 2 && !shiftTabEscapes; j++) {
50
+ await page.keyboard.press('Shift+Tab');
51
+ const { id: back } = await probe();
52
+ shiftTabEscapes = back === null || !inCycle.has(back);
53
+ }
54
+ return page.evaluate(([cycle, escapes]) => window.__ngbA11yFocusProbe.trapFinding(cycle, escapes), [verdict.cycle, shiftTabEscapes]);
55
+ }
56
+ }
57
+ return null;
58
+ }
59
+ /** Settle time after switching a class/attribute theme, so colour transitions finish before axe reads them. */
60
+ const THEME_SETTLE_MS = 300;
61
+ /** Scan every route in one colour scheme, in its own browser context. */
62
+ async function scanPass(browser, colorScheme, config) {
63
+ const { baseUrl, routes, labels, waitMs, axeOptions, inPageScript, frameworkPrefixes } = config;
64
+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme });
31
65
  const pages = [];
32
66
  try {
33
- const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
34
67
  const page = await context.newPage();
35
- if (setup) {
68
+ if (config.setup) {
36
69
  await page.goto(baseUrl, { waitUntil: 'domcontentloaded' });
37
- await setup(page);
70
+ await config.setup(page, { colorScheme });
38
71
  }
39
72
  for (const route of routes) {
40
73
  const url = new URL(route, baseUrl).toString();
41
- const label = labels[route] ?? route;
74
+ const base = labels[route] ?? route;
75
+ // Dark pages get their own label, so a dark page's baseline identity never
76
+ // collides with the same route's light page.
77
+ const label = colorScheme === 'dark' ? `${base} (dark)` : base;
42
78
  try {
43
79
  // networkidle is the right settle signal for an SPA, but some apps keep a
44
80
  // socket open and never reach it — fall back to a plain load.
45
81
  await page.goto(url, { waitUntil: 'networkidle' }).catch(() => page.goto(url));
46
82
  await page.waitForTimeout(waitMs);
83
+ if (colorScheme === 'dark' && (config.darkClass || config.darkAttribute)) {
84
+ await page.evaluate(({ cls, attr }) => {
85
+ if (cls)
86
+ document.documentElement.classList.add(cls);
87
+ if (attr)
88
+ document.documentElement.setAttribute(attr.name, attr.value);
89
+ }, { cls: config.darkClass, attr: config.darkAttribute });
90
+ await page.waitForTimeout(THEME_SETTLE_MS);
91
+ }
92
+ if (config.beforeScan)
93
+ await config.beforeScan(page, { colorScheme, route });
47
94
  await page.addScriptTag({ content: inPageScript });
48
95
  const findings = (await page.evaluate((args) => {
49
96
  const w = window;
50
97
  return w.__ngbA11yScan(args.axe, args.scan);
51
- }, { axe: axeOptions, scan: { frameworkPrefixes, keyboard } }));
52
- pages.push({ label, url: page.url(), findings });
98
+ }, { axe: axeOptions, scan: { frameworkPrefixes, keyboard: config.keyboard } }));
99
+ if (config.focusTraps) {
100
+ // A failed walk shouldn't throw away the scan's findings — warn and move on.
101
+ try {
102
+ const trap = await walkForFocusTrap(page, frameworkPrefixes);
103
+ if (trap)
104
+ findings.push(trap);
105
+ }
106
+ catch (err) {
107
+ const message = err instanceof Error ? err.message : String(err);
108
+ console.warn(`ngbr-a11y-report: focus-trap walk failed on ${label}: ${message}`);
109
+ }
110
+ }
111
+ pages.push({ label, url: page.url(), findings, colorScheme });
53
112
  }
54
113
  catch (err) {
55
114
  // One bad route shouldn't sink the whole run — record it and continue.
56
115
  const message = err instanceof Error ? err.message : String(err);
57
- pages.push({ label, url, findings: [], error: message });
116
+ pages.push({ label, url, findings: [], error: message, colorScheme });
58
117
  }
59
118
  }
60
119
  }
120
+ finally {
121
+ await context.close();
122
+ }
123
+ return pages;
124
+ }
125
+ /**
126
+ * Drive a real headless browser over a running Angular **dev** build and return
127
+ * component-attributed findings per route. The scan runs *in the page* (via the
128
+ * injected in-page bundle), so `window.ng` is live and each violation is mapped
129
+ * to the component that rendered it — with no change to the target app.
130
+ */
131
+ export async function scanPages(options) {
132
+ const { baseUrl, routes, tags, waitMs = 1500, labels = {}, setup, beforeScan, headed = false, frameworkPrefixes, keyboard, focusTraps = false, darkClass, darkAttribute, } = options;
133
+ const colorScheme = options.colorScheme ?? (darkClass || darkAttribute ? 'both' : 'light');
134
+ const config = {
135
+ baseUrl,
136
+ routes,
137
+ labels,
138
+ waitMs,
139
+ axeOptions: tags ? { runOnly: { type: 'tag', values: tags } } : undefined,
140
+ inPageScript: readFileSync(inPageScriptPath(), 'utf8'),
141
+ frameworkPrefixes,
142
+ keyboard,
143
+ focusTraps,
144
+ setup,
145
+ beforeScan,
146
+ darkClass,
147
+ darkAttribute,
148
+ };
149
+ const { chromium } = await loadPlaywright();
150
+ const browser = await chromium.launch({ headless: !headed });
151
+ let pages;
152
+ try {
153
+ if (colorScheme !== 'both') {
154
+ pages = await scanPass(browser, colorScheme, config);
155
+ }
156
+ else {
157
+ const light = await scanPass(browser, 'light', config);
158
+ // A keyboard trap doesn't depend on the theme; walking it twice only costs time.
159
+ const dark = await scanPass(browser, 'dark', { ...config, focusTraps: false });
160
+ // Interleave per route (light, then its dark) and keep only what dark adds.
161
+ pages = light.flatMap((lightPage, i) => {
162
+ const darkPage = dark[i];
163
+ const findings = lightPage.error
164
+ ? darkPage.findings
165
+ : findingsNotIn(darkPage.findings, lightPage.findings);
166
+ return [lightPage, { ...darkPage, findings, darkOnly: true }];
167
+ });
168
+ }
169
+ }
61
170
  finally {
62
171
  await browser.close();
63
172
  }
@@ -0,0 +1,4 @@
1
+ import type { BaselineDiff } from './baseline.js';
2
+ import { type ScanReport } from './format.js';
3
+ /** Render the report as one self-contained, accessible HTML document. */
4
+ export declare function toHtml(report: ScanReport, diff?: BaselineDiff): string;
@@ -0,0 +1,168 @@
1
+ import { addedBySeverity, DARK_ONLY_NOTE, bySeverity, distinctRuleCount, groupByComponent, viaNames, } from './format.js';
2
+ /**
3
+ * A single self-contained HTML report: inline CSS, no scripts, no external
4
+ * requests — so it can be attached to a CI run, emailed, or opened offline.
5
+ * Same content as the Markdown report (summary, optional baseline comparison,
6
+ * findings grouped by owning component, most severe first).
7
+ *
8
+ * An accessibility tool's own report has to be accessible: landmarks, a
9
+ * sequential heading outline, a real data table with header cells, severity
10
+ * given as text (never colour alone), and AA contrast in light and dark
11
+ * schemes. Component groups are plain `<h3>` sections rather than
12
+ * `<details>`: a heading inside `<summary>` loses its heading semantics in some
13
+ * browsers, and heading navigation is how screen-reader users move through a
14
+ * long report.
15
+ */
16
+ function escapeHtml(text) {
17
+ return text
18
+ .replace(/&/g, '&amp;')
19
+ .replace(/</g, '&lt;')
20
+ .replace(/>/g, '&gt;')
21
+ .replace(/"/g, '&quot;')
22
+ .replace(/'/g, '&#39;');
23
+ }
24
+ /** Only http(s) links are rendered as links; anything else stays plain text. */
25
+ function safeHref(url) {
26
+ return /^https?:\/\//i.test(url) ? escapeHtml(url) : null;
27
+ }
28
+ const STYLES = `
29
+ :root {
30
+ color-scheme: light dark;
31
+ --bg: #ffffff; --fg: #1a1a1a; --muted: #555555; --line: #d9d9d9; --panel: #f6f6f6;
32
+ --critical: #a4001d; --serious: #9a4400; --moderate: #6b5300; --minor: #1f4e9c;
33
+ --new: #0b6b3a; --link: #0b57d0;
34
+ }
35
+ @media (prefers-color-scheme: dark) {
36
+ :root {
37
+ --bg: #161616; --fg: #ececec; --muted: #b5b5b5; --line: #3a3a3a; --panel: #222222;
38
+ --critical: #ff8a9a; --serious: #ffb77a; --moderate: #f0d060; --minor: #9cc3ff;
39
+ --new: #7ee0a8; --link: #9cc3ff;
40
+ }
41
+ }
42
+ * { box-sizing: border-box; }
43
+ body { margin: 0; background: var(--bg); color: var(--fg);
44
+ font: 15px/1.55 system-ui, -apple-system, "Segoe UI", sans-serif; }
45
+ main { max-width: 960px; margin: 0 auto; padding: 32px 16px 64px; }
46
+ h1 { font-size: 1.6rem; margin: 0 0 4px; }
47
+ h2 { font-size: 1.25rem; margin: 40px 0 12px; padding-top: 16px; border-top: 1px solid var(--line); }
48
+ h3 { font-size: 1.05rem; margin: 0 0 4px; }
49
+ .meta { color: var(--muted); margin: 0 0 24px; }
50
+ a { color: var(--link); }
51
+ code { font: 0.9em/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; }
52
+ table { border-collapse: collapse; width: 100%; margin: 8px 0 16px; }
53
+ th, td { text-align: left; padding: 6px 10px; border-bottom: 1px solid var(--line); }
54
+ th[scope="col"]:not(:first-child), td:not(:first-child) { text-align: right; }
55
+ tfoot th, tfoot td { font-weight: 700; }
56
+ .table-wrap { overflow-x: auto; }
57
+ .component { background: var(--panel); border: 1px solid var(--line); border-radius: 8px;
58
+ margin: 12px 0; padding: 12px 14px 0; }
59
+ .count { color: var(--muted); font-weight: 400; }
60
+ a:focus-visible { outline: 3px solid var(--link); outline-offset: 2px; }
61
+ .visually-hidden { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0;
62
+ overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
63
+ ul.findings { list-style: none; margin: 0 0 12px; padding: 0; }
64
+ ul.findings > li { padding: 10px 0; border-top: 1px solid var(--line); }
65
+ .impact { font-weight: 700; text-transform: uppercase; font-size: 0.8em; letter-spacing: 0.04em; }
66
+ .impact-critical { color: var(--critical); } .impact-serious { color: var(--serious); }
67
+ .impact-moderate { color: var(--moderate); } .impact-minor { color: var(--minor); }
68
+ .new { font-weight: 700; color: var(--new); }
69
+ .rule { font-weight: 600; }
70
+ .via, .detail { color: var(--muted); font-size: 0.92em; }
71
+ .detail { margin: 4px 0 0; }
72
+ .ok { color: var(--new); font-weight: 600; }
73
+ .error { color: var(--critical); font-weight: 600; }
74
+ .diff { background: var(--panel); border: 1px solid var(--line); border-radius: 8px;
75
+ margin-top: 32px; padding: 4px 16px; }
76
+ .diff h2 { border-top: 0; margin-top: 12px; padding-top: 0; }
77
+ `;
78
+ /** Render the report as one self-contained, accessible HTML document. */
79
+ export function toHtml(report, diff) {
80
+ const all = report.pages.flatMap((p) => p.findings);
81
+ const added = new Set(diff?.added.map((a) => a.finding));
82
+ const out = [];
83
+ out.push('<!doctype html>');
84
+ out.push('<html lang="en">');
85
+ out.push('<head>');
86
+ out.push('<meta charset="utf-8">');
87
+ out.push('<meta name="viewport" content="width=device-width, initial-scale=1">');
88
+ out.push('<title>Accessibility report</title>');
89
+ out.push(`<style>${STYLES}</style>`);
90
+ out.push('</head>');
91
+ out.push('<body>');
92
+ out.push('<main>');
93
+ out.push('<h1>Accessibility report</h1>');
94
+ out.push(`<p class="meta">Generated <time datetime="${escapeHtml(report.generatedAt)}">${escapeHtml(report.generatedAt)}</time> · @ngbracket/a11y-devtools report-mode</p>`);
95
+ // Summary — distinct rules next to raw node-instances, so the bigger number
96
+ // can't be read on its own as "how bad is it".
97
+ out.push('<section aria-labelledby="summary">');
98
+ out.push('<h2 id="summary">Summary</h2>');
99
+ out.push('<div class="table-wrap"><table>');
100
+ out.push('<thead><tr><th scope="col">Page</th><th scope="col">Distinct rules</th><th scope="col">Node-instances</th><th scope="col">Components</th></tr></thead>');
101
+ out.push('<tbody>');
102
+ for (const page of report.pages) {
103
+ out.push(`<tr><th scope="row">${escapeHtml(page.label)}</th><td>${distinctRuleCount(page.findings)}</td><td>${page.findings.length}</td><td>${groupByComponent(page.findings).size}</td></tr>`);
104
+ }
105
+ out.push('</tbody>');
106
+ out.push(`<tfoot><tr><th scope="row">Total</th><td>${distinctRuleCount(all)}</td><td>${all.length}</td><td>${groupByComponent(all).size}</td></tr></tfoot>`);
107
+ out.push('</table></div>');
108
+ out.push('</section>');
109
+ if (diff) {
110
+ out.push('<section aria-labelledby="baseline" class="diff">');
111
+ out.push('<h2 id="baseline">Compared with baseline</h2>');
112
+ out.push(`<p><strong class="new">${diff.added.length} new</strong> · ${diff.fixed.length} fixed · ${diff.unchanged} unchanged</p>`);
113
+ if (diff.added.length) {
114
+ out.push('<ul>');
115
+ for (const { page, finding } of addedBySeverity(diff)) {
116
+ out.push(`<li><span class="impact impact-${escapeHtml(finding.impact ?? 'none')}">${escapeHtml(finding.impact ?? 'n/a')}</span> <span class="rule">${escapeHtml(finding.id)}</span> on ${escapeHtml(page)}, in ${escapeHtml(finding.component ?? '(unknown component)')}: <code>${escapeHtml(finding.target)}</code></li>`);
117
+ }
118
+ out.push('</ul>');
119
+ }
120
+ out.push('</section>');
121
+ }
122
+ report.pages.forEach((page, i) => {
123
+ const headingId = `page-${i + 1}`;
124
+ out.push(`<section aria-labelledby="${headingId}">`);
125
+ out.push(`<h2 id="${headingId}">${escapeHtml(page.label)} <code>${escapeHtml(page.url)}</code></h2>`);
126
+ if (page.darkOnly)
127
+ out.push(`<p class="meta">${escapeHtml(DARK_ONLY_NOTE)}</p>`);
128
+ if (page.error) {
129
+ out.push(`<p class="error">Scan failed: ${escapeHtml(page.error)}</p>`);
130
+ out.push('</section>');
131
+ return;
132
+ }
133
+ if (page.findings.length === 0) {
134
+ out.push('<p class="ok">No violations found.</p>');
135
+ out.push('</section>');
136
+ return;
137
+ }
138
+ out.push(`<p>${page.findings.length} node-instance(s) across ${distinctRuleCount(page.findings)} distinct rule(s).</p>`);
139
+ const byComponent = [...groupByComponent(page.findings)].sort((a, b) => b[1].length - a[1].length);
140
+ for (const [component, items] of byComponent) {
141
+ out.push('<div class="component">');
142
+ out.push(`<h3>${escapeHtml(component)} <span class="count">— ${items.length} issue(s)</span></h3>`);
143
+ out.push('<ul class="findings">');
144
+ for (const finding of bySeverity(items)) {
145
+ const via = viaNames(finding);
146
+ const href = safeHref(finding.helpUrl);
147
+ const impact = finding.impact ?? 'n/a';
148
+ out.push('<li>');
149
+ out.push(`${added.has(finding) ? '<span class="new">New</span> · ' : ''}<span class="impact impact-${escapeHtml(finding.impact ?? 'none')}">${escapeHtml(impact)}</span> · <span class="rule">${escapeHtml(finding.id)}</span>: ${escapeHtml(finding.help)}`);
150
+ if (via.length)
151
+ out.push(` <span class="via">(via ${escapeHtml(via.join(', '))})</span>`);
152
+ out.push(`<p class="detail"><code>${escapeHtml(finding.target)}</code>`);
153
+ if (href) {
154
+ out.push(` · <a href="${href}">Rule reference<span class="visually-hidden"> for ${escapeHtml(finding.id)}</span></a>`);
155
+ }
156
+ out.push('</p>');
157
+ out.push('</li>');
158
+ }
159
+ out.push('</ul>');
160
+ out.push('</div>');
161
+ }
162
+ out.push('</section>');
163
+ });
164
+ out.push('</main>');
165
+ out.push('</body>');
166
+ out.push('</html>');
167
+ return out.join('\n');
168
+ }
@@ -1,2 +1,4 @@
1
- export { scanPages, type ScanPagesOptions } from './headless.js';
2
- export { groupByComponent, distinctRuleCount, toJson, toMarkdown, type PageReport, type ScanReport, } from './format.js';
1
+ export { scanPages, type ColorScheme, type ScanPagesOptions, type ThemeContext, } from './headless.js';
2
+ export { groupByComponent, distinctRuleCount, toJson, toMarkdown, DARK_ONLY_NOTE, type PageReport, type ScanReport, } from './format.js';
3
+ export { toHtml } from './html.js';
4
+ export { diffAgainstBaseline, findingKey, findingsNotIn, parseBaseline, type BaselineDiff, type BaselineReport, type NewFinding, } from './baseline.js';
@@ -1,2 +1,4 @@
1
- export { scanPages } from './headless.js';
2
- export { groupByComponent, distinctRuleCount, toJson, toMarkdown, } from './format.js';
1
+ export { scanPages, } from './headless.js';
2
+ export { groupByComponent, distinctRuleCount, toJson, toMarkdown, DARK_ONLY_NOTE, } from './format.js';
3
+ export { toHtml } from './html.js';
4
+ export { diffAgainstBaseline, findingKey, findingsNotIn, parseBaseline, } from './baseline.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngbracket/a11y-devtools",
3
- "version": "0.8.0",
3
+ "version": "0.10.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",