@ngbracket/a11y-devtools 0.10.0 → 0.11.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.
@@ -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[];
@@ -11,6 +11,7 @@
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';
14
15
  /** Elements that can hold focus and thus may appear in the tab order. */
15
16
  const FOCUSABLE_SELECTOR = [
16
17
  'a[href]',
@@ -28,6 +29,14 @@ const FOCUSABLE_SELECTOR = [
28
29
  '[contenteditable]',
29
30
  '[tabindex]',
30
31
  ].join(',');
32
+ /**
33
+ * True when `element` contains something focusable (a link, control, or
34
+ * `tabindex` element). A click listener on such a container is almost always
35
+ * event delegation — handling clicks on the controls inside — not a fake button.
36
+ */
37
+ export function hasFocusableDescendant(element) {
38
+ return element.querySelector(FOCUSABLE_SELECTOR) !== null;
39
+ }
31
40
  /** A native default of 0 (focusable without a tabindex attribute), else -1. */
32
41
  function nativeTabIndex(element) {
33
42
  return isNativelyFocusable(element) ? 0 : -1;
@@ -134,7 +143,9 @@ export function isTabbable(element, isVisible = defaultIsVisible) {
134
143
  export function tabSequence(root = document, options = {}) {
135
144
  const isVisible = options.isVisible ?? defaultIsVisible;
136
145
  const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
137
- const candidates = [...root.querySelectorAll(FOCUSABLE_SELECTOR)].filter((el) => isTabbable(el, isVisible));
146
+ // The devtools' own UI (the on/off pill) is a real tab stop, but it isn't the
147
+ // app's: leave it out of the order, the tab-order layer and the modal check.
148
+ const candidates = [...root.querySelectorAll(FOCUSABLE_SELECTOR)].filter((el) => !el.closest(OVERLAY_EXCLUDE_SELECTOR) && isTabbable(el, isVisible));
138
149
  const withMeta = candidates.map((element, domIndex) => ({
139
150
  element,
140
151
  domIndex,
@@ -157,21 +168,44 @@ export function tabSequence(root = document, options = {}) {
157
168
  };
158
169
  });
159
170
  }
171
+ /**
172
+ * The default {@link StopRect}: an inline link that wraps across lines starts on
173
+ * one line and ends on the next, and its bounding box starts at the left edge —
174
+ * so compare line boxes, not the bounding box.
175
+ */
176
+ function stopRect(el) {
177
+ const box = el.getBoundingClientRect();
178
+ const lines = el.getClientRects();
179
+ if (lines.length === 0)
180
+ return { top: box.top, left: box.left, right: box.right };
181
+ const first = lines[0];
182
+ const last = lines[lines.length - 1];
183
+ return { top: first.top, left: first.left, right: box.right, endTop: last.top, endLeft: last.left };
184
+ }
160
185
  /**
161
186
  * 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.
187
+ * reading order* — a stop that sits clearly above the stop before it (without
188
+ * moving right), or well to the left on the same row. A heuristic signal that
189
+ * DOM/tabindex order has drifted from the visual order a sighted keyboard user
190
+ * expects; always "verify manually". `getRect` is injectable for tests.
191
+ *
192
+ * Moving up into the *next column* — starting right of where the previous stop
193
+ * ends, like a sidebar then the main content, or across a multi-column footer —
194
+ * is normal reading order, so it isn't a jump. (A stop that moves up but still
195
+ * overlaps the previous one horizontally is.)
166
196
  */
167
- export function visualOrderJumps(stops, getRect = (el) => el.getBoundingClientRect(), rowThreshold = 8) {
197
+ export function visualOrderJumps(stops, getRect = stopRect, rowThreshold = 8) {
168
198
  const jumps = [];
169
199
  for (let i = 1; i < stops.length; i++) {
170
200
  const prev = getRect(stops[i - 1].element);
171
201
  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)
202
+ // Compare where the previous stop *ends* with where this one *starts*.
203
+ const prevTop = prev.endTop ?? prev.top;
204
+ const prevLeft = prev.endLeft ?? prev.left;
205
+ const movedUp = curr.top < prevTop - rowThreshold;
206
+ const nextColumn = curr.left >= (prev.right ?? prev.left + rowThreshold);
207
+ const sameRowMovedLeft = Math.abs(curr.top - prevTop) <= rowThreshold && curr.left < prevLeft - rowThreshold;
208
+ if ((movedUp && !nextColumn) || sameRowMovedLeft)
175
209
  jumps.push(i);
176
210
  }
177
211
  return jumps;
@@ -1,5 +1,6 @@
1
1
  import { type EnvironmentProviders } from '@angular/core';
2
2
  import type { Logger } from './report.js';
3
+ import { type PillPosition } from './toggle.js';
3
4
  export interface A11yDevtoolsOptions {
4
5
  /** Element/Document to scan. Defaults to `document`. */
5
6
  root?: () => Element | Document;
@@ -34,6 +35,22 @@ export interface A11yDevtoolsOptions {
34
35
  * Default false.
35
36
  */
36
37
  keyboard?: boolean;
38
+ /**
39
+ * Start switched on. Default true. Only used when the developer hasn't toggled
40
+ * it yet: once they switch it on or off (pill or shortcut), that choice is
41
+ * remembered in `localStorage` and wins over this default on reload.
42
+ */
43
+ enabled?: boolean;
44
+ /**
45
+ * Show the on/off pill. Default `'bottom-left'`; pass another corner to move
46
+ * it, or `false` to hide it (the shortcut still works).
47
+ */
48
+ pill?: PillPosition | false;
49
+ /**
50
+ * Keyboard shortcut that turns the devtools on/off. Default `'Alt+Shift+A'`.
51
+ * Modifiers: `Alt`, `Shift`, `Ctrl`, `Meta`. Pass `false` to disable it.
52
+ */
53
+ shortcut?: string | false;
37
54
  }
38
55
  /**
39
56
  * Dev-only in-app accessibility auditing. Rescans whenever the application
package/dist/provider.js CHANGED
@@ -5,6 +5,7 @@ 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';
8
9
  /**
9
10
  * Dev-only in-app accessibility auditing. Rescans whenever the application
10
11
  * settles (zoneless-aware, via `ApplicationRef.isStable`) and reports each
@@ -18,7 +19,7 @@ export function provideA11yDevtools(options = {}) {
18
19
  if (!isDevMode()) {
19
20
  return makeEnvironmentProviders([]);
20
21
  }
21
- const { root, log = true, logger, overlay = false, debounceMs = 500, tags, frameworkPrefixes, keyboard = false, } = options;
22
+ const { root, log = true, logger, overlay = false, debounceMs = 500, tags, frameworkPrefixes, keyboard = false, enabled: enabledByDefault = true, pill = 'bottom-left', shortcut: shortcutText = DEFAULT_TOGGLE_SHORTCUT, } = options;
22
23
  const axe = tags
23
24
  ? { runOnly: { type: 'tag', values: tags } }
24
25
  : undefined;
@@ -27,6 +28,39 @@ export function provideA11yDevtools(options = {}) {
27
28
  const appRef = inject(ApplicationRef);
28
29
  const destroyRef = inject(DestroyRef);
29
30
  const overlayView = overlay ? createOverlay() : undefined;
31
+ // On/off switch. Off = no scanning and nothing drawn, so it costs nothing
32
+ // while hidden. The developer's last choice is remembered per origin.
33
+ const storage = safeLocalStorage();
34
+ let enabled = readStoredEnabled(storage) ?? enabledByDefault;
35
+ const shortcut = shortcutText ? parseShortcut(shortcutText) : null;
36
+ const setEnabled = (next) => {
37
+ if (next === enabled)
38
+ return;
39
+ enabled = next;
40
+ writeStoredEnabled(storage, enabled);
41
+ pillView?.setEnabled(enabled);
42
+ if (enabled) {
43
+ scanNow(); // don't wait for the app's next stable moment
44
+ }
45
+ else {
46
+ overlayView?.clear();
47
+ overlayView?.clearTabOrder();
48
+ overlayView?.renderAxPanel(null);
49
+ }
50
+ };
51
+ const pillView = pill
52
+ ? createTogglePill({ enabled, onToggle: setEnabled, shortcut, position: pill })
53
+ : undefined;
54
+ let onKeyDown;
55
+ if (shortcut) {
56
+ onKeyDown = (event) => {
57
+ if (!matchesShortcut(event, shortcut))
58
+ return;
59
+ event.preventDefault();
60
+ setEnabled(!enabled);
61
+ };
62
+ document.addEventListener('keydown', onKeyDown, true);
63
+ }
30
64
  // Keyboard & Focus Mode, part C: a focus-follow accessibility-tree preview.
31
65
  // As the user Tabs, show the focused control's computed role/name/state —
32
66
  // the ~2/3 axe can't test — attributed to its component. Only meaningful
@@ -34,28 +68,34 @@ export function provideA11yDevtools(options = {}) {
34
68
  let onFocusIn;
35
69
  if (overlayView && keyboard) {
36
70
  onFocusIn = (event) => {
71
+ if (!enabled)
72
+ return;
37
73
  const el = event.target;
38
74
  if (!(el instanceof Element) || el.closest(`[${OVERLAY_ATTR}]`))
39
75
  return; // skip our own UI
40
76
  describeElement(el)
41
- .then((desc) => overlayView.renderAxPanel({
42
- ...desc,
43
- component: resolveOwningComponentName(el, frameworkPrefixes),
44
- tag: el.tagName.toLowerCase(),
45
- }))
77
+ .then((desc) => {
78
+ if (!enabled)
79
+ return; // switched off while describing
80
+ overlayView.renderAxPanel({
81
+ ...desc,
82
+ component: resolveOwningComponentName(el, frameworkPrefixes),
83
+ tag: el.tagName.toLowerCase(),
84
+ });
85
+ })
46
86
  .catch(() => undefined);
47
87
  };
48
88
  document.addEventListener('focusin', onFocusIn, true);
49
89
  }
50
90
  let scanning = false;
51
- const subscription = appRef.isStable
52
- .pipe(filter((stable) => stable), debounceTime(debounceMs))
53
- .subscribe(() => {
54
- if (scanning)
91
+ function scanNow() {
92
+ if (!enabled || scanning)
55
93
  return; // don't stack rescans while one is in flight
56
94
  scanning = true;
57
95
  runA11yScan(root?.(), { log, logger, axe, frameworkPrefixes, keyboard })
58
96
  .then((findings) => {
97
+ if (!enabled)
98
+ return; // switched off mid-scan: draw nothing
59
99
  overlayView?.render(findings);
60
100
  // Draw the tab-order path as its own overlay layer (independent of
61
101
  // the findings highlights) when the keyboard layer is on.
@@ -67,13 +107,28 @@ export function provideA11yDevtools(options = {}) {
67
107
  .finally(() => {
68
108
  scanning = false;
69
109
  });
70
- });
110
+ }
111
+ const subscription = appRef.isStable
112
+ .pipe(filter((stable) => stable), debounceTime(debounceMs))
113
+ .subscribe(scanNow);
71
114
  destroyRef.onDestroy(() => {
72
115
  subscription.unsubscribe();
73
116
  if (onFocusIn)
74
117
  document.removeEventListener('focusin', onFocusIn, true);
118
+ if (onKeyDown)
119
+ document.removeEventListener('keydown', onKeyDown, true);
120
+ pillView?.destroy();
75
121
  overlayView?.destroy();
76
122
  });
77
123
  }),
78
124
  ]);
79
125
  }
126
+ /** `window.localStorage`, or undefined where reading it throws (blocked storage). */
127
+ function safeLocalStorage() {
128
+ try {
129
+ return globalThis.localStorage;
130
+ }
131
+ catch {
132
+ return undefined;
133
+ }
134
+ }
@@ -15,6 +15,7 @@ export interface BaselineReport {
15
15
  pages: {
16
16
  label: string;
17
17
  findings: A11yFinding[];
18
+ error?: string;
18
19
  }[];
19
20
  }
20
21
  /** One finding that's in the current run but not the baseline. */
@@ -50,7 +51,9 @@ export declare function findingsNotIn(findings: A11yFinding[], reference: A11yFi
50
51
  * leaves one new. Pages are matched by label; a route the baseline never
51
52
  * scanned counts entirely as new (add it to the baseline when you add it to CI).
52
53
  * Pages that failed to scan in the current run are skipped, so an outage
53
- * doesn't report everything on that page as fixed.
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).
54
57
  */
55
58
  export declare function diffAgainstBaseline(current: ScanReport, baseline: BaselineReport): BaselineDiff;
56
59
  /**
@@ -40,10 +40,13 @@ export function findingsNotIn(findings, reference) {
40
40
  * leaves one new. Pages are matched by label; a route the baseline never
41
41
  * scanned counts entirely as new (add it to the baseline when you add it to CI).
42
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.
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).
44
46
  */
45
47
  export function diffAgainstBaseline(current, baseline) {
46
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));
47
50
  const remaining = new Map();
48
51
  for (const page of baseline.pages) {
49
52
  if (failed.has(page.label))
@@ -60,6 +63,8 @@ export function diffAgainstBaseline(current, baseline) {
60
63
  const added = [];
61
64
  let unchanged = 0;
62
65
  for (const page of current.pages) {
66
+ if (baselineFailed.has(page.label))
67
+ continue;
63
68
  for (const finding of page.findings) {
64
69
  const bucket = remaining.get(findingKey(page.label, finding));
65
70
  if (bucket && bucket.length > 0) {
@@ -59,6 +59,10 @@ export function toJson(report, diff) {
59
59
  pages: report.pages.map((p) => ({
60
60
  label: p.label,
61
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 }),
62
66
  distinctRules: distinctRuleCount(p.findings),
63
67
  nodeInstances: p.findings.length,
64
68
  findings: p.findings,
@@ -0,0 +1,61 @@
1
+ /** Default keyboard shortcut that turns the devtools on/off. */
2
+ export declare const DEFAULT_TOGGLE_SHORTCUT = "Alt+Shift+A";
3
+ /** `localStorage` key holding the remembered on/off choice (`'on'` | `'off'`). */
4
+ export declare const TOGGLE_STORAGE_KEY = "ngbr-a11y-devtools";
5
+ /** Where the on/off pill sits in the viewport. */
6
+ export type PillPosition = 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right';
7
+ /** A parsed shortcut such as `Alt+Shift+A`. */
8
+ export interface Shortcut {
9
+ alt: boolean;
10
+ shift: boolean;
11
+ ctrl: boolean;
12
+ meta: boolean;
13
+ /** The non-modifier key, upper-cased when it's a single character (e.g. `A`, `1`, `F2`). */
14
+ key: string;
15
+ }
16
+ /**
17
+ * Parse `Alt+Shift+A`-style text. Case-insensitive; exactly one non-modifier key.
18
+ * Returns null for anything it can't read, so a typo disables the shortcut
19
+ * rather than throwing inside the app.
20
+ */
21
+ export declare function parseShortcut(text: string): Shortcut | null;
22
+ /**
23
+ * Does a keydown match the shortcut? Letters and digits match on the physical
24
+ * key (`event.code`), because Alt/Option changes `event.key` on macOS
25
+ * (Alt+Shift+A reports `Å`) and on some keyboard layouts.
26
+ */
27
+ export declare function matchesShortcut(event: KeyboardEvent, shortcut: Shortcut): boolean;
28
+ /** The same shortcut in `aria-keyshortcuts` / display form, e.g. `Alt+Shift+A`. */
29
+ export declare function formatShortcut(shortcut: Shortcut): string;
30
+ /**
31
+ * The remembered on/off choice, or null if there isn't one (or storage is
32
+ * blocked, e.g. a private window). Never throws.
33
+ */
34
+ export declare function readStoredEnabled(storage: Storage | undefined): boolean | null;
35
+ /** Remember the on/off choice. Silently does nothing if storage is blocked. */
36
+ export declare function writeStoredEnabled(storage: Storage | undefined, enabled: boolean): void;
37
+ export interface TogglePillOptions {
38
+ /** Document to render into. Defaults to the global `document`. */
39
+ document?: Document;
40
+ /** Initial state. */
41
+ enabled: boolean;
42
+ /** Called with the new state when the user clicks the pill. */
43
+ onToggle: (enabled: boolean) => void;
44
+ /** Shortcut shown in the tooltip and exposed via `aria-keyshortcuts`. */
45
+ shortcut?: Shortcut | null;
46
+ /** Default `bottom-left` (the focus-follow panel uses bottom-right). */
47
+ position?: PillPosition;
48
+ }
49
+ export interface TogglePill {
50
+ /** Reflect a state change made elsewhere (e.g. the keyboard shortcut). */
51
+ setEnabled(enabled: boolean): void;
52
+ destroy(): void;
53
+ }
54
+ /**
55
+ * A small on/off switch for the devtools, fixed to a corner of the page. A real
56
+ * `<button role="switch">` so it works by keyboard and screen reader: the
57
+ * accessible name is "a11y devtools" (it contains the visible "a11y"), state is
58
+ * `aria-checked`, and the visible on/off text means state doesn't rely on colour.
59
+ * Marked with {@link OVERLAY_ATTR} so scans never report the tool's own UI.
60
+ */
61
+ export declare function createTogglePill(options: TogglePillOptions): TogglePill;
package/dist/toggle.js ADDED
@@ -0,0 +1,173 @@
1
+ import { OVERLAY_ATTR } from './overlay.js';
2
+ /** Default keyboard shortcut that turns the devtools on/off. */
3
+ export const DEFAULT_TOGGLE_SHORTCUT = 'Alt+Shift+A';
4
+ /** `localStorage` key holding the remembered on/off choice (`'on'` | `'off'`). */
5
+ export const TOGGLE_STORAGE_KEY = 'ngbr-a11y-devtools';
6
+ const MODIFIERS = {
7
+ alt: 'alt',
8
+ option: 'alt',
9
+ shift: 'shift',
10
+ ctrl: 'ctrl',
11
+ control: 'ctrl',
12
+ meta: 'meta',
13
+ cmd: 'meta',
14
+ command: 'meta',
15
+ };
16
+ /**
17
+ * Parse `Alt+Shift+A`-style text. Case-insensitive; exactly one non-modifier key.
18
+ * Returns null for anything it can't read, so a typo disables the shortcut
19
+ * rather than throwing inside the app.
20
+ */
21
+ export function parseShortcut(text) {
22
+ const parts = text
23
+ .split('+')
24
+ .map((p) => p.trim())
25
+ .filter(Boolean);
26
+ const shortcut = { alt: false, shift: false, ctrl: false, meta: false, key: '' };
27
+ for (const part of parts) {
28
+ const mod = MODIFIERS[part.toLowerCase()];
29
+ if (mod) {
30
+ shortcut[mod] = true;
31
+ }
32
+ else if (!shortcut.key) {
33
+ shortcut.key = part.length === 1 ? part.toUpperCase() : part;
34
+ }
35
+ else {
36
+ return null; // two non-modifier keys
37
+ }
38
+ }
39
+ return shortcut.key ? shortcut : null;
40
+ }
41
+ /**
42
+ * Does a keydown match the shortcut? Letters and digits match on the physical
43
+ * key (`event.code`), because Alt/Option changes `event.key` on macOS
44
+ * (Alt+Shift+A reports `Å`) and on some keyboard layouts.
45
+ */
46
+ export function matchesShortcut(event, shortcut) {
47
+ if (event.altKey !== shortcut.alt ||
48
+ event.shiftKey !== shortcut.shift ||
49
+ event.ctrlKey !== shortcut.ctrl ||
50
+ event.metaKey !== shortcut.meta) {
51
+ return false;
52
+ }
53
+ const { key } = shortcut;
54
+ if (/^[A-Z]$/.test(key))
55
+ return event.code === `Key${key}`;
56
+ if (/^[0-9]$/.test(key))
57
+ return event.code === `Digit${key}`;
58
+ return event.key.toLowerCase() === key.toLowerCase();
59
+ }
60
+ /** The same shortcut in `aria-keyshortcuts` / display form, e.g. `Alt+Shift+A`. */
61
+ export function formatShortcut(shortcut) {
62
+ const mods = [
63
+ shortcut.ctrl && 'Control',
64
+ shortcut.alt && 'Alt',
65
+ shortcut.shift && 'Shift',
66
+ shortcut.meta && 'Meta',
67
+ ].filter(Boolean);
68
+ return [...mods, shortcut.key].join('+');
69
+ }
70
+ /**
71
+ * The remembered on/off choice, or null if there isn't one (or storage is
72
+ * blocked, e.g. a private window). Never throws.
73
+ */
74
+ export function readStoredEnabled(storage) {
75
+ try {
76
+ const value = storage?.getItem(TOGGLE_STORAGE_KEY);
77
+ return value === 'on' ? true : value === 'off' ? false : null;
78
+ }
79
+ catch {
80
+ return null;
81
+ }
82
+ }
83
+ /** Remember the on/off choice. Silently does nothing if storage is blocked. */
84
+ export function writeStoredEnabled(storage, enabled) {
85
+ try {
86
+ storage?.setItem(TOGGLE_STORAGE_KEY, enabled ? 'on' : 'off');
87
+ }
88
+ catch {
89
+ // Storage blocked or full: the toggle still works, it just isn't remembered.
90
+ }
91
+ }
92
+ const PILL_ON = '#3ecf8e';
93
+ const PILL_OFF = '#8a8f98';
94
+ /**
95
+ * A small on/off switch for the devtools, fixed to a corner of the page. A real
96
+ * `<button role="switch">` so it works by keyboard and screen reader: the
97
+ * accessible name is "a11y devtools" (it contains the visible "a11y"), state is
98
+ * `aria-checked`, and the visible on/off text means state doesn't rely on colour.
99
+ * Marked with {@link OVERLAY_ATTR} so scans never report the tool's own UI.
100
+ */
101
+ export function createTogglePill(options) {
102
+ const doc = options.document ?? document;
103
+ const position = options.position ?? 'bottom-left';
104
+ const [vertical, horizontal] = position.split('-');
105
+ const button = doc.createElement('button');
106
+ button.type = 'button';
107
+ button.setAttribute(OVERLAY_ATTR, '');
108
+ button.setAttribute('role', 'switch');
109
+ button.setAttribute('aria-label', 'a11y devtools');
110
+ const keys = options.shortcut ? formatShortcut(options.shortcut) : null;
111
+ if (keys)
112
+ button.setAttribute('aria-keyshortcuts', keys);
113
+ Object.assign(button.style, {
114
+ position: 'fixed',
115
+ [vertical]: '12px',
116
+ [horizontal]: '12px',
117
+ zIndex: '2147483647',
118
+ display: 'inline-flex',
119
+ alignItems: 'center',
120
+ gap: '6px',
121
+ minHeight: '28px',
122
+ padding: '4px 10px',
123
+ border: '1px solid rgba(255,255,255,0.18)',
124
+ borderRadius: '999px',
125
+ background: 'rgba(20,22,28,0.94)',
126
+ color: '#f4f4f5',
127
+ font: '600 12px/1 ui-sans-serif, system-ui, sans-serif',
128
+ boxShadow: '0 2px 10px rgba(0,0,0,0.35)',
129
+ cursor: 'pointer',
130
+ pointerEvents: 'auto',
131
+ });
132
+ const dot = doc.createElement('span');
133
+ dot.setAttribute('aria-hidden', 'true');
134
+ Object.assign(dot.style, { width: '8px', height: '8px', borderRadius: '50%' });
135
+ const name = doc.createElement('span');
136
+ name.textContent = 'a11y';
137
+ // The state word is visible for sighted users; assistive tech gets it from
138
+ // aria-checked, so it's hidden to avoid "a11y on, switch, on".
139
+ const state = doc.createElement('span');
140
+ state.setAttribute('aria-hidden', 'true');
141
+ state.style.fontWeight = '400';
142
+ button.append(dot, name, state);
143
+ // Inline styles can't do :focus-visible, so draw the ring from focus events,
144
+ // only when the browser would show one.
145
+ button.addEventListener('focus', () => {
146
+ if (button.matches(':focus-visible')) {
147
+ button.style.outline = '2px solid #7ab8ff';
148
+ button.style.outlineOffset = '2px';
149
+ }
150
+ });
151
+ button.addEventListener('blur', () => {
152
+ button.style.outline = '';
153
+ });
154
+ let enabled = options.enabled;
155
+ function setEnabled(next) {
156
+ enabled = next;
157
+ button.setAttribute('aria-checked', String(enabled));
158
+ dot.style.background = enabled ? PILL_ON : PILL_OFF;
159
+ state.textContent = enabled ? 'on' : 'off';
160
+ button.style.opacity = enabled ? '1' : '0.75';
161
+ button.title = `a11y devtools ${enabled ? 'on' : 'off'}${keys ? ` (${keys})` : ''}`;
162
+ }
163
+ setEnabled(enabled);
164
+ button.addEventListener('click', () => {
165
+ setEnabled(!enabled);
166
+ options.onToggle(enabled);
167
+ });
168
+ doc.body.appendChild(button);
169
+ return {
170
+ setEnabled,
171
+ destroy: () => button.remove(),
172
+ };
173
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngbracket/a11y-devtools",
3
- "version": "0.10.0",
3
+ "version": "0.11.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",