Md Tarek — Portfolio© 2026

Full-stack Developer

System Design — built to hold up.

dhaka → remote, worldwide

Loading experience

Md TarekTarek
Design

Web Accessibility WCAG 2.2 and Keyboard Navigation in Production

By: Md Tarek · 17 Oct 2026

Hero image: web accessibility WCAG 2.2 and keyboard navigation audit showing focus rings, ARIA live regions, and 24 px target size annotations
Hero image: web accessibility WCAG 2.2 and keyboard navigation audit showing focus rings, ARIA live regions, and 24 px target size annotations

# Production Web Accessibility: WCAG 2.2 and Keyboard Navigation

Every accessibility regression I have shipped to production reduced to one of four root causes: focus escaped a modal, an ARIA live region announced into the void, a hit target measured 20×20 CSS px, or nobody had ever driven the feature with a screen reader. This note is the engineering playbook I use to close all four — the WCAG 2.2 success criteria that actually changed the work, the browser primitives that made most hand-rolled code obsolete, and the CI harness that stops it from regressing.

Executive Summary & Key Takeaways

  • WCAG 2.2 adds nine success criteria, and only four change day-to-day UI work: SC 2.5.8 Target Size (Minimum) at AA requires ≥24×24 CSS px or a 24 px-diameter spacing circle that intersects no other target; SC 2.4.11/2.4.12 govern obscured focus; SC 3.3.7 Redundant Entry forbids re-asking for data already supplied in the same flow; SC 3.3.8 Accessible Authentication (Minimum) bans cognitive-function tests and blocks nothing that a password manager or paste could handle.
  • Stop hand-rolling focus traps. <dialog>.showModal() plus the inert attribute ships 0 KB of JavaScript and eliminates roughly 90% of focus-management bugs; the popular focus-trap + tabbable pair costs ~11–13 KB gzip and still cannot participate in the top layer. Baseline: Chrome 102+ / Firefox 112+ / Safari 15.5+, with a sentinel fallback behind a capability check.
  • **ARIA live regions fail on *timing*, not markup. The region must already be in the accessibility tree before the text mutation lands. Mount regions once at boot, inject after a double `requestAnimationFrame` flush, and rate-limit `assertive` to ≤1 interrupt per 2 seconds** or the screen reader speech queue falls behind by minutes.
  • Automation is a smoke test, not a proof. axe-core, Pa11y, and Lighthouse evaluate only about 30–40% of WCAG 2.2 failures by criterion (Deque claims ~57% by issue frequency). Focus containment, focus restoration, announcement quality, and virtual-cursor reading order are observable only in a manual NVDA+Firefox, JAWS+Chrome, VoiceOver+Safari, and TalkBack matrix.
  • Focus visibility and focus obscuring are two different bugs. A :focus-visible ring of ≥2 CSS px at ≥3:1 contrast against both the component and its background clears SC 2.4.7/2.4.11, and scroll-margin-top: var(--header-height) on every focusable target stops sticky headers from swallowing the focused element during keyboard traversal.

1. The Focus Contract: Containment, Initial Focus, Restoration

A modal overlay has exactly three obligations, and WCAG does not care how you meet them:

1. Containment — while open, Tab, Shift+Tab, and script-invoked focus() cannot land outside the overlay (SC 2.1.1 Keyboard, SC 2.4.3 Focus Order). 2. Initial focus — focus moves *into* the overlay on open, to a deterministic element: the dialog title for a destructive confirm, the first field for a form. Leaving focus on the trigger behind the scrim is a silent failure that NVDA reports as an empty document region. 3. Restoration — on close, focus returns to the opener, or to the nearest stable ancestor if the opener no longer exists.

SC 2.1.2 No Keyboard Trap is not in tension with this. A modal trap is conformant because Escape or an explicit close control always exits. A trap with no exit path is a failure.

 open()                                     close()
   |                                          ^
   v                                          |
+------------------------------+   +------------------------------+
| 1  capture origin            |   | 4  un-inert + restore focus  |
|    activeElement -> origin   |   |    origin.isConnected ?      |
+------------------------------+   |    origin.closest([inert]) ? |
| 2  inert everything outside  |-->|    -> rAF(origin.focus())    |
|    walk container -> body    |   +------------------------------+
+------------------------------+   | 3b focusin guard             |
| 3a keydown Tab wrap          |<--|    target outside? bounce in |
+------------------------------+   +------------------------------+

The primitive that deleted 500 lines of trap code

<dialog>.showModal() promotes the element to the top layer:

  • The rest of the document becomes inert at the user-agent level. No aria-hidden bookkeeping, no manual tabindex surgery.
  • It paints above every z-index on the page because the top layer is a separate stacking context. That kills the classic *dropdown renders behind the modal* bug permanently.
  • Escape fires a cancelable cancel event, then close. Focus containment is enforced by the engine, including for elements added to the dialog after it opened.
  • ::backdrop gives you a scrim without a portal or a stacking-context tax.

What it does not do: backdrop click-to-close (you must hit-test the click against the dialog rectangle yourself), reliable focus restoration when the opener was unmounted, and consistent scroll locking across engines. In Safari the ::backdrop element does not receive pointer events the way Chrome's does, so a naive event.target === dialog check silently fails there.

`inert` as the containment primitive for non-dialog overlays

Mobile nav drawers, combobox popovers, and slide-over panels are not <dialog> elements, so you still need containment. inert is the right tool: it removes a subtree from the tab order, from pointer hits, and from the accessibility tree — all three at once, which is precisely what a scrim implies.

Use a walk-up-the-tree strategy rather than a flat document.body.children loop: start at the container, inert every sibling at each ancestor level, and stop at document.body. This keeps nested overlays working, because an ancestor's other children get inerted while the branch containing both the outer and inner overlay stays live.

> War story — the 300 ms focus-restore race. A React settings modal restored focus in a useEffect cleanup, which ran *before* the trigger button had re-rendered after a route transition. Focus landed on <body>. NVDA users reported being dumped at the top of the document and having to re-navigate 40 controls. The fix was not setTimeout — it was checking origin.isConnected and deferring the restore with requestAnimationFrame so it ran after the origin's commit. We now assert restoration in Playwright with toBeFocused(), which caught three further instances of the same bug across the app.

Focus appearance and obscuring

SC 2.4.13 Focus Appearance (AAA) formalises what a focus indicator must be: an area at least as large as a 2 CSS px perimeter around the unfocused component, with a ≥3:1 contrast ratio between the same pixels in the focused and unfocused states. SC 2.4.11/2.4.12 (AA/AAA) require that the focused component is not *entirely* hidden by author-created content such as sticky headers, cookie banners, or chat launchers.

The cheapest mitigation is one line of CSS, applied to the focusable target rather than the container:

:where(a, button, input, select, textarea, summary, [tabindex]):focus-visible {
  outline: 2px solid var(--focus-ring, #1a73e8);
  outline-offset: 2px;
  /* Keeps the focused element clear of sticky headers (SC 2.4.11). */
  scroll-margin-top: calc(var(--header-height, 64px) + 12px);
  scroll-margin-bottom: 24px;
}

Note the :focus-visible caveat: Safari does not apply :focus-visible to every programmatically focused element, so a dialog that calls title.focus() may show no ring at all. Pair programmatic focus with an explicit data-focus-ring attribute selector, or apply :focus (not just :focus-visible) to elements that receive programmatic focus.

2. Composite Widgets: One Tab Stop, Arrow Keys Inside

The rule that trips up more teams than any other: a composite widget — toolbar, tablist, grid, tree, listbox, menubar, radio group — must be a single tab stop. Tab enters and leaves the widget; arrow keys move *within* it. Violating this inflates the tab sequence from 12 stops to 312 on a data grid, which is a de facto SC 2.1.1 failure for keyboard-only users.

Tab -> [ Save ] [ Export v ] [ Delete ]  Tab ->  next region
                   |
                   +-- ArrowDown --> menu item 1
                       ArrowDown --> menu item 2
                       Home      --> menu item 1
                       End       --> last item
                       Escape    --> close, focus back on trigger

Roving tabindex vs. `aria-activedescendant`

Roving tabindex keeps exactly one item with tabindex="0" and every sibling at -1, then calls .focus() on the target after a keydown. DOM focus is real, so :focus-visible styling, browser find-in-page, and AT virtual-cursor synchronisation all behave. Cost: one focus event per arrow press.

`aria-activedescendant` keeps DOM focus on the container and publishes the active item's id as an attribute. It scales to virtualised lists of 10,000 rows where calling .focus() per keystroke would thrash the DOM. The catch is that the container must be focusable, every option needs a stable id, and VoiceOver on macOS has historically needed a short delay between the attribute change and the item render to announce correctly.

A subtle but severe bug: never reset the active index to 0 on re-render. If a toolbar re-mounts and reruns its initialiser, a user who arrowed to item 7 and triggered an action will find focus back at item 1 — a direct SC 2.4.3 Focus Order failure. Persist the active index in a ref, not in render state, and restore it on mount if the item still exists.

> War story — the 312-tab date picker. A booking flow rendered a 42-cell calendar grid with every day focusable. Keyboard users had to press Tab up to 30 times to reach the month navigation, and voice-control users could not say *next month* because the control was 30 stops away. Converting the grid to roving tabindex with ArrowLeft/Right/Up/Down, Home/End, PageUp/PageDown for month jumps, and Escape-to-close cut the tab count for the entire booking page from 340 to 29. Task completion time for keyboard-only testers dropped by roughly half in our moderated sessions.

3. ARIA Live Regions: A Timing Problem Wearing a Markup Costume

Every asynchronous state change needs an announcement: *3 results*, *Saved*, *2 validation errors*, *Connection lost*. Browsers publish these through the accessibility tree, and AT subscribes to mutations. Live-region semantics are evaluated at the moment of the mutation, which produces a race that no amount of correct markup can fix on its own.

 producer           LiveAnnouncer                  accessibility tree        AT
 --------           -------------                  ------------------        --
 fetch ok  --> announce(polite) --> queue
                                     |
                                     | coalesce (last write wins, polite)
                                     v
                               rAF #1: region.textContent = ''
                                     v
                               rAF #2: region.textContent = msg + NBSP
                                     v
                               AX mutation -----------> speech queue

The rules that actually matter

  • Mount regions once, at application boot, and never unmount them. A region created in the same commit as its content is inserted with the text already inside; VoiceOver on iOS typically drops the announcement, NVDA sometimes catches it, and you get an environment-dependent bug that reproduces *on some Tuesdays*.
  • Never toggle `display: none` or `visibility: hidden` on a live region. Both remove the node from the accessibility tree; the subsequent text mutation emits no event. The correct visually-hidden pattern is clip-path: inset(50%) with a 1 px box, which keeps the node in the tree.
  • `role="alert"` implies `aria-live="assertive"` and `aria-atomic="true"`. Never add role="alert" to a container that mounts with its text already present, and never set both role="status" and aria-live="assertive" on the same node — the conflict is the most common cause of double-speak in NVDA.
  • `aria-busy="true"` batches mutations. Set it while a table re-sorts through six DOM updates, then flip to false for a single announcement instead of six.
  • Throttle progress. A live region wired to a 20 Hz progress stream enqueues 20 utterances per second; the AT speech queue will still be reading them a minute after the upload finished. Announce at thresholds — 0, 25, 50, 75, 100 — and use role="progressbar" with aria-valuenow for the continuous part.
  • iOS overlay quirk: while an element with aria-modal="true" is open, VoiceOver on iOS may ignore live regions that live outside the modal subtree. Either mount the announcer inside the dialog, or move the region into the top layer with the dialog.

Choosing the right role

| Intent | Markup | Politeness | Atomic | Notes | | --- | --- | --- | --- | --- | | Autosave, background status, result counts | role="status" | polite | true | The default choice. Waits for the current utterance to finish. | | Validation failure, session expiry, destructive action blocked | role="alert" | assertive | true | Interrupts speech. Cap at one per ~2 s — this is a usability budget, not a technical one. | | Append-only activity feed or chat log | role="log" | polite | false | Implicit aria-relevant="additions text"; leave atomic off so only the new row is read. | | File upload / long task progress | role="progressbar" + aria-valuenow | none | n/a | Announce thresholds via a separate role="status" region. | | SPA route change | Focus the new <h1 tabindex="-1"> | polite | true | Do not also push the page title through a live region; you will speak it twice. | | Loading spinner | role="status" + aria-busy | polite | true | One message on start, one on completion. Nothing in between. |

> War story — the toast that only spoke on Tuesdays. Our toast root rendered inside a <div hidden> until the first message arrived. On the first notification after page load, React committed the container mount and the message text in the same task, so the mutation targeted a node that had not yet been painted into the accessibility tree. NVDA announced it; VoiceOver on macOS and iOS did not; JAWS announced it about 60% of the time. Support tickets described it as *random*. Moving region creation to application boot and injecting content two frames later made announcements deterministic across all four AT combos — the only remaining flake was traced to a second aria-atomic on an ancestor, which caused NVDA to read each toast twice.

Practical Implementation

Production code below is framework-agnostic TypeScript. Wire FocusTrap.open() to your overlay mount and close() to your unmount; call LiveAnnouncer.get() once from your app entry point.

1. A zero-dependency focus trap that prefers the platform

// src/a11y/focus-trap.ts
// Prefers the native top layer + `inert`; degrades to a keydown/focusin guard
// on engines that do not support `inert` (Chrome < 102, Firefox < 112, Safari < 15.5).

const FOCUSABLE = [
  'a[href]',
  'area[href]',
  'button:not([disabled])',
  'input:not([disabled]):not([type=hidden])',
  'select:not([disabled])',
  'textarea:not([disabled])',
  'iframe',
  'audio[controls]',
  'video[controls]',
  '[contenteditable]:not([contenteditable=false])',
  '[tabindex]',
].join(',');

function isVisible(el: HTMLElement): boolean {
  // checkVisibility() reads cached style/layout and avoids the reflow storm of
  // offsetWidth probing on a 200-node dialog.
  if (typeof el.checkVisibility === 'function') {
    return el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });
  }
  return el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0;
}

function isDisabled(el: HTMLElement): boolean {
  return el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true';
}

export interface FocusTrapOptions {
  /** Element to focus on open. Defaults to the first focusable descendant. */
  initialFocus?: HTMLElement | (() => HTMLElement | null) | null;
  /** Element to restore focus to. Defaults to the active element at open(). */
  returnFocus?: HTMLElement | null;
  /** Called when Escape is pressed while the trap owns the key. */
  onEscape?: () => void;
  /** Set false for non-modal popovers that must not lock the page. */
  modal?: boolean;
}

export class FocusTrap {
  private readonly container: HTMLElement;
  private readonly opts: FocusTrapOptions;
  private abort = new AbortController();
  private origin: HTMLElement | null = null;
  private inerted: HTMLElement[] = [];
  private active = false;

  constructor(container: HTMLElement, opts: FocusTrapOptions = {}) {
    this.container = container;
    this.opts = { modal: true, ...opts };
  }

  private getFocusable(): HTMLElement[] {
    return Array.from(this.container.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
      (el) => el.tabIndex >= 0 && !isDisabled(el) && isVisible(el),
    );
  }

  /** Inerts every sibling on the path from the container up to <body>. */
  private inertOutside(): void {
    if (!('inert' in HTMLElement.prototype)) return; // fallback: focusin guard only

    let node: HTMLElement = this.container;
    while (node.parentElement && node.parentElement !== document.body) {
      for (const sibling of Array.from(node.parentElement.children)) {
        if (sibling === node || !(sibling instanceof HTMLElement)) continue;
        if (sibling.hasAttribute('inert')) continue; // never clobber someone else's inert
        sibling.setAttribute('inert', '');
        this.inerted.push(sibling);
      }
      node = node.parentElement;
    }

    for (const child of Array.from(document.body.children)) {
      if (child === node || !(child instanceof HTMLElement)) continue;
      // Live regions must stay in the accessibility tree or every announcement
      // silently disappears while a modal is open.
      if (child.dataset.a11yLive === 'true') continue;
      if (child.hasAttribute('inert')) continue;
      child.setAttribute('inert', '');
      this.inerted.push(child);
    }
  }

  private restoreOutside(): void {
    for (let i = this.inerted.length - 1; i >= 0; i -= 1) {
      const el = this.inerted[i];
      if (el.isConnected) el.removeAttribute('inert');
    }
    this.inerted = [];
  }

  private onKeyDown = (event: KeyboardEvent): void => {
    if (!this.active) return;

    if (event.key === 'Escape' && this.opts.onEscape) {
      event.preventDefault();
      event.stopPropagation();
      this.opts.onEscape();
      return;
    }
    if (event.key !== 'Tab') return;

    const focusable = this.getFocusable();
    if (focusable.length === 0) {
      event.preventDefault();
      this.container.focus({ preventScroll: true });
      return;
    }

    const first = focusable[0];
    const last = focusable[focusable.length - 1];
    const current = document.activeElement as HTMLElement | null;
    const inside = current !== null && this.container.contains(current);

    if (!event.shiftKey && (current === last || !inside)) {
      event.preventDefault();
      first.focus({ preventScroll: true });
    } else if (event.shiftKey && (current === first || !inside)) {
      event.preventDefault();
      last.focus({ preventScroll: true });
    }
  };

  /** Catches script-invoked focus() and engine gaps in `inert` support. */
  private onFocusIn = (event: FocusEvent): void => {
    if (!this.active) return;
    const target = event.target as Node | null;
    if (target && this.container.contains(target)) return;
    const fallback = this.getFocusable()[0] ?? this.container;
    if (document.activeElement === fallback) return; // no infinite bounce loop
    fallback.focus({ preventScroll: true });
  };

  open(): void {
    if (this.active) return;
    this.active = true;
    this.origin = this.opts.returnFocus ?? (document.activeElement as HTMLElement | null);

    const { signal } = this.abort;
    document.addEventListener('keydown', this.onKeyDown, { capture: true, signal });
    document.addEventListener('focusin', this.onFocusIn, { capture: true, signal });

    if (this.opts.modal !== false) this.inertOutside();

    const configured = typeof this.opts.initialFocus === 'function'
      ? this.opts.initialFocus()
      : this.opts.initialFocus;
    const target = configured ?? this.getFocusable()[0] ?? null;

    if (target) {
      target.focus({ preventScroll: true });
    } else {
      // No focusable children: make the container itself a focus target so the
      // screen reader cursor lands inside the overlay instead of on <body>.
      if (!this.container.hasAttribute('tabindex')) {
        this.container.setAttribute('tabindex', '-1');
      }
      this.container.focus({ preventScroll: true });
    }
  }

  close(): void {
    if (!this.active) return;
    this.active = false;
    this.abort.abort();
    this.abort = new AbortController();
    this.restoreOutside();

    const origin = this.origin;
    this.origin = null;
    if (!origin || !origin.isConnected) return;
    if (origin.closest('[inert]')) return;
    if (origin.getAttribute('aria-hidden') === 'true') return;

    // rAF: the origin may still be inside a subtree that is mid-unmount.
    requestAnimationFrame(() => origin.focus({ preventScroll: true }));
  }
}

2. A boot-once live announcer with queueing and coalescing

// src/a11y/announcer.ts
type Politeness = 'polite' | 'assertive';
interface QueuedMessage { message: string; politeness: Politeness }

const VISUALLY_HIDDEN = {
  position: 'absolute',
  width: '1px',
  height: '1px',
  margin: '-1px',
  padding: '0',
  overflow: 'hidden',
  clip: 'rect(0 0 0 0)',
  clipPath: 'inset(50%)',
  whiteSpace: 'nowrap',
  border: '0',
  // Deliberately NOT display:none or visibility:hidden. Either of those removes
  // the node from the accessibility tree and kills every announcement.
} as const satisfies Partial<CSSStyleDeclaration>;

export class LiveAnnouncer {
  private static instance: LiveAnnouncer | undefined;
  private readonly regions: Record<Politeness, HTMLElement>;
  private readonly lastRendered = new Map<Politeness, string>();
  private readonly queue: QueuedMessage[] = [];
  private busy = false;

  private constructor() {
    if (!document.body) {
      throw new Error('LiveAnnouncer must be constructed after DOMContentLoaded.');
    }
    this.regions = {
      polite: this.createRegion('polite'),
      assertive: this.createRegion('assertive'),
    };
  }

  static get(): LiveAnnouncer {
    LiveAnnouncer.instance ??= new LiveAnnouncer();
    return LiveAnnouncer.instance;
  }

  private createRegion(politeness: Politeness): HTMLElement {
    const el = document.createElement('div');
    el.dataset.a11yLive = 'true';
    el.setAttribute('aria-live', politeness);
    el.setAttribute('aria-atomic', 'true');
    el.setAttribute('aria-relevant', 'additions text');
    el.setAttribute('role', politeness === 'assertive' ? 'alert' : 'status');
    Object.assign(el.style, VISUALLY_HIDDEN);
    // Mounted immediately and permanently. This is the entire trick.
    document.body.append(el);
    return el;
  }

  announce(message: string, politeness: Politeness = 'polite'): void {
    const text = message.trim();
    if (!text) return;

    if (politeness === 'polite') {
      // Last-write-wins: keystroke-driven filter results collapse into one utterance.
      const pending = this.queue.findIndex((q) => q.politeness === 'polite');
      if (pending >= 0) {
        this.queue[pending] = { message: text, politeness };
        return;
      }
    } else if (this.queue.some((q) => q.politeness === 'assertive')) {
      // Never queue two interrupting messages; the second is stale by the time it plays.
      return;
    }

    if (this.queue.length >= 4) this.queue.shift();
    this.queue.push({ message: text, politeness });
    void this.drain();
  }

  private async drain(): Promise<void> {
    if (this.busy) return;
    this.busy = true;
    try {
      while (this.queue.length > 0) {
        const next = this.queue.shift();
        if (next) await this.flush(next);
      }
    } finally {
      this.busy = false;
    }
  }

  private flush({ message, politeness }: QueuedMessage): Promise<void> {
    const region = this.regions[politeness];
    // NVDA and JAWS suppress a second announcement of an identical string, so a
    // repeat needs an empty render, a settle gap, and a fresh injection.
    const repeat = message === this.lastRendered.get(politeness);
    const settle = repeat ? 120 : 0;

    return new Promise((resolve) => {
      requestAnimationFrame(() => {
        region.textContent = '';
        window.setTimeout(() => {
          // Trailing non-breaking space forces a discrete text mutation even when
          // the message is byte-identical to the previous one.
          region.textContent = message + '\u00A0';
          this.lastRendered.set(politeness, message);
          window.setTimeout(resolve, politeness === 'assertive' ? 2000 : 400);
        }, settle);
      });
    });
  }
}

3. Expanding hit areas without touching layout (SC 2.5.8)

/* Visual box stays 20x20; the pointer/touch target becomes 44x44. */
.icon-button {
  position: relative;
  width: 20px;
  height: 20px;
  touch-action: manipulation;
}

.icon-button::before {
  content: '';
  position: absolute;
  inset: -12px; /* 20 + 12 + 12 = 44 CSS px in both axes */
  /* Keep the expanded target below sibling content so it never steals clicks. */
  z-index: 0;
}

/* Inline links in prose are exempt from SC 2.5.8, but nav links are not. */
.nav-link {
  display: inline-flex;
  align-items: center;
  min-height: 24px;
  min-width: 24px;
  padding: 8px 12px;
}

Pseudo-element hit-slop fails when a sibling with a higher stacking order overlaps the expanded box, and it does nothing for elements that are position: static — check both before shipping. Where hit-slop is impossible, increase min-height/min-width and absorb the layout change with gap reduction; a 4 px spacing reduction is cheaper than a WCAG failure.

4. A CI guard that catches regressions before review

// tests/a11y/focus-and-wcag.spec.ts
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';

test('dialog contains focus and restores it to the trigger', async ({ page }) => {
  await page.goto('/settings');
  const trigger = page.getByRole('button', { name: 'Delete workspace' });
  await trigger.focus();
  await trigger.press('Enter');

  await expect(page.getByRole('dialog')).toBeVisible();

  // 40 Tab presses: focus must never leave the dialog subtree.
  for (let i = 0; i < 40; i += 1) {
    await page.keyboard.press('Tab');
    const inside = await page.evaluate(() => {
      const dialog = document.querySelector('[role=dialog], dialog');
      return dialog !== null && dialog.contains(document.activeElement);
    });
    expect(inside, `focus escaped on Tab press ${i + 1}`).toBe(true);
  }

  await page.keyboard.press('Escape');
  await expect(trigger).toBeFocused();
});

test('no axe violations at WCAG 2.2 AA', async ({ page }) => {
  await page.goto('/settings');
  const { violations } = await new AxeBuilder({ page })
    .withTags(['wcag2a', 'wcag2aa', 'wcag21aa', 'wcag22aa'])
    .analyze();
  expect(violations, JSON.stringify(violations, null, 2)).toEqual([]);
});

Performance Benchmarks & Trade-Offs

Figures below come from a reference harness (Chrome 126, 2019 MacBook Pro, 6× CPU throttle, 200-node overlay, 40 rapid announcements) plus published bundle sizes. Treat them as orders of magnitude, not gospel.

| Focus containment strategy | JS cost (gzip) | LOC | Containment guarantee | Browser floor | Primary risk | | --- | --- | --- | --- | --- | --- | | <dialog>.showModal() + top layer | 0 KB | ~10 | Native; UA inerts the rest of the document | Chrome 37 / Firefox 98 / Safari 15.4 | Backdrop click-to-close is not native; cancel must be handled explicitly | | inert + focusin guard | 0 KB | ~70 | Strong; script-invoked focus() is bounced | Chrome 102 / Firefox 112 / Safari 15.5 | Must skip [inert] on live regions and nested traps; cleanup on unmount | | Sentinel <span tabindex=0> boundaries | 0 KB | ~40 | Good for Tab; mouse and script focus can still escape | Every engine, incl. IE11 | Adds phantom tab stops; VoiceOver sometimes announces the sentinel | | focus-trap + tabbable (npm) | ~11–13 KB | ~5 | Good | IE11+ | Extra dependency; cannot enter the top layer; version drift across upgrades | | tabindex=-1 on all outside nodes | 0 KB | ~120+ | Fragile | Any | Destroys restore order and third-party widgets; never ship this | | Roving tabindex (composites) | 0 KB | ~40 | n/a — single tab stop inside the widget | Any | Must not reset the active index on re-render (SC 2.4.3) | | aria-activedescendant | 0 KB | ~30 | n/a — DOM focus stays on the container | Any, but AT behaviour varies | Container must be focusable; VoiceOver lags on very large lists |

Timing observations from the harness: focus movement inside a trapped dialog measured a p95 of 1.4 ms per Tab press with inert, versus 2.9 ms with sentinel-only handling and 6.1 ms with the npm trap doing a full tabbable re-scan on every keydown. Announcement latency from announce() call to the AT receiving the AX mutation measured a p95 of ~34 ms (two animation frames plus the mutation queue) — imperceptible, and the same code path that fixes the reliability failure.

| Target size floor | Minimum | Source / scope | | --- | --- | --- | | WCAG 2.2 SC 2.5.8 Target Size (Minimum), AA | 24×24 CSS px | Or a 24 px-diameter spacing circle that intersects no other target. Exceptions: inline text links, UA-controlled controls, essential sizing | | WCAG 2.1 SC 2.5.5 Target Size, AAA | 44×44 CSS px | Same exception list as above | | Apple Human Interface Guidelines | 44×44 pt | iOS/iPadOS — approximately 44×44 CSS px at 1× density | | Material Design 3 | 48×48 dp | Android touch targets | | GOV.UK Design System | 44×44 px | Chosen to exceed the AA floor for public-sector services | | WCAG 2.2 SC 2.5.7 Dragging Movements, AA | n/a | Any drag interaction must have a single-pointer, non-dragging alternative |

Pro-Tips & Common Pitfalls

Anti-patterns that have caused real incidents:

  • ❌ Toggling a live region with display: none or visibility: hidden. The node leaves the accessibility tree and the announcement never fires.
  • ❌ Mounting role="alert" with its text already inside on first render. Some AT announce it, some do not, and the bug depends on render timing.
  • ❌ Resetting a roving tabindex to index 0 on every render. Scroll position and focus both jump — a direct SC 2.4.3 failure.
  • ❌ outline: none without a :focus-visible replacement. This is SC 2.4.7, and SC 2.4.11 makes it worse under sticky headers.
  • ❌ Sticky headers, cookie bars, and chat launchers without scroll-margin-top on focusable targets. This is the single most common SC 2.4.11 failure I find in audits.
  • ❌ aria-label on a bare <div> with no role. AT ignores the label entirely; the text is invisible to both screen readers and search crawlers.
  • ❌ Positive tabindex values (tabindex="3"). They create an order the DOM cannot express and break on any refactor.
  • ❌ aria-hidden="true" on an ancestor of a focusable element. axe flags this as aria-hidden-focus, and it strands keyboard users in an invisible trap.
  • ❌ display: none on an open <dialog>. You destroy the top layer and the Escape handler in one CSS rule.
  • ❌ Announcement storms: a live region inside a 20 Hz polling loop. Throttle to thresholds or the AT queue never drains.

Checklist before every accessibility-sensitive PR:

  • ✅ Skip link is the first tabbable element and becomes visible on focus.
  • ✅ Every composite widget is a single tab stop with documented arrow-key semantics.
  • ✅ Focus is restored after every overlay close, verified by an assertion, not by eye.
  • ✅ Announcements use role="status" by default and role="alert" only for genuine interruptions.
  • ✅ Target sizes are ≥24×24 CSS px, or ≥44×44 wherever the design can afford it.
  • ✅ prefers-reduced-motion disables non-essential transitions.
  • ✅ The layout survives 400% zoom at a 1280 px viewport (SC 1.4.10 Reflow).
  • ✅ At least one manual pass with NVDA+Firefox and VoiceOver+Safari before merge, not before release.
  • ✅ Automation (axe + Pa11y + Lighthouse) runs on every PR — it catches the cheap 30–40% so humans can spend their time on the expensive rest.

Frequently Asked Questions (FAQ)

Does the `inert` attribute replace a focus trap entirely?

For modal overlays, yes — inert plus a focusin guard covers containment, and if the overlay is a <dialog> opened with showModal(), the engine handles it for you. For non-modal overlays (popovers, autocomplete listboxes, inline drawers) you must not inert the page, because users still need to interact with content behind the overlay. Those need roving tabindex or aria-activedescendant instead, plus an explicit dismiss path on Escape. The one case inert never solves is focus restoration, which is application state and must be implemented by hand with isConnected and [inert] checks.

Why does my ARIA live region work in NVDA but not in VoiceOver?

The three usual causes, in order of frequency: (1) the region was mounted in the same commit as its text, so the accessibility tree mutation targeted a node that had not been painted — fix it by creating the region at application boot and injecting after two animation frames; (2) an ancestor was display: none, visibility: hidden, or had aria-hidden="true" at injection time, which removed the region from the tree; (3) on iOS, an element with aria-modal="true" was open and the live region lived outside the modal subtree, which VoiceOver silently ignores. VoiceOver is also stricter than NVDA about identical repeated strings, which is why the announcer above appends a non-breaking space and inserts a settle gap before re-announcing the same message.

How do I test WCAG 2.2 target size (SC 2.5.8) automatically in CI?

Use getBoundingClientRect() on every interactive element and assert both dimensions are ≥24 CSS px, or that a 24 px-diameter circle centred on the target intersects no other target's rect (the spacing exception). Filter out elements where checkVisibility() returns false and any element matching the inline-link exception, or you will drown in false positives from off-screen menus. Be explicit about what automation cannot decide: whether a control is *essential* (an exception), whether an inline link inside a paragraph qualifies for the inline exception, and whether a 23×30 px target passes on spacing grounds. The practical split is automated measurement for the numeric floor plus a one-line human sign-off on the exceptions list.

*Reviewed against WCAG 2.2 (W3C Recommendation, 5 October 2023) and the ARIA Authoring Practices Guide patterns current at the time of writing.*