@ngbracket/a11y-devtools 0.11.0 → 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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,48 @@
3
3
  All notable changes to `@ngbracket/a11y-devtools` are documented here.
4
4
  This project adheres to [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## 0.12.0
7
+
8
+ ### Added
9
+
10
+ - **A settings menu on the pill.** The `⋯` button next to the on/off switch opens a
11
+ panel for choosing what's drawn, so you're not looking at everything at once:
12
+ - **Highlights**, **Tab order** and **Focus preview**, each on or off.
13
+ - **Show issues**: all, moderate and above, serious and above, or critical
14
+ only. It filters what's drawn on the page; the console still logs every issue.
15
+ - How many issues the page has and how many are shown.
16
+ - **Download report**: a self-contained HTML report (the same format as report
17
+ mode) for every route you've visited since the app loaded, labelled by route.
18
+ Each developer's choices are remembered in `localStorage`; only what differs
19
+ from the app's defaults is stored. Needs `overlay: true`.
20
+ - New provider options set the defaults: `layers` (`{ highlights, tabOrder,
21
+ focusPreview }`) and `minImpact`. `highlights` defaults to `true`; `tabOrder`
22
+ and `focusPreview` follow `keyboard`, as before. Tab order and focus preview can
23
+ now also be turned on from the menu without `keyboard: true`, which still
24
+ controls the `ngbr/*` keyboard findings.
25
+
26
+ ### Fixed
27
+
28
+ - **The overlay and the on/off pill now show over modals.** Native
29
+ `<dialog>.showModal()` and popovers render in the browser's top layer, above
30
+ any z-index, and Angular CDK overlays use popovers by default from v22, so that
31
+ covers Material dialogs, menus and selects. The overlay was drawn underneath
32
+ them, and a modal `<dialog>` also made the pill unclickable. The overlay and the
33
+ pill are now top-layer popovers too: while a modal dialog is open they move
34
+ inside it, and they re-show whenever the app opens another popover so they stay
35
+ on top.
36
+ - **No false `ngbr/modal-focus-not-contained` on Angular CDK / Material
37
+ dialogs.** CDK keeps focus in with a JS focus trap (empty `aria-hidden`
38
+ sentinels either side of the dialog) rather than making the page inert. A modal
39
+ bracketed by sentinels (`aria-hidden="true"` or `data-focus-guard`, with no
40
+ content) now counts as containing focus. Checked with real Tab presses on a CDK
41
+ dialog. A modal with no trap is still flagged.
42
+ - **The tab order while a modal is open** only includes the modal's own stops,
43
+ for native modal dialogs and for trapped `aria-modal` dialogs. That removes
44
+ false `ngbr/tab-order-mismatch` findings and tab-order badges on the page behind
45
+ the modal. Focus-trap sentinels are left out of the tab order. Pass
46
+ `includeSentinels: true` to `tabSequence` to keep them.
47
+
6
48
  ## 0.11.0
7
49
 
8
50
  ### Added
package/README.md CHANGED
@@ -16,7 +16,9 @@ Part of the `@ngbracket` Angular tooling family.
16
16
  Angular's documented dev debug API (`window.ng`).
17
17
  - **In-app provider**: rescans as the app settles; grouped console output and an
18
18
  optional on-page overlay. Switch it on and off with the on-page pill or
19
- Alt+Shift+A; the choice is remembered.
19
+ Alt+Shift+A; the pill's menu picks what's drawn (highlights, tab order, focus
20
+ preview, minimum severity) and downloads an HTML report of the routes you've
21
+ visited. Choices are remembered.
20
22
  - **Report mode**: scan many routes headless from the CLI; Markdown, JSON and a
21
23
  self-contained HTML report.
22
24
  - **CI gating with a baseline**: fail only on *new* issues, so an app with known
package/dist/index.d.ts CHANGED
@@ -10,3 +10,4 @@ export { createFocusWalkProbe, detectTabTrap, type FocusObservation, type FocusW
10
10
  export { describeElement, accessibleDescription, ariaStates, type AxDescription, } from './keyboard/accname.js';
11
11
  export { createOverlay, OVERLAY_ATTR, OVERLAY_EXCLUDE_SELECTOR, type A11yOverlay, type OverlayOptions, type AxPanelData, } from './overlay.js';
12
12
  export { createTogglePill, parseShortcut, matchesShortcut, formatShortcut, readStoredEnabled, writeStoredEnabled, DEFAULT_TOGGLE_SHORTCUT, TOGGLE_STORAGE_KEY, type PillPosition, type Shortcut, type TogglePill, type TogglePillOptions, } from './toggle.js';
13
+ export type { DevtoolsSettings, MinImpact, OverlayLayers } from './settings.js';
@@ -34222,6 +34222,82 @@
34222
34222
  return names;
34223
34223
  }
34224
34224
 
34225
+ // dist/top-layer.js
34226
+ var POPOVER_LAYER_STYLE = {
34227
+ position: "fixed",
34228
+ inset: "0",
34229
+ width: "100%",
34230
+ height: "100%",
34231
+ maxWidth: "none",
34232
+ maxHeight: "none",
34233
+ margin: "0",
34234
+ padding: "0",
34235
+ border: "0",
34236
+ background: "transparent",
34237
+ color: "inherit",
34238
+ overflow: "visible"
34239
+ };
34240
+ var managed = /* @__PURE__ */ new WeakSet();
34241
+ function safeMatches(el, selector) {
34242
+ try {
34243
+ return el.matches(selector);
34244
+ } catch {
34245
+ return false;
34246
+ }
34247
+ }
34248
+ function isModalDialog(el) {
34249
+ return el.tagName === "DIALOG" && safeMatches(el, ":modal");
34250
+ }
34251
+ function blockingModalDialog(doc = document, isModal = isModalDialog) {
34252
+ const open = [...doc.querySelectorAll("dialog[open]")].filter(isModal);
34253
+ return open.at(-1) ?? null;
34254
+ }
34255
+ function keepInTopLayer(el, options = {}) {
34256
+ const doc = options.document ?? el.ownerDocument;
34257
+ const isModal = options.isModal ?? isModalDialog;
34258
+ const canPopover = typeof el.showPopover === "function";
34259
+ managed.add(el);
34260
+ if (canPopover) {
34261
+ el.setAttribute("popover", "manual");
34262
+ Object.assign(el.style, POPOVER_LAYER_STYLE);
34263
+ }
34264
+ const show = () => {
34265
+ if (!canPopover)
34266
+ return;
34267
+ try {
34268
+ if (safeMatches(el, ":popover-open"))
34269
+ el.hidePopover();
34270
+ el.showPopover();
34271
+ } catch {
34272
+ }
34273
+ };
34274
+ const place = () => {
34275
+ const parent = blockingModalDialog(doc, isModal) ?? doc.body;
34276
+ if (el.parentNode !== parent)
34277
+ parent.appendChild(el);
34278
+ show();
34279
+ };
34280
+ const observer = new MutationObserver(place);
34281
+ observer.observe(doc.documentElement, {
34282
+ subtree: true,
34283
+ attributes: true,
34284
+ attributeFilter: ["open"]
34285
+ });
34286
+ const onToggle = (event) => {
34287
+ if (event.target instanceof Element && managed.has(event.target))
34288
+ return;
34289
+ if (event.newState === "open")
34290
+ place();
34291
+ };
34292
+ doc.addEventListener("toggle", onToggle, true);
34293
+ place();
34294
+ return () => {
34295
+ observer.disconnect();
34296
+ doc.removeEventListener("toggle", onToggle, true);
34297
+ managed.delete(el);
34298
+ };
34299
+ }
34300
+
34225
34301
  // dist/overlay.js
34226
34302
  var SVG_NS = "http://www.w3.org/2000/svg";
34227
34303
  var TAB_ORDER_COLOR = "#0b8f8f";
@@ -34253,6 +34329,7 @@
34253
34329
  zIndex: "2147483646"
34254
34330
  });
34255
34331
  doc.body.appendChild(container);
34332
+ const releaseTopLayer = keepInTopLayer(container, { document: doc });
34256
34333
  const svg = doc.createElementNS(SVG_NS, "svg");
34257
34334
  svg.setAttribute(OVERLAY_ATTR, "");
34258
34335
  Object.assign(svg.style, {
@@ -34397,6 +34474,7 @@
34397
34474
  renderAxPanel(null);
34398
34475
  win?.removeEventListener("scroll", onViewportChange, { capture: true });
34399
34476
  win?.removeEventListener("resize", onViewportChange);
34477
+ releaseTopLayer();
34400
34478
  container.remove();
34401
34479
  }
34402
34480
  return { render, renderTabOrder, renderAxPanel, clear, clearTabOrder, destroy };
@@ -34535,6 +34613,26 @@
34535
34613
  }
34536
34614
 
34537
34615
  // dist/keyboard/tab-sequence.js
34616
+ function isFocusSentinel(el) {
34617
+ if (el.childElementCount > 0 || (el.textContent ?? "").trim() !== "")
34618
+ return false;
34619
+ return el.getAttribute("aria-hidden") === "true" || el.hasAttribute("data-focus-guard");
34620
+ }
34621
+ function sentinelTrappedModal(root, order) {
34622
+ const modals = [...root.querySelectorAll('[aria-modal="true"]')].reverse();
34623
+ for (const modal of modals) {
34624
+ const inside = order.map((el) => modal.contains(el));
34625
+ const first = inside.indexOf(true);
34626
+ const last = inside.lastIndexOf(true);
34627
+ if (first === -1 || inside.slice(first, last + 1).includes(false))
34628
+ continue;
34629
+ const before = order[first - 1];
34630
+ const after = order[last + 1];
34631
+ if (before && after && isFocusSentinel(before) && isFocusSentinel(after))
34632
+ return modal;
34633
+ }
34634
+ return null;
34635
+ }
34538
34636
  var FOCUSABLE_SELECTOR = [
34539
34637
  "a[href]",
34540
34638
  "area[href]",
@@ -34629,7 +34727,14 @@
34629
34727
  function tabSequence(root = document, options = {}) {
34630
34728
  const isVisible = options.isVisible ?? defaultIsVisible;
34631
34729
  const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
34632
- const candidates = [...root.querySelectorAll(FOCUSABLE_SELECTOR)].filter((el) => !el.closest(OVERLAY_EXCLUDE_SELECTOR) && isTabbable(el, isVisible));
34730
+ const doc = root instanceof Document ? root : root.ownerDocument;
34731
+ const modal = doc ? blockingModalDialog(doc, options.isModal) : null;
34732
+ let candidates = [...root.querySelectorAll(FOCUSABLE_SELECTOR)].filter((el) => !el.closest(OVERLAY_EXCLUDE_SELECTOR) && (!modal || modal.contains(el)) && isTabbable(el, isVisible));
34733
+ const trapped = modal ? null : sentinelTrappedModal(root, candidates);
34734
+ if (trapped)
34735
+ candidates = candidates.filter((el) => trapped.contains(el));
34736
+ if (!options.includeSentinels)
34737
+ candidates = candidates.filter((el) => !isFocusSentinel(el));
34633
34738
  const withMeta = candidates.map((element, domIndex) => ({
34634
34739
  element,
34635
34740
  domIndex,
@@ -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
@@ -12,6 +12,40 @@
12
12
  */
13
13
  import { appComponentFromPath, DEFAULT_FRAMEWORK_PREFIXES, resolveComponentPath, } from '../attribution.js';
14
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
+ }
15
49
  /** Elements that can hold focus and thus may appear in the tab order. */
16
50
  const FOCUSABLE_SELECTOR = [
17
51
  'a[href]',
@@ -143,9 +177,23 @@ export function isTabbable(element, isVisible = defaultIsVisible) {
143
177
  export function tabSequence(root = document, options = {}) {
144
178
  const isVisible = options.isVisible ?? defaultIsVisible;
145
179
  const prefixes = options.frameworkPrefixes ?? DEFAULT_FRAMEWORK_PREFIXES;
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;
146
184
  // The devtools' own UI (the on/off pill) is a real tab stop, but it isn't the
147
185
  // 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));
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));
149
197
  const withMeta = candidates.map((element, domIndex) => ({
150
198
  element,
151
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,6 +1,7 @@
1
1
  import { type EnvironmentProviders } from '@angular/core';
2
2
  import type { Logger } from './report.js';
3
3
  import { type PillPosition } from './toggle.js';
4
+ import { type MinImpact, type OverlayLayers } from './settings.js';
4
5
  export interface A11yDevtoolsOptions {
5
6
  /** Element/Document to scan. Defaults to `document`. */
6
7
  root?: () => Element | Document;
@@ -51,6 +52,18 @@ export interface A11yDevtoolsOptions {
51
52
  * Modifiers: `Alt`, `Shift`, `Ctrl`, `Meta`. Pass `false` to disable it.
52
53
  */
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;
54
67
  }
55
68
  /**
56
69
  * Dev-only in-app accessibility auditing. Rescans whenever the application
package/dist/provider.js CHANGED
@@ -6,6 +6,7 @@ import { tabSequence } from './keyboard/tab-sequence.js';
6
6
  import { describeElement } from './keyboard/accname.js';
7
7
  import { resolveOwningComponentName } from './attribution.js';
8
8
  import { createTogglePill, DEFAULT_TOGGLE_SHORTCUT, matchesShortcut, parseShortcut, readStoredEnabled, writeStoredEnabled, } from './toggle.js';
9
+ import { readStoredSettings, resolveSettings, visibleFindings, writeStoredSettings, } from './settings.js';
9
10
  /**
10
11
  * Dev-only in-app accessibility auditing. Rescans whenever the application
11
12
  * settles (zoneless-aware, via `ApplicationRef.isStable`) and reports each
@@ -19,7 +20,13 @@ export function provideA11yDevtools(options = {}) {
19
20
  if (!isDevMode()) {
20
21
  return makeEnvironmentProviders([]);
21
22
  }
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;
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
+ };
23
30
  const axe = tags
24
31
  ? { runOnly: { type: 'tag', values: tags } }
25
32
  : undefined;
@@ -33,23 +40,78 @@ export function provideA11yDevtools(options = {}) {
33
40
  const storage = safeLocalStorage();
34
41
  let enabled = readStoredEnabled(storage) ?? enabledByDefault;
35
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
+ }
36
74
  const setEnabled = (next) => {
37
75
  if (next === enabled)
38
76
  return;
39
77
  enabled = next;
40
78
  writeStoredEnabled(storage, enabled);
41
79
  pillView?.setEnabled(enabled);
42
- if (enabled) {
80
+ if (enabled)
43
81
  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
- }
82
+ else
83
+ draw();
50
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.
51
107
  const pillView = pill
52
- ? createTogglePill({ enabled, onToggle: setEnabled, shortcut, position: pill })
108
+ ? createTogglePill({
109
+ enabled,
110
+ onToggle: setEnabled,
111
+ shortcut,
112
+ position: pill,
113
+ menu: overlayView ? { settings, onChange: setSettings, onDownload: downloadReport } : undefined,
114
+ })
53
115
  : undefined;
54
116
  let onKeyDown;
55
117
  if (shortcut) {
@@ -63,19 +125,19 @@ export function provideA11yDevtools(options = {}) {
63
125
  }
64
126
  // Keyboard & Focus Mode, part C: a focus-follow accessibility-tree preview.
65
127
  // As the user Tabs, show the focused control's computed role/name/state —
66
- // the ~2/3 axe can't test — attributed to its component. Only meaningful
67
- // 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.
68
130
  let onFocusIn;
69
- if (overlayView && keyboard) {
131
+ if (overlayView) {
70
132
  onFocusIn = (event) => {
71
- if (!enabled)
133
+ if (!enabled || !settings.focusPreview)
72
134
  return;
73
135
  const el = event.target;
74
136
  if (!(el instanceof Element) || el.closest(`[${OVERLAY_ATTR}]`))
75
137
  return; // skip our own UI
76
138
  describeElement(el)
77
139
  .then((desc) => {
78
- if (!enabled)
140
+ if (!enabled || !settings.focusPreview)
79
141
  return; // switched off while describing
80
142
  overlayView.renderAxPanel({
81
143
  ...desc,
@@ -96,12 +158,11 @@ export function provideA11yDevtools(options = {}) {
96
158
  .then((findings) => {
97
159
  if (!enabled)
98
160
  return; // switched off mid-scan: draw nothing
99
- overlayView?.render(findings);
100
- // Draw the tab-order path as its own overlay layer (independent of
101
- // the findings highlights) when the keyboard layer is on.
102
- if (overlayView && keyboard) {
103
- overlayView.renderTabOrder(tabSequence(root?.() ?? document, { frameworkPrefixes }));
104
- }
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();
105
166
  })
106
167
  .catch(() => undefined)
107
168
  .finally(() => {
@@ -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;
@@ -0,0 +1,68 @@
1
+ /** `localStorage` key for a developer's own menu choices (only what they changed). */
2
+ export const SETTINGS_STORAGE_KEY = 'ngbr-a11y-devtools:settings';
3
+ const IMPACT_RANK = { minor: 0, moderate: 1, serious: 2, critical: 3 };
4
+ /** Severity choices, least to most severe. */
5
+ export const IMPACTS = ['minor', 'moderate', 'serious', 'critical'];
6
+ /**
7
+ * Is a finding at or above `min`? A finding with no impact is kept only when
8
+ * everything is shown (`minor`).
9
+ */
10
+ export function meetsMinImpact(impact, min) {
11
+ if (!impact)
12
+ return min === 'minor';
13
+ return IMPACT_RANK[impact] >= IMPACT_RANK[min];
14
+ }
15
+ /** The findings to draw, given the severity filter. */
16
+ export function visibleFindings(findings, min) {
17
+ return min === 'minor' ? findings : findings.filter((f) => meetsMinImpact(f.impact, min));
18
+ }
19
+ /**
20
+ * The effective settings: the app's defaults with the developer's remembered
21
+ * changes on top. Unknown or malformed stored values are ignored.
22
+ */
23
+ export function resolveSettings(defaults, stored) {
24
+ const out = { ...defaults };
25
+ if (!stored)
26
+ return out;
27
+ for (const key of ['highlights', 'tabOrder', 'focusPreview']) {
28
+ if (typeof stored[key] === 'boolean')
29
+ out[key] = stored[key];
30
+ }
31
+ if (stored.minImpact && stored.minImpact in IMPACT_RANK)
32
+ out.minImpact = stored.minImpact;
33
+ return out;
34
+ }
35
+ /** The developer's remembered changes, or null. Never throws. */
36
+ export function readStoredSettings(storage) {
37
+ try {
38
+ const raw = storage?.getItem(SETTINGS_STORAGE_KEY);
39
+ if (!raw)
40
+ return null;
41
+ const parsed = JSON.parse(raw);
42
+ return parsed && typeof parsed === 'object' ? parsed : null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ /**
49
+ * Remember only the settings that differ from the app's defaults, so a later
50
+ * change to the defaults still reaches developers who never touched that
51
+ * setting. Silently does nothing if storage is blocked.
52
+ */
53
+ export function writeStoredSettings(storage, settings, defaults) {
54
+ const changed = {};
55
+ for (const key of Object.keys(settings)) {
56
+ if (settings[key] !== defaults[key])
57
+ changed[key] = settings[key];
58
+ }
59
+ try {
60
+ if (Object.keys(changed).length === 0)
61
+ storage?.removeItem(SETTINGS_STORAGE_KEY);
62
+ else
63
+ storage?.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(changed));
64
+ }
65
+ catch {
66
+ // Storage blocked or full: the change still applies, it just isn't remembered.
67
+ }
68
+ }
package/dist/toggle.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type PillMenuOptions, type PillMenuStatus } from './pill-menu.js';
1
2
  /** Default keyboard shortcut that turns the devtools on/off. */
2
3
  export declare const DEFAULT_TOGGLE_SHORTCUT = "Alt+Shift+A";
3
4
  /** `localStorage` key holding the remembered on/off choice (`'on'` | `'off'`). */
@@ -45,10 +46,14 @@ export interface TogglePillOptions {
45
46
  shortcut?: Shortcut | null;
46
47
  /** Default `bottom-left` (the focus-follow panel uses bottom-right). */
47
48
  position?: PillPosition;
49
+ /** Add the `⋯` settings menu next to the switch. */
50
+ menu?: Omit<PillMenuOptions, 'opensUp' | 'alignLeft'>;
48
51
  }
49
52
  export interface TogglePill {
50
53
  /** Reflect a state change made elsewhere (e.g. the keyboard shortcut). */
51
54
  setEnabled(enabled: boolean): void;
55
+ /** Update the menu's issue and page counts (no-op without a menu). */
56
+ setStatus(status: PillMenuStatus): void;
52
57
  destroy(): void;
53
58
  }
54
59
  /**
package/dist/toggle.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { OVERLAY_ATTR } from './overlay.js';
2
+ import { keepInTopLayer } from './top-layer.js';
3
+ import { createPillMenu } from './pill-menu.js';
2
4
  /** Default keyboard shortcut that turns the devtools on/off. */
3
5
  export const DEFAULT_TOGGLE_SHORTCUT = 'Alt+Shift+A';
4
6
  /** `localStorage` key holding the remembered on/off choice (`'on'` | `'off'`). */
@@ -111,10 +113,6 @@ export function createTogglePill(options) {
111
113
  if (keys)
112
114
  button.setAttribute('aria-keyshortcuts', keys);
113
115
  Object.assign(button.style, {
114
- position: 'fixed',
115
- [vertical]: '12px',
116
- [horizontal]: '12px',
117
- zIndex: '2147483647',
118
116
  display: 'inline-flex',
119
117
  alignItems: 'center',
120
118
  gap: '6px',
@@ -165,9 +163,42 @@ export function createTogglePill(options) {
165
163
  setEnabled(!enabled);
166
164
  options.onToggle(enabled);
167
165
  });
168
- doc.body.appendChild(button);
166
+ // A click-through full-viewport layer holds the pill, so the layer (not the
167
+ // button) becomes the top-layer popover and the button keeps its corner.
168
+ const layer = doc.createElement('div');
169
+ layer.setAttribute(OVERLAY_ATTR, '');
170
+ Object.assign(layer.style, {
171
+ position: 'fixed',
172
+ inset: '0',
173
+ pointerEvents: 'none',
174
+ zIndex: '2147483647',
175
+ });
176
+ // The switch, the optional menu button and its panel sit together in a corner.
177
+ const group = doc.createElement('div');
178
+ Object.assign(group.style, {
179
+ position: 'fixed',
180
+ [vertical]: '12px',
181
+ [horizontal]: '12px',
182
+ display: 'flex',
183
+ alignItems: 'center',
184
+ gap: '6px',
185
+ });
186
+ group.appendChild(button);
187
+ const menu = options.menu
188
+ ? createPillMenu(doc, { ...options.menu, opensUp: vertical === 'bottom', alignLeft: horizontal === 'left' })
189
+ : undefined;
190
+ if (menu)
191
+ group.append(menu.button, menu.panel);
192
+ layer.appendChild(group);
193
+ doc.body.appendChild(layer);
194
+ const releaseTopLayer = keepInTopLayer(layer, { document: doc });
169
195
  return {
170
196
  setEnabled,
171
- destroy: () => button.remove(),
197
+ setStatus: (status) => menu?.setStatus(status),
198
+ destroy: () => {
199
+ menu?.destroy();
200
+ releaseTopLayer();
201
+ layer.remove();
202
+ },
172
203
  };
173
204
  }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Keeping the devtools' own UI visible over modals.
3
+ *
4
+ * Native `<dialog>.showModal()` and popovers (which Angular CDK overlays use by
5
+ * default from v22 — Material dialogs, menus, selects) render in the browser's
6
+ * **top layer**, above every z-index. A modal dialog also makes everything
7
+ * outside it inert. So a plain fixed-position overlay ends up hidden under the
8
+ * dialog and the pill can't be clicked. Verified in Chromium: making our UI a
9
+ * popover alone isn't enough while a modal is open (it stays inert); it has to
10
+ * be inside the modal. Outside a modal, it has to be the most recently shown
11
+ * popover to sit on top.
12
+ */
13
+ /** Is this dialog open with `showModal()` (not `show()` or the `open` attribute)? */
14
+ export declare function isModalDialog(el: Element): boolean;
15
+ /**
16
+ * The open modal `<dialog>` that blocks the rest of `doc`, or null. With several
17
+ * open, takes the last in document order as the topmost (nested modals are
18
+ * normally opened later and inserted later).
19
+ */
20
+ export declare function blockingModalDialog(doc?: Document, isModal?: (el: Element) => boolean): HTMLDialogElement | null;
21
+ export interface TopLayerOptions {
22
+ /** Document to watch. Defaults to the element's own document. */
23
+ document?: Document;
24
+ /** Override modal detection (tests; jsdom has no `:modal`). */
25
+ isModal?: (el: Element) => boolean;
26
+ }
27
+ /**
28
+ * Keep `el` (one of the devtools' own layers, already in the document) on top
29
+ * of whatever the app has in the top layer:
30
+ *
31
+ * - it's shown as a manual popover, so it sits in the top layer itself;
32
+ * - while a modal dialog is open it's moved inside that dialog, so it isn't
33
+ * inert, and moved back to `<body>` when the dialog closes;
34
+ * - when the app shows another popover or dialog, it's re-shown so it stays the
35
+ * topmost.
36
+ *
37
+ * Falls back to a plain fixed element where popovers aren't supported. Returns a
38
+ * function that stops watching.
39
+ */
40
+ export declare function keepInTopLayer(el: HTMLElement, options?: TopLayerOptions): () => void;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Keeping the devtools' own UI visible over modals.
3
+ *
4
+ * Native `<dialog>.showModal()` and popovers (which Angular CDK overlays use by
5
+ * default from v22 — Material dialogs, menus, selects) render in the browser's
6
+ * **top layer**, above every z-index. A modal dialog also makes everything
7
+ * outside it inert. So a plain fixed-position overlay ends up hidden under the
8
+ * dialog and the pill can't be clicked. Verified in Chromium: making our UI a
9
+ * popover alone isn't enough while a modal is open (it stays inert); it has to
10
+ * be inside the modal. Outside a modal, it has to be the most recently shown
11
+ * popover to sit on top.
12
+ */
13
+ /** Resets the UA popover styles so a popover can act as a full-viewport layer. */
14
+ const POPOVER_LAYER_STYLE = {
15
+ position: 'fixed',
16
+ inset: '0',
17
+ width: '100%',
18
+ height: '100%',
19
+ maxWidth: 'none',
20
+ maxHeight: 'none',
21
+ margin: '0',
22
+ padding: '0',
23
+ border: '0',
24
+ background: 'transparent',
25
+ color: 'inherit',
26
+ overflow: 'visible',
27
+ };
28
+ /**
29
+ * Every layer this module manages. Their own popover toggles are ignored, or two
30
+ * layers (overlay + pill) would keep re-showing to get above each other.
31
+ */
32
+ const managed = new WeakSet();
33
+ /** True if `el` matches `selector`; false if the browser doesn't know the selector. */
34
+ function safeMatches(el, selector) {
35
+ try {
36
+ return el.matches(selector);
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ /** Is this dialog open with `showModal()` (not `show()` or the `open` attribute)? */
43
+ export function isModalDialog(el) {
44
+ return el.tagName === 'DIALOG' && safeMatches(el, ':modal');
45
+ }
46
+ /**
47
+ * The open modal `<dialog>` that blocks the rest of `doc`, or null. With several
48
+ * open, takes the last in document order as the topmost (nested modals are
49
+ * normally opened later and inserted later).
50
+ */
51
+ export function blockingModalDialog(doc = document, isModal = isModalDialog) {
52
+ const open = [...doc.querySelectorAll('dialog[open]')].filter(isModal);
53
+ return open.at(-1) ?? null;
54
+ }
55
+ /**
56
+ * Keep `el` (one of the devtools' own layers, already in the document) on top
57
+ * of whatever the app has in the top layer:
58
+ *
59
+ * - it's shown as a manual popover, so it sits in the top layer itself;
60
+ * - while a modal dialog is open it's moved inside that dialog, so it isn't
61
+ * inert, and moved back to `<body>` when the dialog closes;
62
+ * - when the app shows another popover or dialog, it's re-shown so it stays the
63
+ * topmost.
64
+ *
65
+ * Falls back to a plain fixed element where popovers aren't supported. Returns a
66
+ * function that stops watching.
67
+ */
68
+ export function keepInTopLayer(el, options = {}) {
69
+ const doc = options.document ?? el.ownerDocument;
70
+ const isModal = options.isModal ?? isModalDialog;
71
+ const canPopover = typeof el.showPopover === 'function';
72
+ managed.add(el);
73
+ if (canPopover) {
74
+ el.setAttribute('popover', 'manual');
75
+ Object.assign(el.style, POPOVER_LAYER_STYLE);
76
+ }
77
+ const show = () => {
78
+ if (!canPopover)
79
+ return;
80
+ try {
81
+ if (safeMatches(el, ':popover-open'))
82
+ el.hidePopover();
83
+ el.showPopover();
84
+ }
85
+ catch {
86
+ // Not connected, or the browser refused: stay a plain fixed layer.
87
+ }
88
+ };
89
+ const place = () => {
90
+ const parent = blockingModalDialog(doc, isModal) ?? doc.body;
91
+ // Moving a node closes it as a popover, so only move when needed.
92
+ if (el.parentNode !== parent)
93
+ parent.appendChild(el);
94
+ show();
95
+ };
96
+ // A dialog opening or closing flips its `open` attribute; popovers don't, but
97
+ // they fire `toggle` (it doesn't bubble, so listen in the capture phase).
98
+ const observer = new MutationObserver(place);
99
+ observer.observe(doc.documentElement, {
100
+ subtree: true,
101
+ attributes: true,
102
+ attributeFilter: ['open'],
103
+ });
104
+ const onToggle = (event) => {
105
+ if (event.target instanceof Element && managed.has(event.target))
106
+ return;
107
+ if (event.newState === 'open')
108
+ place();
109
+ };
110
+ doc.addEventListener('toggle', onToggle, true);
111
+ place();
112
+ return () => {
113
+ observer.disconnect();
114
+ doc.removeEventListener('toggle', onToggle, true);
115
+ managed.delete(el);
116
+ };
117
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngbracket/a11y-devtools",
3
- "version": "0.11.0",
3
+ "version": "0.12.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",