@ngbracket/a11y-devtools 0.10.1 → 0.12.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.
@@ -19,6 +19,8 @@ import { tabSequence } from './tab-sequence.js';
19
19
  * no tabbable content of its own is skipped (nothing to trap).
20
20
  */
21
21
  export function findUncontainedModals(root = document, options = {}) {
22
+ // A modal kept in by a JS focus trap (CDK/Material) comes back from
23
+ // tabSequence with only its own stops, so it has no leak and isn't flagged.
22
24
  const stops = tabSequence(root, options);
23
25
  if (stops.length === 0)
24
26
  return [];
@@ -20,7 +20,25 @@ export interface TabSequenceOptions {
20
20
  * layout. Defaults to a computed-style + `inert`/`hidden`/`<details>` check.
21
21
  */
22
22
  isVisible?: (element: Element) => boolean;
23
+ /**
24
+ * Modal-dialog check override — for tests (jsdom has no `:modal`). Defaults to
25
+ * `dialog:modal`, i.e. opened with `showModal()`.
26
+ */
27
+ isModal?: (element: Element) => boolean;
28
+ /**
29
+ * Keep focus-trap sentinels (see {@link isFocusSentinel}) in the order. Off by
30
+ * default: focus never rests on them — the trap moves it straight on — so they
31
+ * aren't stops a user sees, and badging or order-checking them is noise.
32
+ */
33
+ includeSentinels?: boolean;
23
34
  }
35
+ /**
36
+ * A focus-trap sentinel: an empty, script-driven tab stop that sends focus back
37
+ * into the modal when reached — Angular CDK / Material's `cdk-focus-trap-anchor`
38
+ * (`tabindex="0"`, `aria-hidden="true"`), or a `data-focus-guard` element (the
39
+ * focus-lock pattern). No text and no child elements, so it isn't real content.
40
+ */
41
+ export declare function isFocusSentinel(el: Element): boolean;
24
42
  /**
25
43
  * True when `element` contains something focusable (a link, control, or
26
44
  * `tabindex` element). A click listener on such a container is almost always
@@ -11,6 +11,41 @@
11
11
  * or a native default in DOM order.
12
12
  */
13
13
  import { appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, resolveComponentPath, } from '../attribution.js';
14
+ import { OVERLAY_EXCLUDE_SELECTOR } from '../overlay.js';
15
+ import { blockingModalDialog } from '../top-layer.js';
16
+ /**
17
+ * A focus-trap sentinel: an empty, script-driven tab stop that sends focus back
18
+ * into the modal when reached — Angular CDK / Material's `cdk-focus-trap-anchor`
19
+ * (`tabindex="0"`, `aria-hidden="true"`), or a `data-focus-guard` element (the
20
+ * focus-lock pattern). No text and no child elements, so it isn't real content.
21
+ */
22
+ export function isFocusSentinel(el) {
23
+ if (el.childElementCount > 0 || (el.textContent ?? '').trim() !== '')
24
+ return false;
25
+ return el.getAttribute('aria-hidden') === 'true' || el.hasAttribute('data-focus-guard');
26
+ }
27
+ /**
28
+ * The open `aria-modal` whose focus a JS trap keeps in, or null: its stops are
29
+ * one unbroken run in `order` with a sentinel directly before and after. The
30
+ * browser can reach those sentinels, but the trap sends focus from them back
31
+ * into the modal. Checked with real Tab presses on a CDK dialog: from the last
32
+ * control, Tab wraps to the first. With several, the last is the topmost.
33
+ */
34
+ function sentinelTrappedModal(root, order) {
35
+ const modals = [...root.querySelectorAll('[aria-modal="true"]')].reverse();
36
+ for (const modal of modals) {
37
+ const inside = order.map((el) => modal.contains(el));
38
+ const first = inside.indexOf(true);
39
+ const last = inside.lastIndexOf(true);
40
+ if (first === -1 || inside.slice(first, last + 1).includes(false))
41
+ continue;
42
+ const before = order[first - 1];
43
+ const after = order[last + 1];
44
+ if (before && after && isFocusSentinel(before) && isFocusSentinel(after))
45
+ return modal;
46
+ }
47
+ return null;
48
+ }
14
49
  /** Elements that can hold focus and thus may appear in the tab order. */
15
50
  const FOCUSABLE_SELECTOR = [
16
51
  'a[href]',
@@ -142,7 +177,23 @@ export function isTabbable(element, isVisible = defaultIsVisible) {
142
177
  export function tabSequence(root = document, options = {}) {
143
178
  const isVisible = options.isVisible ?? defaultIsVisible;
144
179
  const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
145
- const candidates = [...root.querySelectorAll(FOCUSABLE_SELECTOR)].filter((el) => isTabbable(el, isVisible));
180
+ // While a modal <dialog> is open the browser makes everything outside it
181
+ // inert, so only stops inside it are reachable.
182
+ const doc = root instanceof Document ? root : root.ownerDocument;
183
+ const modal = doc ? blockingModalDialog(doc, options.isModal) : null;
184
+ // The devtools' own UI (the on/off pill) is a real tab stop, but it isn't the
185
+ // app's: leave it out of the order, the tab-order layer and the modal check.
186
+ let candidates = [...root.querySelectorAll(FOCUSABLE_SELECTOR)].filter((el) => !el.closest(OVERLAY_EXCLUDE_SELECTOR) &&
187
+ (!modal || modal.contains(el)) &&
188
+ isTabbable(el, isVisible));
189
+ // A JS focus trap (Angular CDK / Material dialogs) doesn't make the page inert,
190
+ // but keeps Tab inside the modal just the same — so, like a native modal, only
191
+ // its stops are reachable.
192
+ const trapped = modal ? null : sentinelTrappedModal(root, candidates);
193
+ if (trapped)
194
+ candidates = candidates.filter((el) => trapped.contains(el));
195
+ if (!options.includeSentinels)
196
+ candidates = candidates.filter((el) => !isFocusSentinel(el));
146
197
  const withMeta = candidates.map((element, domIndex) => ({
147
198
  element,
148
199
  domIndex,
package/dist/overlay.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { keepInTopLayer } from './top-layer.js';
1
2
  const SVG_NS = 'http://www.w3.org/2000/svg';
2
3
  /** Tab-order path + badge colours: normal teal, warning orange for positive tabindex. */
3
4
  const TAB_ORDER_COLOR = '#0b8f8f';
@@ -44,6 +45,9 @@ export function createOverlay(options = {}) {
44
45
  zIndex: '2147483646',
45
46
  });
46
47
  doc.body.appendChild(container);
48
+ // Stay visible over native modal dialogs and CDK/Material popover overlays,
49
+ // which render in the browser's top layer above any z-index.
50
+ const releaseTopLayer = keepInTopLayer(container, { document: doc });
47
51
  // The tab-order connector lives on its own SVG layer under the badges, so the
48
52
  // findings highlights and the tab-order path render and clear independently.
49
53
  const svg = doc.createElementNS(SVG_NS, 'svg');
@@ -208,6 +212,7 @@ export function createOverlay(options = {}) {
208
212
  renderAxPanel(null);
209
213
  win?.removeEventListener('scroll', onViewportChange, { capture: true });
210
214
  win?.removeEventListener('resize', onViewportChange);
215
+ releaseTopLayer();
211
216
  container.remove();
212
217
  }
213
218
  return { render, renderTabOrder, renderAxPanel, clear, clearTabOrder, destroy };
@@ -0,0 +1,35 @@
1
+ import { type DevtoolsSettings } from './settings.js';
2
+ export interface PillMenuOptions {
3
+ /** Current settings; the menu reflects them and reports changes. */
4
+ settings: DevtoolsSettings;
5
+ onChange: (settings: DevtoolsSettings) => void;
6
+ /** Download the report for the pages visited so far. */
7
+ onDownload: () => void;
8
+ /** Open the panel above the button (pill at the bottom) or below it. */
9
+ opensUp: boolean;
10
+ /** Align the panel's left edge (pill on the left) or right edge. */
11
+ alignLeft: boolean;
12
+ }
13
+ export interface PillMenuStatus {
14
+ /** Findings on the current page. */
15
+ found: number;
16
+ /** How many of those are drawn, after the severity filter. */
17
+ shown: number;
18
+ /** Pages recorded for the report. */
19
+ pages: number;
20
+ }
21
+ export interface PillMenu {
22
+ /** The `⋯` button that opens the panel. */
23
+ button: HTMLButtonElement;
24
+ /** The panel itself (a sibling of the button). */
25
+ panel: HTMLElement;
26
+ setStatus(status: PillMenuStatus): void;
27
+ destroy(): void;
28
+ }
29
+ /**
30
+ * The settings menu behind the pill's `⋯` button: a disclosure (APG pattern), not
31
+ * an ARIA menu, because it holds form controls. Native checkboxes and a select,
32
+ * so keyboard and screen-reader support come from the browser. Escape or a click
33
+ * outside closes it; Escape returns focus to the button.
34
+ */
35
+ export declare function createPillMenu(doc: Document, options: PillMenuOptions): PillMenu;
@@ -0,0 +1,185 @@
1
+ import { IMPACTS } from './settings.js';
2
+ const SEVERITY_LABEL = {
3
+ minor: 'All issues',
4
+ moderate: 'Moderate and above',
5
+ serious: 'Serious and above',
6
+ critical: 'Critical only',
7
+ };
8
+ const LAYER_LABEL = {
9
+ highlights: ['Highlights', 'Boxes over each issue'],
10
+ tabOrder: ['Tab order', 'Numbered path through the page'],
11
+ focusPreview: ['Focus preview', 'Role, name and state of the focused control'],
12
+ };
13
+ let nextId = 0;
14
+ /**
15
+ * The settings menu behind the pill's `⋯` button: a disclosure (APG pattern), not
16
+ * an ARIA menu, because it holds form controls. Native checkboxes and a select,
17
+ * so keyboard and screen-reader support come from the browser. Escape or a click
18
+ * outside closes it; Escape returns focus to the button.
19
+ */
20
+ export function createPillMenu(doc, options) {
21
+ const id = `ngbr-a11y-menu-${nextId++}`;
22
+ let settings = { ...options.settings };
23
+ const button = doc.createElement('button');
24
+ button.type = 'button';
25
+ button.textContent = '⋯';
26
+ button.setAttribute('aria-label', 'a11y devtools settings');
27
+ button.setAttribute('aria-expanded', 'false');
28
+ button.setAttribute('aria-controls', id);
29
+ Object.assign(button.style, {
30
+ minWidth: '28px',
31
+ minHeight: '28px',
32
+ padding: '0 8px',
33
+ border: '1px solid rgba(255,255,255,0.18)',
34
+ borderRadius: '999px',
35
+ background: 'rgba(20,22,28,0.94)',
36
+ color: '#f4f4f5',
37
+ font: '700 14px/1 ui-sans-serif, system-ui, sans-serif',
38
+ cursor: 'pointer',
39
+ pointerEvents: 'auto',
40
+ });
41
+ const panel = doc.createElement('div');
42
+ panel.id = id;
43
+ panel.hidden = true;
44
+ Object.assign(panel.style, {
45
+ position: 'absolute',
46
+ [options.opensUp ? 'bottom' : 'top']: 'calc(100% + 8px)',
47
+ [options.alignLeft ? 'left' : 'right']: '0',
48
+ width: '260px',
49
+ padding: '10px 12px',
50
+ borderRadius: '8px',
51
+ border: '1px solid rgba(255,255,255,0.18)',
52
+ background: 'rgba(20,22,28,0.97)',
53
+ color: '#f4f4f5',
54
+ font: '13px/1.45 ui-sans-serif, system-ui, sans-serif',
55
+ boxShadow: '0 4px 18px rgba(0,0,0,0.45)',
56
+ pointerEvents: 'auto',
57
+ textAlign: 'left',
58
+ });
59
+ const muted = '#b9c0cc'; // 9.9:1 on the panel background
60
+ const status = doc.createElement('p');
61
+ Object.assign(status.style, { margin: '0 0 8px', color: muted });
62
+ const fieldset = doc.createElement('fieldset');
63
+ Object.assign(fieldset.style, { margin: '0 0 10px', padding: '0', border: '0' });
64
+ const legend = doc.createElement('legend');
65
+ legend.textContent = 'Show on the page';
66
+ Object.assign(legend.style, { padding: '0', marginBottom: '4px', fontWeight: '700' });
67
+ fieldset.append(legend);
68
+ for (const key of Object.keys(LAYER_LABEL)) {
69
+ const [text, hint] = LAYER_LABEL[key];
70
+ const label = doc.createElement('label');
71
+ Object.assign(label.style, { display: 'flex', gap: '8px', alignItems: 'flex-start', padding: '3px 0', cursor: 'pointer' });
72
+ const box = doc.createElement('input');
73
+ box.type = 'checkbox';
74
+ // Name is just the setting ("Tab order"); the hint is its description.
75
+ box.setAttribute('aria-labelledby', `${id}-${key}`);
76
+ box.setAttribute('aria-describedby', `${id}-${key}-hint`);
77
+ box.checked = settings[key];
78
+ Object.assign(box.style, { width: '16px', height: '16px', margin: '2px 0 0', accentColor: '#3ecf8e' });
79
+ box.addEventListener('change', () => update({ [key]: box.checked }));
80
+ const words = doc.createElement('span');
81
+ const name = doc.createElement('span');
82
+ name.id = `${id}-${key}`;
83
+ name.textContent = text;
84
+ const sub = doc.createElement('span');
85
+ sub.id = `${id}-${key}-hint`;
86
+ sub.textContent = hint;
87
+ Object.assign(sub.style, { display: 'block', fontSize: '12px', color: muted });
88
+ words.append(name, sub);
89
+ label.append(box, words);
90
+ fieldset.append(label);
91
+ }
92
+ const severityLabel = doc.createElement('label');
93
+ severityLabel.textContent = 'Show issues';
94
+ Object.assign(severityLabel.style, { display: 'block', fontWeight: '700', marginBottom: '4px' });
95
+ const select = doc.createElement('select');
96
+ select.id = `${id}-severity`;
97
+ severityLabel.htmlFor = select.id;
98
+ for (const impact of IMPACTS) {
99
+ const opt = doc.createElement('option');
100
+ opt.value = impact;
101
+ opt.textContent = SEVERITY_LABEL[impact];
102
+ select.append(opt);
103
+ }
104
+ select.value = settings.minImpact;
105
+ Object.assign(select.style, {
106
+ width: '100%',
107
+ minHeight: '28px',
108
+ marginBottom: '10px',
109
+ font: 'inherit',
110
+ color: '#f4f4f5',
111
+ background: '#2a2e37',
112
+ border: '1px solid rgba(255,255,255,0.3)',
113
+ borderRadius: '4px',
114
+ });
115
+ select.addEventListener('change', () => update({ minImpact: select.value }));
116
+ const download = doc.createElement('button');
117
+ download.type = 'button';
118
+ download.textContent = 'Download report';
119
+ Object.assign(download.style, {
120
+ width: '100%',
121
+ minHeight: '28px',
122
+ font: '600 13px/1 ui-sans-serif, system-ui, sans-serif',
123
+ color: '#0d1f17',
124
+ background: '#3ecf8e',
125
+ border: '0',
126
+ borderRadius: '4px',
127
+ cursor: 'pointer',
128
+ });
129
+ download.addEventListener('click', () => options.onDownload());
130
+ const pagesNote = doc.createElement('p');
131
+ Object.assign(pagesNote.style, { margin: '4px 0 0', fontSize: '12px', color: muted });
132
+ panel.append(status, fieldset, severityLabel, select, download, pagesNote);
133
+ function update(patch) {
134
+ settings = { ...settings, ...patch };
135
+ options.onChange(settings);
136
+ }
137
+ let isOpen = false;
138
+ const setOpen = (open) => {
139
+ isOpen = open;
140
+ panel.hidden = !open;
141
+ button.setAttribute('aria-expanded', String(open));
142
+ };
143
+ button.addEventListener('click', () => setOpen(!isOpen));
144
+ const onKeyDown = (event) => {
145
+ if (event.key !== 'Escape' || !isOpen)
146
+ return;
147
+ event.stopPropagation(); // don't also close an app dialog underneath
148
+ setOpen(false);
149
+ button.focus();
150
+ };
151
+ panel.addEventListener('keydown', onKeyDown);
152
+ button.addEventListener('keydown', onKeyDown);
153
+ const onPointerDown = (event) => {
154
+ const target = event.target;
155
+ if (isOpen && target && !panel.contains(target) && !button.contains(target))
156
+ setOpen(false);
157
+ };
158
+ doc.addEventListener('pointerdown', onPointerDown, true);
159
+ // Inline styles can't do :focus-visible; draw the rings from focus events.
160
+ for (const el of [button, download, select]) {
161
+ el.addEventListener('focus', () => {
162
+ if (el.matches(':focus-visible')) {
163
+ el.style.outline = '2px solid #7ab8ff';
164
+ el.style.outlineOffset = '2px';
165
+ }
166
+ });
167
+ el.addEventListener('blur', () => {
168
+ el.style.outline = '';
169
+ });
170
+ }
171
+ return {
172
+ button,
173
+ panel,
174
+ setStatus({ found, shown, pages }) {
175
+ const issues = `${found} ${found === 1 ? 'issue' : 'issues'} on this page`;
176
+ status.textContent = shown === found ? issues : `${issues}, ${shown} shown`;
177
+ pagesNote.textContent = `Covers ${pages} ${pages === 1 ? 'page' : 'pages'} visited since the app loaded.`;
178
+ download.disabled = pages === 0;
179
+ download.style.opacity = pages === 0 ? '0.6' : '1';
180
+ },
181
+ destroy() {
182
+ doc.removeEventListener('pointerdown', onPointerDown, true);
183
+ },
184
+ };
185
+ }
@@ -1,5 +1,7 @@
1
1
  import { type EnvironmentProviders } from '@angular/core';
2
2
  import type { Logger } from './report.js';
3
+ import { type PillPosition } from './toggle.js';
4
+ import { type MinImpact, type OverlayLayers } from './settings.js';
3
5
  export interface A11yDevtoolsOptions {
4
6
  /** Element/Document to scan. Defaults to `document`. */
5
7
  root?: () => Element | Document;
@@ -34,6 +36,34 @@ export interface A11yDevtoolsOptions {
34
36
  * Default false.
35
37
  */
36
38
  keyboard?: boolean;
39
+ /**
40
+ * Start switched on. Default true. Only used when the developer hasn't toggled
41
+ * it yet: once they switch it on or off (pill or shortcut), that choice is
42
+ * remembered in `localStorage` and wins over this default on reload.
43
+ */
44
+ enabled?: boolean;
45
+ /**
46
+ * Show the on/off pill. Default `'bottom-left'`; pass another corner to move
47
+ * it, or `false` to hide it (the shortcut still works).
48
+ */
49
+ pill?: PillPosition | false;
50
+ /**
51
+ * Keyboard shortcut that turns the devtools on/off. Default `'Alt+Shift+A'`.
52
+ * Modifiers: `Alt`, `Shift`, `Ctrl`, `Meta`. Pass `false` to disable it.
53
+ */
54
+ shortcut?: string | false;
55
+ /**
56
+ * What the overlay draws by default. Developers can change each from the
57
+ * pill's menu; their choice is remembered and wins over these defaults.
58
+ * Defaults: `highlights: true`; `tabOrder` and `focusPreview` follow `keyboard`.
59
+ */
60
+ layers?: Partial<OverlayLayers>;
61
+ /**
62
+ * Lowest severity drawn on the page by default: `'minor'` (everything),
63
+ * `'moderate'`, `'serious'` or `'critical'`. The console still logs every
64
+ * issue. Developers can change it from the pill's menu. Default `'minor'`.
65
+ */
66
+ minImpact?: MinImpact;
37
67
  }
38
68
  /**
39
69
  * Dev-only in-app accessibility auditing. Rescans whenever the application
package/dist/provider.js CHANGED
@@ -5,6 +5,8 @@ import { createOverlay, OVERLAY_ATTR } from './overlay.js';
5
5
  import { tabSequence } from './keyboard/tab-sequence.js';
6
6
  import { describeElement } from './keyboard/accname.js';
7
7
  import { resolveOwningComponentName } from './attribution.js';
8
+ import { createTogglePill, DEFAULT_TOGGLE_SHORTCUT, matchesShortcut, parseShortcut, readStoredEnabled, writeStoredEnabled, } from './toggle.js';
9
+ import { readStoredSettings, resolveSettings, visibleFindings, writeStoredSettings, } from './settings.js';
8
10
  /**
9
11
  * Dev-only in-app accessibility auditing. Rescans whenever the application
10
12
  * settles (zoneless-aware, via `ApplicationRef.isStable`) and reports each
@@ -18,7 +20,13 @@ export function provideA11yDevtools(options = {}) {
18
20
  if (!isDevMode()) {
19
21
  return makeEnvironmentProviders([]);
20
22
  }
21
- const { root, log = true, logger, overlay = false, debounceMs = 500, tags, frameworkPrefixes, keyboard = false, } = options;
23
+ 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;
24
+ const defaultSettings = {
25
+ highlights: layers.highlights ?? true,
26
+ tabOrder: layers.tabOrder ?? keyboard,
27
+ focusPreview: layers.focusPreview ?? keyboard,
28
+ minImpact,
29
+ };
22
30
  const axe = tags
23
31
  ? { runOnly: { type: 'tag', values: tags } }
24
32
  : undefined;
@@ -27,53 +35,161 @@ export function provideA11yDevtools(options = {}) {
27
35
  const appRef = inject(ApplicationRef);
28
36
  const destroyRef = inject(DestroyRef);
29
37
  const overlayView = overlay ? createOverlay() : undefined;
38
+ // On/off switch. Off = no scanning and nothing drawn, so it costs nothing
39
+ // while hidden. The developer's last choice is remembered per origin.
40
+ const storage = safeLocalStorage();
41
+ let enabled = readStoredEnabled(storage) ?? enabledByDefault;
42
+ const shortcut = shortcutText ? parseShortcut(shortcutText) : null;
43
+ // What's drawn: the app's defaults, overridden by the developer's menu choices.
44
+ let settings = resolveSettings(defaultSettings, readStoredSettings(storage));
45
+ // The latest findings, kept so a settings change redraws without a rescan,
46
+ // and the latest findings per route visited, for the downloadable report.
47
+ let lastFindings = [];
48
+ const visited = new Map();
49
+ /** Draw (or clear) each overlay layer from the last scan and the settings. */
50
+ function draw() {
51
+ const shown = settings.highlights ? visibleFindings(lastFindings, settings.minImpact) : [];
52
+ pillView?.setStatus({ found: lastFindings.length, shown: shown.length, pages: visited.size });
53
+ if (!overlayView)
54
+ return;
55
+ if (!enabled) {
56
+ overlayView.clear();
57
+ overlayView.clearTabOrder();
58
+ overlayView.renderAxPanel(null);
59
+ return;
60
+ }
61
+ if (settings.highlights)
62
+ overlayView.render(shown);
63
+ else
64
+ overlayView.clear();
65
+ if (settings.tabOrder) {
66
+ overlayView.renderTabOrder(tabSequence(root?.() ?? document, { frameworkPrefixes }));
67
+ }
68
+ else {
69
+ overlayView.clearTabOrder();
70
+ }
71
+ if (!settings.focusPreview)
72
+ overlayView.renderAxPanel(null);
73
+ }
74
+ const setEnabled = (next) => {
75
+ if (next === enabled)
76
+ return;
77
+ enabled = next;
78
+ writeStoredEnabled(storage, enabled);
79
+ pillView?.setEnabled(enabled);
80
+ if (enabled)
81
+ scanNow(); // don't wait for the app's next stable moment
82
+ else
83
+ draw();
84
+ };
85
+ const setSettings = (next) => {
86
+ settings = next;
87
+ writeStoredSettings(storage, settings, defaultSettings);
88
+ draw();
89
+ };
90
+ const downloadReport = () => {
91
+ import('./report/html.js')
92
+ .then(({ toHtml }) => {
93
+ const html = toHtml({ generatedAt: new Date().toISOString(), pages: [...visited.values()] });
94
+ const url = URL.createObjectURL(new Blob([html], { type: 'text/html' }));
95
+ const link = document.createElement('a');
96
+ link.href = url;
97
+ link.download = `a11y-report-${new Date().toISOString().slice(0, 10)}.html`;
98
+ link.setAttribute(OVERLAY_ATTR, '');
99
+ document.body.appendChild(link);
100
+ link.click();
101
+ link.remove();
102
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
103
+ })
104
+ .catch(() => undefined);
105
+ };
106
+ // The settings menu needs the overlay: without it there's nothing to show or hide.
107
+ const pillView = pill
108
+ ? createTogglePill({
109
+ enabled,
110
+ onToggle: setEnabled,
111
+ shortcut,
112
+ position: pill,
113
+ menu: overlayView ? { settings, onChange: setSettings, onDownload: downloadReport } : undefined,
114
+ })
115
+ : undefined;
116
+ let onKeyDown;
117
+ if (shortcut) {
118
+ onKeyDown = (event) => {
119
+ if (!matchesShortcut(event, shortcut))
120
+ return;
121
+ event.preventDefault();
122
+ setEnabled(!enabled);
123
+ };
124
+ document.addEventListener('keydown', onKeyDown, true);
125
+ }
30
126
  // Keyboard & Focus Mode, part C: a focus-follow accessibility-tree preview.
31
127
  // As the user Tabs, show the focused control's computed role/name/state —
32
- // the ~2/3 axe can't test — attributed to its component. Only meaningful
33
- // with the visual overlay on.
128
+ // the ~2/3 axe can't test — attributed to its component. Needs the visual
129
+ // overlay; shown while the Focus preview setting is on.
34
130
  let onFocusIn;
35
- if (overlayView && keyboard) {
131
+ if (overlayView) {
36
132
  onFocusIn = (event) => {
133
+ if (!enabled || !settings.focusPreview)
134
+ return;
37
135
  const el = event.target;
38
136
  if (!(el instanceof Element) || el.closest(`[${OVERLAY_ATTR}]`))
39
137
  return; // skip our own UI
40
138
  describeElement(el)
41
- .then((desc) => overlayView.renderAxPanel({
42
- ...desc,
43
- component: resolveOwningComponentName(el, frameworkPrefixes),
44
- tag: el.tagName.toLowerCase(),
45
- }))
139
+ .then((desc) => {
140
+ if (!enabled || !settings.focusPreview)
141
+ return; // switched off while describing
142
+ overlayView.renderAxPanel({
143
+ ...desc,
144
+ component: resolveOwningComponentName(el, frameworkPrefixes),
145
+ tag: el.tagName.toLowerCase(),
146
+ });
147
+ })
46
148
  .catch(() => undefined);
47
149
  };
48
150
  document.addEventListener('focusin', onFocusIn, true);
49
151
  }
50
152
  let scanning = false;
51
- const subscription = appRef.isStable
52
- .pipe(filter((stable) => stable), debounceTime(debounceMs))
53
- .subscribe(() => {
54
- if (scanning)
153
+ function scanNow() {
154
+ if (!enabled || scanning)
55
155
  return; // don't stack rescans while one is in flight
56
156
  scanning = true;
57
157
  runA11yScan(root?.(), { log, logger, axe, frameworkPrefixes, keyboard })
58
158
  .then((findings) => {
59
- overlayView?.render(findings);
60
- // Draw the tab-order path as its own overlay layer (independent of
61
- // the findings highlights) when the keyboard layer is on.
62
- if (overlayView && keyboard) {
63
- overlayView.renderTabOrder(tabSequence(root?.() ?? document, { frameworkPrefixes }));
64
- }
159
+ if (!enabled)
160
+ return; // switched off mid-scan: draw nothing
161
+ lastFindings = findings;
162
+ const route = location.pathname + location.search;
163
+ // Label by route: a single-page app usually keeps one title on every route.
164
+ visited.set(route, { label: route, url: location.href, findings });
165
+ draw();
65
166
  })
66
167
  .catch(() => undefined)
67
168
  .finally(() => {
68
169
  scanning = false;
69
170
  });
70
- });
171
+ }
172
+ const subscription = appRef.isStable
173
+ .pipe(filter((stable) => stable), debounceTime(debounceMs))
174
+ .subscribe(scanNow);
71
175
  destroyRef.onDestroy(() => {
72
176
  subscription.unsubscribe();
73
177
  if (onFocusIn)
74
178
  document.removeEventListener('focusin', onFocusIn, true);
179
+ if (onKeyDown)
180
+ document.removeEventListener('keydown', onKeyDown, true);
181
+ pillView?.destroy();
75
182
  overlayView?.destroy();
76
183
  });
77
184
  }),
78
185
  ]);
79
186
  }
187
+ /** `window.localStorage`, or undefined where reading it throws (blocked storage). */
188
+ function safeLocalStorage() {
189
+ try {
190
+ return globalThis.localStorage;
191
+ }
192
+ catch {
193
+ return undefined;
194
+ }
195
+ }
@@ -0,0 +1,39 @@
1
+ import type { A11yFinding, Impact } from './scan.js';
2
+ /** What the overlay draws. Each can be switched from the pill's menu. */
3
+ export interface OverlayLayers {
4
+ /** Boxes over flagged elements. */
5
+ highlights: boolean;
6
+ /** Numbered tab-order badges and path. */
7
+ tabOrder: boolean;
8
+ /** The accessibility-tree panel that follows focus. */
9
+ focusPreview: boolean;
10
+ }
11
+ /** Lowest severity drawn on the page. The console still logs everything. */
12
+ export type MinImpact = NonNullable<Impact>;
13
+ export interface DevtoolsSettings extends OverlayLayers {
14
+ minImpact: MinImpact;
15
+ }
16
+ /** `localStorage` key for a developer's own menu choices (only what they changed). */
17
+ export declare const SETTINGS_STORAGE_KEY = "ngbr-a11y-devtools:settings";
18
+ /** Severity choices, least to most severe. */
19
+ export declare const IMPACTS: readonly MinImpact[];
20
+ /**
21
+ * Is a finding at or above `min`? A finding with no impact is kept only when
22
+ * everything is shown (`minor`).
23
+ */
24
+ export declare function meetsMinImpact(impact: Impact, min: MinImpact): boolean;
25
+ /** The findings to draw, given the severity filter. */
26
+ export declare function visibleFindings(findings: A11yFinding[], min: MinImpact): A11yFinding[];
27
+ /**
28
+ * The effective settings: the app's defaults with the developer's remembered
29
+ * changes on top. Unknown or malformed stored values are ignored.
30
+ */
31
+ export declare function resolveSettings(defaults: DevtoolsSettings, stored: Partial<DevtoolsSettings> | null): DevtoolsSettings;
32
+ /** The developer's remembered changes, or null. Never throws. */
33
+ export declare function readStoredSettings(storage: Storage | undefined): Partial<DevtoolsSettings> | null;
34
+ /**
35
+ * Remember only the settings that differ from the app's defaults, so a later
36
+ * change to the defaults still reaches developers who never touched that
37
+ * setting. Silently does nothing if storage is blocked.
38
+ */
39
+ export declare function writeStoredSettings(storage: Storage | undefined, settings: DevtoolsSettings, defaults: DevtoolsSettings): void;