An open source design system that's fully customizable and agent ready
TypeScript
fix(core): focus trap and live-region hardening (#4375)
Baraa Hamodif7bce661c572
diff --git a/.changeset/a11y-focus-trap-hardening.md b/.changeset/a11y-focus-trap-hardening.mdnew file mode 100644index 0000000000..cefc659317--- /dev/null+++ b/.changeset/a11y-focus-trap-hardening.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] hooks: resolve focus-trap Escape by DOM depth instead of push order, exclude aria-hidden subtrees from trap tab cycles, and auto-clear live regions after announcing so stale status text does not linger+@bhamodidiff --git a/packages/core/src/hooks/useAnnounce.test.tsx b/packages/core/src/hooks/useAnnounce.test.tsxindex 6f3e11d289..bf10ad8603 100644--- a/packages/core/src/hooks/useAnnounce.test.tsx+++ b/packages/core/src/hooks/useAnnounce.test.tsx@@ -9,8 +9,8 @@* SYNC: When useAnnounce.ts changes, update tests to match new behavior*/-import {describe, it, expect, afterEach} from 'vitest';-import {renderHook, waitFor} from '@testing-library/react';+import {describe, it, expect, afterEach, vi} from 'vitest';+import {act, renderHook, waitFor} from '@testing-library/react';import {useAnnounce, __resetLiveRegionsForTest} from './useAnnounce';afterEach(() => {@@ -82,6 +82,79 @@ describe('useAnnounce', () => {expect(politeRegion()).toBeNull();});+ it('clears the region after the clear delay, but not before', () => {+ vi.useFakeTimers();+ try {+ const {result} = renderHook(() => useAnnounce());+ result.current('Saved');+ // Flush the rAF that re-sets the message.+ act(() => {+ vi.advanceTimersByTime(50);+ });+ expect(politeRegion()?.textContent).toBe('Saved');++ // The message survives long enough for AT to finish reading it.+ act(() => {+ vi.advanceTimersByTime(1000);+ });+ expect(politeRegion()?.textContent).toBe('Saved');++ // After the clear delay, stale status text is removed from the DOM.+ act(() => {+ vi.advanceTimersByTime(10_000);+ });+ expect(politeRegion()?.textContent).toBe('');+ } finally {+ vi.useRealTimers();+ }+ });++ it('resets the clear timer on each announce', () => {+ vi.useFakeTimers();+ try {+ const {result} = renderHook(() => useAnnounce());+ result.current('first');+ act(() => {+ vi.advanceTimersByTime(1500);+ });+ // Announcing again must reset the pending clear, not inherit it.+ result.current('second');+ act(() => {+ vi.advanceTimersByTime(1900);+ });+ // 3.4s after 'first' (past its clear point) but only 1.9s after+ // 'second' — the newer message must still be present.+ expect(politeRegion()?.textContent).toBe('second');+ act(() => {+ vi.advanceTimersByTime(10_000);+ });+ expect(politeRegion()?.textContent).toBe('');+ } finally {+ vi.useRealTimers();+ }+ });++ it('re-announces normally after a clear', () => {+ vi.useFakeTimers();+ try {+ const {result} = renderHook(() => useAnnounce());+ result.current('gone soon');+ act(() => {+ vi.advanceTimersByTime(10_000);+ });+ expect(politeRegion()?.textContent).toBe('');++ // The clear-then-rAF re-announce pattern still works after a clear.+ result.current('back again');+ act(() => {+ vi.advanceTimersByTime(50);+ });+ expect(politeRegion()?.textContent).toBe('back again');+ } finally {+ vi.useRealTimers();+ }+ });+it('reuses the same singleton regions across hook instances', async () => {const {result: a} = renderHook(() => useAnnounce());a.current('first');diff --git a/packages/core/src/hooks/useAnnounce.ts b/packages/core/src/hooks/useAnnounce.tsindex 6e2c3b1a52..8529396056 100644--- a/packages/core/src/hooks/useAnnounce.ts+++ b/packages/core/src/hooks/useAnnounce.ts@@ -7,7 +7,9 @@* @input Uses React useCallback; DOM APIs for a singleton live-region pair* @output Exports useAnnounce hook and AnnouncePoliteness type* @position Core a11y hook; provides imperative screen-reader announcements- * via persistently-mounted polite/assertive live regions+ * via persistently-mounted polite/assertive live regions; regions are+ * auto-cleared shortly after announcing so stale status text does not+ * linger in the accessibility tree** SYNC: When modified, update:* - /packages/core/src/hooks/index.ts@@ -47,6 +49,40 @@ interface LiveRegions {assertive: HTMLElement;}+/**+ * How long an announcement stays in its region before being auto-cleared.+ * Long enough for screen readers to pick the message up and finish reading+ * it; clearing afterwards keeps stale status text out of the accessibility+ * tree for users who browse the DOM later. Each announce resets the timer.+ */+const CLEAR_DELAY_MS = 2000;++const clearTimers: {+ [K in AnnouncePoliteness]: ReturnType<typeof setTimeout> | null;+} = {+ polite: null,+ assertive: null,+};++function cancelScheduledClear(politeness: AnnouncePoliteness): void {+ const timer = clearTimers[politeness];+ if (timer != null) {+ clearTimeout(timer);+ clearTimers[politeness] = null;+ }+}++function scheduleClear(+ politeness: AnnouncePoliteness,+ target: HTMLElement,+): void {+ cancelScheduledClear(politeness);+ clearTimers[politeness] = setTimeout(() => {+ clearTimers[politeness] = null;+ target.textContent = '';+ }, CLEAR_DELAY_MS);+}+// Singleton: the live regions are created ONCE and stay mounted for the// lifetime of the document. This is the crux of reliable announcements — many// screen readers will not announce content injected into a live region that is@@ -103,6 +139,10 @@ function announceMessage(requestAnimationFrame(() => {target.textContent = message;});+ // Auto-clear so the last message does not linger in the accessibility tree+ // indefinitely. Scheduled per announce, so a newer announcement always+ // resets the countdown (the delay comfortably outlasts the rAF re-set).+ scheduleClear(politeness, target);}/**@@ -111,6 +151,7 @@ function announceMessage(* so stale status text does not linger in the accessibility tree.*/function clearRegion(politeness: AnnouncePoliteness): void {+ cancelScheduledClear(politeness);if (!regions) {return;}@@ -126,6 +167,9 @@ function clearRegion(politeness: AnnouncePoliteness): void {* The polite and assertive regions are created once on first use and kept* mounted, so announcements are reliable even for messages that appear* immediately (unlike a live region rendered together with its content).+ * Each message is automatically cleared a couple of seconds after being+ * announced, so users browsing the DOM later do not encounter stale status+ * text; announcing again before the clear simply resets the countdown.** @example* ```@@ -160,6 +204,8 @@ export function useAnnounce(): AnnounceFn {* @internal*/export function __resetLiveRegionsForTest(): void {+ cancelScheduledClear('polite');+ cancelScheduledClear('assertive');if (regions) {regions.polite.remove();regions.assertive.remove();diff --git a/packages/core/src/hooks/useFocusTrap.test.tsx b/packages/core/src/hooks/useFocusTrap.test.tsxindex e5a9e0ffe6..6d6aa33267 100644--- a/packages/core/src/hooks/useFocusTrap.test.tsx+++ b/packages/core/src/hooks/useFocusTrap.test.tsx@@ -50,6 +50,39 @@ function EscapeTrap({);}+function NestedInnerTrap({onEscape}: {onEscape: () => void}) {+ const {containerRef} = useFocusTrap<HTMLDivElement>({+ isActive: true,+ onEscape,+ });+ return (+ <div ref={containerRef} data-testid="nested-inner">+ <button type="button">inner-btn</button>+ </div>+ );+}++function NestedTraps({+ onOuterEscape,+ onInnerEscape,+ showInner = true,+}: {+ onOuterEscape: () => void;+ onInnerEscape: () => void;+ showInner?: boolean;+}) {+ const {containerRef} = useFocusTrap<HTMLDivElement>({+ isActive: true,+ onEscape: onOuterEscape,+ });+ return (+ <div ref={containerRef} data-testid="nested-outer">+ <button type="button">outer-btn</button>+ {showInner && <NestedInnerTrap onEscape={onInnerEscape} />}+ </div>+ );+}+function RestoreTrap({isActive}: {isActive: boolean}) {const {containerRef} = useFocusTrap<HTMLDivElement>({isActive});return (@@ -118,6 +151,47 @@ describe('useFocusTrap tabbable model (infra-8)', () => {// Focus skips the inert button and lands on the real one.expect(screen.getByTestId('real-btn')).toHaveFocus();});++ it('ignores an aria-hidden subtree when finding focusables', () => {+ render(+ <Trap>+ <div aria-hidden="true">+ <button type="button" data-testid="aria-hidden-btn">+ Hidden from AT+ </button>+ </div>+ <button type="button" data-testid="real-btn">+ Real+ </button>+ </Trap>,+ );+ fireEvent.click(screen.getByTestId('focus-first'));+ // An element AT cannot perceive must not be a trap tab stop (WCAG 4.1.2).+ expect(screen.getByTestId('real-btn')).toHaveFocus();+ });++ it('excludes an aria-hidden focusable from the Tab wrap boundary', () => {+ render(+ <Trap>+ <button type="button" data-testid="first">+ First+ </button>+ <button type="button" data-testid="visible-last">+ Visible last+ </button>+ <div aria-hidden="true">+ <button type="button" data-testid="aria-hidden-btn">+ Hidden from AT+ </button>+ </div>+ </Trap>,+ );+ // The last VISIBLE-to-AT element is the wrap boundary: Tab from it wraps+ // to the first element instead of landing on the aria-hidden button.+ screen.getByTestId('visible-last').focus();+ fireEvent.keyDown(document, {key: 'Tab'});+ expect(screen.getByTestId('first')).toHaveFocus();+ });});describe('FOCUSABLE_SELECTOR href matching', () => {@@ -198,6 +272,36 @@ describe('useFocusTrap Escape coordination', () => {expect(onEscape).toHaveBeenCalledTimes(1);});+ it('resolves Escape to the DOM-nested inner trap when both mount in one commit', () => {+ const outer = vi.fn();+ const inner = vi.fn();+ // Outer and inner mount in the SAME React commit. React runs child+ // effects before parent effects, so the inner trap is PUSHED first —+ // DOM containment, not push order, must decide who answers Escape.+ render(<NestedTraps onOuterEscape={outer} onInnerEscape={inner} />);+ fireEvent.keyDown(document, {key: 'Escape'});+ expect(inner).toHaveBeenCalledTimes(1);+ expect(outer).not.toHaveBeenCalled();+ });++ it('falls back to the outer trap once the nested inner trap unmounts', () => {+ const outer = vi.fn();+ const inner = vi.fn();+ const {rerender} = render(+ <NestedTraps onOuterEscape={outer} onInnerEscape={inner} />,+ );+ rerender(+ <NestedTraps+ onOuterEscape={outer}+ onInnerEscape={inner}+ showInner={false}+ />,+ );+ fireEvent.keyDown(document, {key: 'Escape'});+ expect(outer).toHaveBeenCalledTimes(1);+ expect(inner).not.toHaveBeenCalled();+ });+it('does not respond after the trap is deactivated', () => {const onEscape = vi.fn();const {rerender} = render(diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.tsindex 417230c4c4..d81f709aac 100644--- a/packages/core/src/hooks/useFocusTrap.ts+++ b/packages/core/src/hooks/useFocusTrap.ts@@ -26,24 +26,62 @@ import {FOCUSABLE_SELECTOR} from './focusableSelector';* Every active `useFocusTrap` used to attach its own document-level `keydown`* listener with no coordination, so a single Escape press closed *every* open* layer at once (e.g. a popover nested inside a Dialog closed both). Tracking- * traps in a shared stack lets only the most recently activated (top-most)- * trap respond to Escape.+ * traps in a shared stack lets only the top-most trap respond to Escape.+ *+ * "Top-most" is resolved by DOM containment first, push order second. Push+ * order alone is not reliable: React runs child effects before parent+ * effects, so when an outer and an inner (DOM-nested) trap mount in the SAME+ * commit, the inner trap pushes first and the outer trap would wrongly win a+ * pure last-pushed comparison.*/-const escapeStack: (() => void)[] = [];+interface EscapeStackEntry {+ handler: () => void;+ getContainer: () => HTMLElement | null;+}-function pushEscapeHandler(handler: () => void): void {- escapeStack.push(handler);+const escapeStack: EscapeStackEntry[] = [];++function pushEscapeHandler(entry: EscapeStackEntry): void {+ escapeStack.push(entry);}function removeEscapeHandler(handler: () => void): void {- const index = escapeStack.lastIndexOf(handler);- if (index !== -1) {- escapeStack.splice(index, 1);+ for (let i = escapeStack.length - 1; i >= 0; i--) {+ if (escapeStack[i].handler === handler) {+ escapeStack.splice(i, 1);+ return;+ }}}+/**+ * Resolve the top-most trap: walk the stack in push order, keeping the+ * deepest container by DOM containment. When a later entry's container+ * contains the current candidate's container, the candidate is nested inside+ * it and stays on top; otherwise the later push wins (containment for nested+ * traps, push order as the tiebreaker for unrelated ones).+ */function isTopEscapeHandler(handler: () => void): boolean {- return escapeStack[escapeStack.length - 1] === handler;+ if (escapeStack.length === 0) {+ return false;+ }+ let top = escapeStack[0];+ for (let i = 1; i < escapeStack.length; i++) {+ const entry = escapeStack[i];+ const topContainer = top.getContainer();+ const entryContainer = entry.getContainer();+ if (+ topContainer != null &&+ entryContainer != null &&+ entryContainer !== topContainer &&+ entryContainer.contains(topContainer)+ ) {+ // The current top is nested inside this entry — it stays on top.+ continue;+ }+ top = entry;+ }+ return top.handler === handler;}/**@@ -73,7 +111,9 @@ export function isImeKeyEvent(event: {/*** Whether an element is currently perceivable/focusable — excludes ones hidden* via `display:none`/`visibility:hidden` or inside an `inert`/`hidden` subtree,- * which the browser skips for Tab.+ * which the browser skips for Tab, and ones inside an `aria-hidden="true"`+ * subtree, which sighted-keyboard users could Tab to while AT skips them+ * (WCAG 4.1.2 — focusable content must be exposed to assistive tech).*/function isVisiblyFocusable(el: HTMLElement): boolean {if (el.hasAttribute('inert') || el.closest('[inert]')) {@@ -82,6 +122,10 @@ function isVisiblyFocusable(el: HTMLElement): boolean {if (el.hidden || el.closest('[hidden]')) {return false;}+ // closest() matches the element itself as well as any ancestor.+ if (el.closest('[aria-hidden="true"]')) {+ return false;+ }// offsetParent is null for display:none (and fixed elements); pair with a// visibility check via getComputedStyle when available.if (typeof window !== 'undefined' && window.getComputedStyle) {@@ -323,12 +367,17 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(// Register this trap on the shared Escape stack so only the top-most// active trap responds to Escape. A stable identity per active period is- // enough — we push on activate and remove on cleanup.+ // enough — we push on activate and remove on cleanup. The container is+ // read lazily: the ref may not be attached yet at effect time, and the+ // stack resolves top-most by DOM containment at keydown time.const escapeHandler = () => {onEscape?.();};if (onEscape) {- pushEscapeHandler(escapeHandler);+ pushEscapeHandler({+ handler: escapeHandler,+ getContainer: () => containerRef.current,+ });}const handleKeyDown = (event: KeyboardEvent) => {diff --git a/packages/core/src/hooks/useHotkeys.ts b/packages/core/src/hooks/useHotkeys.tsindex e057547c87..a537f63495 100644--- a/packages/core/src/hooks/useHotkeys.ts+++ b/packages/core/src/hooks/useHotkeys.ts@@ -155,6 +155,15 @@ function matchesCombo(* definitions live in a ref, so re-renders update behavior without* re-subscribing. First matching hotkey wins per event.*+ * Accessibility (WCAG 2.1.4 — Character Key Shortcuts): a shortcut whose+ * combo is a single unmodified character (letter, digit, punctuation or+ * symbol — e.g. 'c' or '/') is easily triggered by accident by speech-input+ * users and keyboard users with motor impairments. If you register one, you+ * MUST also provide at least one of: (a) a way to turn the shortcut off,+ * (b) a way to remap it to include a modifier, or (c) scope it so it is only+ * active while the relevant component has focus. Prefer `mod`-based combos+ * where possible; the `isDisabled` flag can back a user-facing off switch.+ ** @param hotkeys - Shortcut registrations to listen for.** @example