@ngbracket/a11y-devtools 0.9.0 → 0.10.1

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.
@@ -34239,6 +34239,9 @@
34239
34239
  "[contenteditable]",
34240
34240
  "[tabindex]"
34241
34241
  ].join(",");
34242
+ function hasFocusableDescendant(element) {
34243
+ return element.querySelector(FOCUSABLE_SELECTOR) !== null;
34244
+ }
34242
34245
  function nativeTabIndex(element) {
34243
34246
  return isNativelyFocusable(element) ? 0 : -1;
34244
34247
  }
@@ -34335,14 +34338,26 @@
34335
34338
  };
34336
34339
  });
34337
34340
  }
34338
- function visualOrderJumps(stops, getRect = (el) => el.getBoundingClientRect(), rowThreshold = 8) {
34341
+ function stopRect(el) {
34342
+ const box = el.getBoundingClientRect();
34343
+ const lines = el.getClientRects();
34344
+ if (lines.length === 0)
34345
+ return { top: box.top, left: box.left, right: box.right };
34346
+ const first = lines[0];
34347
+ const last = lines[lines.length - 1];
34348
+ return { top: first.top, left: first.left, right: box.right, endTop: last.top, endLeft: last.left };
34349
+ }
34350
+ function visualOrderJumps(stops, getRect = stopRect, rowThreshold = 8) {
34339
34351
  const jumps = [];
34340
34352
  for (let i = 1; i < stops.length; i++) {
34341
34353
  const prev = getRect(stops[i - 1].element);
34342
34354
  const curr = getRect(stops[i].element);
34343
- const movedUp = curr.top < prev.top - rowThreshold;
34344
- const sameRowMovedLeft = Math.abs(curr.top - prev.top) <= rowThreshold && curr.left < prev.left - rowThreshold;
34345
- if (movedUp || sameRowMovedLeft)
34355
+ const prevTop = prev.endTop ?? prev.top;
34356
+ const prevLeft = prev.endLeft ?? prev.left;
34357
+ const movedUp = curr.top < prevTop - rowThreshold;
34358
+ const nextColumn = curr.left >= (prev.right ?? prev.left + rowThreshold);
34359
+ const sameRowMovedLeft = Math.abs(curr.top - prevTop) <= rowThreshold && curr.left < prevLeft - rowThreshold;
34360
+ if (movedUp && !nextColumn || sameRowMovedLeft)
34346
34361
  jumps.push(i);
34347
34362
  }
34348
34363
  return jumps;
@@ -34431,6 +34446,8 @@
34431
34446
  const interactiveByRole = INTERACTIVE_ROLES.has(role);
34432
34447
  if (!hasClick && !interactiveByRole)
34433
34448
  continue;
34449
+ if (!interactiveByRole && hasFocusableDescendant(element))
34450
+ continue;
34434
34451
  const focusable = isTabbable(element, isVisible);
34435
34452
  if (!focusable) {
34436
34453
  const reason = interactiveByRole ? `has role="${role}"` : "has a click handler";
@@ -12,7 +12,7 @@
12
12
  * confirmed failures.
13
13
  */
14
14
  import { appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, resolveComponentPath, resolveDirectiveNames, resolveListenerEvents, } from '../attribution.js';
15
- import { isNativelyFocusable, isTabbable, tabSequence, visualOrderJumps, } from './tab-sequence.js';
15
+ import { hasFocusableDescendant, isNativelyFocusable, isTabbable, tabSequence, visualOrderJumps, } from './tab-sequence.js';
16
16
  import { findUncontainedModals } from './focus-trap.js';
17
17
  /** WAI-ARIA roles that make a non-native element behave as an interactive control. */
18
18
  const INTERACTIVE_ROLES = new Set([
@@ -90,6 +90,11 @@ export function scanKeyboard(root = document, options = {}) {
90
90
  const interactiveByRole = INTERACTIVE_ROLES.has(role);
91
91
  if (!hasClick && !interactiveByRole)
92
92
  continue; // nothing marks this as interactive
93
+ // A click listener on a container of links/controls (no interactive role of
94
+ // its own) is event delegation, not a control — the controls inside are what
95
+ // the keyboard reaches.
96
+ if (!interactiveByRole && hasFocusableDescendant(element))
97
+ continue;
93
98
  const focusable = isTabbable(element, isVisible);
94
99
  if (!focusable) {
95
100
  const reason = interactiveByRole ? `has role="${role}"` : 'has a click handler';
@@ -21,6 +21,12 @@ export interface TabSequenceOptions {
21
21
  */
22
22
  isVisible?: (element: Element) => boolean;
23
23
  }
24
+ /**
25
+ * True when `element` contains something focusable (a link, control, or
26
+ * `tabindex` element). A click listener on such a container is almost always
27
+ * event delegation — handling clicks on the controls inside — not a fake button.
28
+ */
29
+ export declare function hasFocusableDescendant(element: Element): boolean;
24
30
  /**
25
31
  * True when the element takes focus without an explicit `tabindex` — a link with
26
32
  * an href, a form control, a `<summary>`, an editing host, and the embedded
@@ -45,14 +51,27 @@ export declare function isTabbable(element: Element, isVisible?: (el: Element) =
45
51
  * browser actually moves focus. Each stop carries its owning component.
46
52
  */
47
53
  export declare function tabSequence(root?: ParentNode, options?: TabSequenceOptions): TabStop[];
54
+ /** Where a stop starts and ends on screen, for {@link visualOrderJumps}. */
55
+ export interface StopRect {
56
+ /** Top-left of where the element starts (its first line box, for wrapped inline text). */
57
+ top: number;
58
+ left: number;
59
+ /** Right edge of the whole element. */
60
+ right?: number;
61
+ /** Top-left of where it ends (its last line box); defaults to `top`/`left`. */
62
+ endTop?: number;
63
+ endLeft?: number;
64
+ }
48
65
  /**
49
66
  * 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.
67
+ * reading order* — a stop that sits clearly above the stop before it (without
68
+ * moving right), or well to the left on the same row. A heuristic signal that
69
+ * DOM/tabindex order has drifted from the visual order a sighted keyboard user
70
+ * expects; always "verify manually". `getRect` is injectable for tests.
71
+ *
72
+ * Moving up into the *next column* — starting right of where the previous stop
73
+ * ends, like a sidebar then the main content, or across a multi-column footer —
74
+ * is normal reading order, so it isn't a jump. (A stop that moves up but still
75
+ * overlaps the previous one horizontally is.)
54
76
  */
55
- export declare function visualOrderJumps(stops: readonly TabStop[], getRect?: (el: Element) => {
56
- top: number;
57
- left: number;
58
- }, rowThreshold?: number): number[];
77
+ export declare function visualOrderJumps(stops: readonly TabStop[], getRect?: (el: Element) => StopRect, rowThreshold?: number): number[];
@@ -28,6 +28,14 @@ const FOCUSABLE_SELECTOR = [
28
28
  '[contenteditable]',
29
29
  '[tabindex]',
30
30
  ].join(',');
31
+ /**
32
+ * True when `element` contains something focusable (a link, control, or
33
+ * `tabindex` element). A click listener on such a container is almost always
34
+ * event delegation — handling clicks on the controls inside — not a fake button.
35
+ */
36
+ export function hasFocusableDescendant(element) {
37
+ return element.querySelector(FOCUSABLE_SELECTOR) !== null;
38
+ }
31
39
  /** A native default of 0 (focusable without a tabindex attribute), else -1. */
32
40
  function nativeTabIndex(element) {
33
41
  return isNativelyFocusable(element) ? 0 : -1;
@@ -157,21 +165,44 @@ export function tabSequence(root = document, options = {}) {
157
165
  };
158
166
  });
159
167
  }
168
+ /**
169
+ * The default {@link StopRect}: an inline link that wraps across lines starts on
170
+ * one line and ends on the next, and its bounding box starts at the left edge —
171
+ * so compare line boxes, not the bounding box.
172
+ */
173
+ function stopRect(el) {
174
+ const box = el.getBoundingClientRect();
175
+ const lines = el.getClientRects();
176
+ if (lines.length === 0)
177
+ return { top: box.top, left: box.left, right: box.right };
178
+ const first = lines[0];
179
+ const last = lines[lines.length - 1];
180
+ return { top: first.top, left: first.left, right: box.right, endTop: last.top, endLeft: last.left };
181
+ }
160
182
  /**
161
183
  * Indices (0-based, into the sequence) where the tab path jumps *backward against
162
- * reading order* — a stop that sits clearly above, or well to the left on the
163
- * same row, of the stop before it. A heuristic signal that DOM/tabindex order
164
- * has drifted from the visual order a sighted keyboard user expects; always
165
- * "verify manually". `getRect` is injectable for tests.
184
+ * reading order* — a stop that sits clearly above the stop before it (without
185
+ * moving right), or well to the left on the same row. A heuristic signal that
186
+ * DOM/tabindex order has drifted from the visual order a sighted keyboard user
187
+ * expects; always "verify manually". `getRect` is injectable for tests.
188
+ *
189
+ * Moving up into the *next column* — starting right of where the previous stop
190
+ * ends, like a sidebar then the main content, or across a multi-column footer —
191
+ * is normal reading order, so it isn't a jump. (A stop that moves up but still
192
+ * overlaps the previous one horizontally is.)
166
193
  */
167
- export function visualOrderJumps(stops, getRect = (el) => el.getBoundingClientRect(), rowThreshold = 8) {
194
+ export function visualOrderJumps(stops, getRect = stopRect, rowThreshold = 8) {
168
195
  const jumps = [];
169
196
  for (let i = 1; i < stops.length; i++) {
170
197
  const prev = getRect(stops[i - 1].element);
171
198
  const curr = getRect(stops[i].element);
172
- const movedUp = curr.top < prev.top - rowThreshold;
173
- const sameRowMovedLeft = Math.abs(curr.top - prev.top) <= rowThreshold && curr.left < prev.left - rowThreshold;
174
- if (movedUp || sameRowMovedLeft)
199
+ // Compare where the previous stop *ends* with where this one *starts*.
200
+ const prevTop = prev.endTop ?? prev.top;
201
+ const prevLeft = prev.endLeft ?? prev.left;
202
+ const movedUp = curr.top < prevTop - rowThreshold;
203
+ const nextColumn = curr.left >= (prev.right ?? prev.left + rowThreshold);
204
+ const sameRowMovedLeft = Math.abs(curr.top - prevTop) <= rowThreshold && curr.left < prevLeft - rowThreshold;
205
+ if ((movedUp && !nextColumn) || sameRowMovedLeft)
175
206
  jumps.push(i);
176
207
  }
177
208
  return jumps;
@@ -0,0 +1,64 @@
1
+ import type { A11yFinding } from '../scan.js';
2
+ import type { ScanReport } from './format.js';
3
+ /**
4
+ * Baseline/diff for report-mode: compare a run against a previous one so CI can
5
+ * fail only on *new* problems. An app with 40 known issues can still adopt a
6
+ * gate today — the known ones are the baseline, and the gate stops the count
7
+ * going up. Pure (no Node imports), so it's unit-testable and shares the
8
+ * browser-safe constraint of `format.ts`.
9
+ *
10
+ * The baseline is simply an earlier run's JSON report (`--out` writes it), so
11
+ * there's no separate file format to learn or migrate.
12
+ */
13
+ /** The parts of a report the diff needs — satisfied by a parsed `toJson` report. */
14
+ export interface BaselineReport {
15
+ pages: {
16
+ label: string;
17
+ findings: A11yFinding[];
18
+ error?: string;
19
+ }[];
20
+ }
21
+ /** One finding that's in the current run but not the baseline. */
22
+ export interface NewFinding {
23
+ /** Label of the page it's on. */
24
+ page: string;
25
+ finding: A11yFinding;
26
+ }
27
+ /** Result of comparing a run with its baseline. */
28
+ export interface BaselineDiff {
29
+ /** In this run, not in the baseline — the ones a CI gate should fail on. */
30
+ added: NewFinding[];
31
+ /** In the baseline, gone from this run. */
32
+ fixed: NewFinding[];
33
+ /** Present in both. */
34
+ unchanged: number;
35
+ }
36
+ /**
37
+ * A finding's identity across runs: the page, the rule, the owning component,
38
+ * and the (normalized) element selector. Impact and help text are left out on
39
+ * purpose — an axe upgrade rewording a message shouldn't make it "new".
40
+ */
41
+ export declare function findingKey(page: string, finding: A11yFinding): string;
42
+ /**
43
+ * The findings in `findings` that aren't also in `reference`, matched by
44
+ * {@link findingKey} with counts. Used for a dark-mode pass, so it reports only
45
+ * what dark mode adds rather than repeating every light-mode finding.
46
+ */
47
+ export declare function findingsNotIn(findings: A11yFinding[], reference: A11yFinding[]): A11yFinding[];
48
+ /**
49
+ * Compare `current` with `baseline`. Matching is by {@link findingKey} with
50
+ * counts, so two identical keys in the current run against one in the baseline
51
+ * leaves one new. Pages are matched by label; a route the baseline never
52
+ * scanned counts entirely as new (add it to the baseline when you add it to CI).
53
+ * Pages that failed to scan in the current run are skipped, so an outage
54
+ * doesn't report everything on that page as fixed. Pages that failed in the
55
+ * *baseline* are skipped too — there's nothing to compare against, so their
56
+ * current findings aren't counted as new (re-record the baseline to cover them).
57
+ */
58
+ export declare function diffAgainstBaseline(current: ScanReport, baseline: BaselineReport): BaselineDiff;
59
+ /**
60
+ * Read a baseline from its JSON text (a previous `toJson` report). Throws a
61
+ * readable error for anything that isn't one, rather than silently diffing
62
+ * against nothing and failing every finding as new.
63
+ */
64
+ export declare function parseBaseline(json: string): BaselineReport;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Angular stamps component-style scoping attributes (`_ngcontent-ng-c123…`,
3
+ * `_nghost-…`) whose hash changes between builds. They can appear in an axe
4
+ * selector, so strip them to keep a finding's identity stable across builds.
5
+ */
6
+ function normalizeTarget(target) {
7
+ return target.replace(/\[_ng(?:content|host)-[^\]]*\]/g, '').trim();
8
+ }
9
+ /**
10
+ * A finding's identity across runs: the page, the rule, the owning component,
11
+ * and the (normalized) element selector. Impact and help text are left out on
12
+ * purpose — an axe upgrade rewording a message shouldn't make it "new".
13
+ */
14
+ export function findingKey(page, finding) {
15
+ return [page, finding.id, finding.component ?? '', normalizeTarget(finding.target)].join('\u0000');
16
+ }
17
+ /**
18
+ * The findings in `findings` that aren't also in `reference`, matched by
19
+ * {@link findingKey} with counts. Used for a dark-mode pass, so it reports only
20
+ * what dark mode adds rather than repeating every light-mode finding.
21
+ */
22
+ export function findingsNotIn(findings, reference) {
23
+ const counts = new Map();
24
+ for (const finding of reference) {
25
+ const key = findingKey('', finding);
26
+ counts.set(key, (counts.get(key) ?? 0) + 1);
27
+ }
28
+ return findings.filter((finding) => {
29
+ const key = findingKey('', finding);
30
+ const left = counts.get(key) ?? 0;
31
+ if (left === 0)
32
+ return true;
33
+ counts.set(key, left - 1);
34
+ return false;
35
+ });
36
+ }
37
+ /**
38
+ * Compare `current` with `baseline`. Matching is by {@link findingKey} with
39
+ * counts, so two identical keys in the current run against one in the baseline
40
+ * leaves one new. Pages are matched by label; a route the baseline never
41
+ * scanned counts entirely as new (add it to the baseline when you add it to CI).
42
+ * Pages that failed to scan in the current run are skipped, so an outage
43
+ * doesn't report everything on that page as fixed. Pages that failed in the
44
+ * *baseline* are skipped too — there's nothing to compare against, so their
45
+ * current findings aren't counted as new (re-record the baseline to cover them).
46
+ */
47
+ export function diffAgainstBaseline(current, baseline) {
48
+ const failed = new Set(current.pages.filter((p) => p.error).map((p) => p.label));
49
+ const baselineFailed = new Set(baseline.pages.filter((p) => p.error).map((p) => p.label));
50
+ const remaining = new Map();
51
+ for (const page of baseline.pages) {
52
+ if (failed.has(page.label))
53
+ continue;
54
+ for (const finding of page.findings) {
55
+ const key = findingKey(page.label, finding);
56
+ const bucket = remaining.get(key);
57
+ if (bucket)
58
+ bucket.push({ page: page.label, finding });
59
+ else
60
+ remaining.set(key, [{ page: page.label, finding }]);
61
+ }
62
+ }
63
+ const added = [];
64
+ let unchanged = 0;
65
+ for (const page of current.pages) {
66
+ if (baselineFailed.has(page.label))
67
+ continue;
68
+ for (const finding of page.findings) {
69
+ const bucket = remaining.get(findingKey(page.label, finding));
70
+ if (bucket && bucket.length > 0) {
71
+ bucket.pop();
72
+ unchanged++;
73
+ }
74
+ else {
75
+ added.push({ page: page.label, finding });
76
+ }
77
+ }
78
+ }
79
+ const fixed = [...remaining.values()].flat();
80
+ return { added, fixed, unchanged };
81
+ }
82
+ /**
83
+ * Read a baseline from its JSON text (a previous `toJson` report). Throws a
84
+ * readable error for anything that isn't one, rather than silently diffing
85
+ * against nothing and failing every finding as new.
86
+ */
87
+ export function parseBaseline(json) {
88
+ let data;
89
+ try {
90
+ data = JSON.parse(json);
91
+ }
92
+ catch {
93
+ throw new Error('baseline is not valid JSON — pass a report written by `--out` (the .json file).');
94
+ }
95
+ const pages = data.pages;
96
+ if (!Array.isArray(pages) ||
97
+ !pages.every((p) => typeof p?.label === 'string' && Array.isArray(p.findings))) {
98
+ throw new Error('baseline has no `pages[].findings` — pass a report written by `--out` (the .json file).');
99
+ }
100
+ return { pages: pages };
101
+ }
@@ -1,4 +1,5 @@
1
1
  import type { A11yFinding } from '../scan.js';
2
+ import type { BaselineDiff } from './baseline.js';
2
3
  /**
3
4
  * Pure formatting for report-mode: grouping + Markdown/JSON serialization. Kept
4
5
  * free of any Node or Playwright imports so the browser side (`report.ts`) can
@@ -13,7 +14,16 @@ export interface PageReport {
13
14
  findings: A11yFinding[];
14
15
  /** Set when this route failed to scan; findings will be empty. */
15
16
  error?: string;
17
+ /** Colour scheme the page was scanned in; absent means the browser default (light). */
18
+ colorScheme?: 'light' | 'dark';
19
+ /**
20
+ * True on the dark pass of a `colorScheme: 'both'` run: findings are only the
21
+ * ones that don't also appear in the light pass of the same route.
22
+ */
23
+ darkOnly?: boolean;
16
24
  }
25
+ /** One-line explanation for a dark-only page, shared by the Markdown and HTML reports. */
26
+ export declare const DARK_ONLY_NOTE = "Dark mode: lists only issues that don\u2019t also appear in light mode on this route.";
17
27
  /** A whole report-mode run across one or more pages. */
18
28
  export interface ScanReport {
19
29
  /** ISO timestamp of the run. */
@@ -32,7 +42,20 @@ export declare function groupByComponent(findings: A11yFinding[]): Map<string, A
32
42
  * actually describes an app. Reports surface both so neither can mislead.
33
43
  */
34
44
  export declare function distinctRuleCount(findings: A11yFinding[]): number;
35
- /** Serialize a report to JSON, with per-page and overall summary counts. */
36
- export declare function toJson(report: ScanReport): string;
37
- /** Render a human-readable Markdown report grouped by owning component. */
38
- export declare function toMarkdown(report: ScanReport): string;
45
+ /**
46
+ * Serialize a report to JSON, with per-page and overall summary counts. With a
47
+ * baseline `diff`, adds a `baseline` block (counts + the new findings). The
48
+ * output stays a valid baseline for the next run.
49
+ */
50
+ export declare function toJson(report: ScanReport, diff?: BaselineDiff): string;
51
+ /** UI primitives and directives a finding came through, for a "via …" note. */
52
+ export declare function viaNames(finding: A11yFinding): string[];
53
+ /** Findings sorted most severe first (stable within an impact level). */
54
+ export declare function bySeverity(findings: A11yFinding[]): A11yFinding[];
55
+ /** A baseline diff's new findings, most severe first — what to look at first. */
56
+ export declare function addedBySeverity(diff: BaselineDiff): BaselineDiff['added'];
57
+ /**
58
+ * Render a human-readable Markdown report grouped by owning component. With a
59
+ * baseline `diff`, adds a comparison section and marks new findings.
60
+ */
61
+ export declare function toMarkdown(report: ScanReport, diff?: BaselineDiff): string;
@@ -1,3 +1,5 @@
1
+ /** One-line explanation for a dark-only page, shared by the Markdown and HTML reports. */
2
+ export const DARK_ONLY_NOTE = 'Dark mode: lists only issues that don’t also appear in light mode on this route.';
1
3
  /**
2
4
  * Group findings by the component that rendered them — the readable form the
3
5
  * attribution makes possible ("♿ HeaderComponent — 2 issues" beats a list of
@@ -32,8 +34,12 @@ const IMPACT_RANK = {
32
34
  function impactRank(impact) {
33
35
  return impact ? (IMPACT_RANK[impact] ?? 4) : 4;
34
36
  }
35
- /** Serialize a report to JSON, with per-page and overall summary counts. */
36
- export function toJson(report) {
37
+ /**
38
+ * Serialize a report to JSON, with per-page and overall summary counts. With a
39
+ * baseline `diff`, adds a `baseline` block (counts + the new findings). The
40
+ * output stays a valid baseline for the next run.
41
+ */
42
+ export function toJson(report, diff) {
37
43
  const all = report.pages.flatMap((p) => p.findings);
38
44
  return JSON.stringify({
39
45
  generatedAt: report.generatedAt,
@@ -42,17 +48,47 @@ export function toJson(report) {
42
48
  distinctRules: distinctRuleCount(all),
43
49
  nodeInstances: all.length,
44
50
  },
51
+ ...(diff && {
52
+ baseline: {
53
+ new: diff.added.length,
54
+ fixed: diff.fixed.length,
55
+ unchanged: diff.unchanged,
56
+ newFindings: diff.added.map(({ page, finding }) => ({ page, ...finding })),
57
+ },
58
+ }),
45
59
  pages: report.pages.map((p) => ({
46
60
  label: p.label,
47
61
  url: p.url,
62
+ // A failed route must not read as a clean one: keep its error.
63
+ ...(p.error !== undefined && { error: p.error }),
64
+ ...(p.colorScheme && { colorScheme: p.colorScheme }),
65
+ ...(p.darkOnly && { darkOnly: true }),
48
66
  distinctRules: distinctRuleCount(p.findings),
49
67
  nodeInstances: p.findings.length,
50
68
  findings: p.findings,
51
69
  })),
52
70
  }, null, 2);
53
71
  }
54
- /** Render a human-readable Markdown report grouped by owning component. */
55
- export function toMarkdown(report) {
72
+ /** UI primitives and directives a finding came through, for a "via …" note. */
73
+ export function viaNames(finding) {
74
+ // e.g. an `<button nbButton>` shows as "via NbButtonComponent" under its app owner.
75
+ const ownerIndex = finding.component ? finding.componentPath.indexOf(finding.component) : -1;
76
+ const wrappers = ownerIndex > 0 ? finding.componentPath.slice(0, ownerIndex) : [];
77
+ return [...wrappers, ...finding.directives];
78
+ }
79
+ /** Findings sorted most severe first (stable within an impact level). */
80
+ export function bySeverity(findings) {
81
+ return [...findings].sort((a, b) => impactRank(a.impact) - impactRank(b.impact));
82
+ }
83
+ /** A baseline diff's new findings, most severe first — what to look at first. */
84
+ export function addedBySeverity(diff) {
85
+ return [...diff.added].sort((a, b) => impactRank(a.finding.impact) - impactRank(b.finding.impact));
86
+ }
87
+ /**
88
+ * Render a human-readable Markdown report grouped by owning component. With a
89
+ * baseline `diff`, adds a comparison section and marks new findings.
90
+ */
91
+ export function toMarkdown(report, diff) {
56
92
  const all = report.pages.flatMap((p) => p.findings);
57
93
  const lines = [];
58
94
  lines.push('# Accessibility report');
@@ -70,9 +106,25 @@ export function toMarkdown(report) {
70
106
  }
71
107
  lines.push(`| **Total** | **${distinctRuleCount(all)}** | **${all.length}** | **${groupByComponent(all).size}** |`);
72
108
  lines.push('');
109
+ const added = new Set(diff?.added.map((a) => a.finding));
110
+ if (diff) {
111
+ lines.push('## Compared with baseline');
112
+ lines.push('');
113
+ lines.push(`**${diff.added.length} new** · ${diff.fixed.length} fixed · ${diff.unchanged} unchanged`);
114
+ lines.push('');
115
+ for (const { page, finding } of addedBySeverity(diff)) {
116
+ lines.push(`- 🆕 **${finding.impact ?? 'n/a'} · ${finding.id}** on ${page}, in ${finding.component ?? '(unknown component)'}: \`${finding.target}\``);
117
+ }
118
+ if (diff.added.length)
119
+ lines.push('');
120
+ }
73
121
  for (const page of report.pages) {
74
122
  lines.push(`## ${page.label} — \`${page.url}\``);
75
123
  lines.push('');
124
+ if (page.darkOnly) {
125
+ lines.push(`_${DARK_ONLY_NOTE}_`);
126
+ lines.push('');
127
+ }
76
128
  if (page.error) {
77
129
  lines.push(`⚠️ Scan failed: ${page.error}`);
78
130
  lines.push('');
@@ -89,15 +141,11 @@ export function toMarkdown(report) {
89
141
  for (const [component, items] of byComponent) {
90
142
  lines.push(`### ♿ ${component} — ${items.length} issue(s)`);
91
143
  lines.push('');
92
- const sorted = [...items].sort((a, b) => impactRank(a.impact) - impactRank(b.impact));
93
- for (const finding of sorted) {
94
- // UI primitives the app component rendered through, e.g. an `<button
95
- // nbButton>` shows as "via NbButtonComponent" under its app owner.
96
- const ownerIndex = finding.component ? finding.componentPath.indexOf(finding.component) : -1;
97
- const wrappers = ownerIndex > 0 ? finding.componentPath.slice(0, ownerIndex) : [];
98
- const via = [...wrappers, ...finding.directives];
144
+ for (const finding of bySeverity(items)) {
145
+ const via = viaNames(finding);
99
146
  const suffix = via.length ? ` _(via ${via.join(', ')})_` : '';
100
- lines.push(`- **${finding.impact ?? 'n/a'} · ${finding.id}**: ${finding.help}${suffix}`);
147
+ const isNew = added.has(finding) ? '🆕 ' : '';
148
+ lines.push(`- ${isNew}**${finding.impact ?? 'n/a'} · ${finding.id}**: ${finding.help}${suffix}`);
101
149
  lines.push(` - \`${finding.target}\``);
102
150
  lines.push(` - ${finding.helpUrl}`);
103
151
  }
@@ -1,5 +1,12 @@
1
1
  import type { Page } from 'playwright';
2
2
  import type { ScanReport } from './format.js';
3
+ /** A colour scheme a pass is scanned in. */
4
+ export type ColorScheme = 'light' | 'dark';
5
+ /** Passed to the `setup` and `beforeScan` hooks, so they can pick the matching theme. */
6
+ export interface ThemeContext {
7
+ /** The scheme this pass scans in. The browser already emulates it for `prefers-color-scheme`. */
8
+ colorScheme: ColorScheme;
9
+ }
3
10
  export interface ScanPagesOptions {
4
11
  /** Origin of the running dev server, e.g. `http://localhost:4200`. */
5
12
  baseUrl: string;
@@ -12,11 +19,43 @@ export interface ScanPagesOptions {
12
19
  /** Optional human labels keyed by route path (falls back to the route). */
13
20
  labels?: Record<string, string>;
14
21
  /**
15
- * Run once against `baseUrl` before scanning — e.g. dismiss a splash or pick a
16
- * theme (ngx-admin gates its dashboard behind a theme picker). State that
17
- * persists (localStorage/cookies) carries into the scanned routes.
22
+ * Run once per pass against `baseUrl` before scanning — e.g. log in, dismiss a
23
+ * splash, or pick a theme (ngx-admin gates its dashboard behind a theme
24
+ * picker). State that persists (localStorage/cookies) carries into the scanned
25
+ * routes. With `colorScheme: 'both'` it runs once for each pass, in a fresh
26
+ * browser context, and `colorScheme` says which theme to select.
27
+ */
28
+ setup?: (page: Page, context: ThemeContext) => Promise<void>;
29
+ /**
30
+ * Run on every route after it loads and before it's scanned — for a theme that
31
+ * doesn't persist between pages. Gets the pass's `colorScheme` and the route.
32
+ */
33
+ beforeScan?: (page: Page, context: ThemeContext & {
34
+ route: string;
35
+ }) => Promise<void>;
36
+ /**
37
+ * Which colour scheme(s) to scan in. The browser emulates the scheme, so
38
+ * `prefers-color-scheme` styles apply. `'both'` scans every route twice, and
39
+ * the dark pages list only issues that don't also appear in light (see
40
+ * `PageReport.darkOnly`). Default `'light'`, or `'both'` when `darkClass` /
41
+ * `darkAttribute` is set.
42
+ */
43
+ colorScheme?: ColorScheme | 'both';
44
+ /**
45
+ * For a class-toggled dark theme: add this class to `<html>` before each
46
+ * dark-pass scan (e.g. `'dark'` for Tailwind, `'dark-theme'` for many Material
47
+ * apps). Implies `colorScheme: 'both'` unless set.
48
+ */
49
+ darkClass?: string;
50
+ /**
51
+ * For an attribute-toggled dark theme: set this attribute on `<html>` before
52
+ * each dark-pass scan, e.g. `{ name: 'data-bs-theme', value: 'dark' }`
53
+ * (Bootstrap). Implies `colorScheme: 'both'` unless set.
18
54
  */
19
- setup?: (page: Page) => Promise<void>;
55
+ darkAttribute?: {
56
+ name: string;
57
+ value: string;
58
+ };
20
59
  /** Launch a headed browser (for debugging). Default false (headless). */
21
60
  headed?: boolean;
22
61
  /**