Skip to content

feat(a11y): add focus trap with nested modal support - #1528

Merged
nanaf6203-bit merged 1 commit into
MettaChain:mainfrom
precy41:feat/issue-1367-focus-trap-modal
Nov 24, 2026
Merged

nanaf6203-bit merged 1 commit into
MettaChain:mainfrom
precy41:feat/issue-1367-focus-trap-modal

Conversation

@precy41

@precy41 precy41 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes #1367

Adds a reusable focus trap to ui-extensions/ and, in the same module family, the three other accessibility primitives assigned to this contributor: reduced-motion handling (#1371), a throttled polite live region for price updates (#1369), and a 7:1 high contrast theme (#1365). The most important design decision is that the trap resolves the owning dialog by DOM depth rather than by mount order — React runs child effects before parent effects, so a modal rendered inside another would otherwise be won by the outer trap — and it re-reads focusable descendants on every Tab press instead of caching them at mount.

Also closes

Closes #1371, Closes #1369, Closes #1365

Why

ui-extensions/ had no shared focus management. PropertyComparisonTable and the dialog-like panels could open, but Tab walked straight out of the overlay into the page behind it, and closing an overlay left focus on document.body rather than the trigger. There was also no way for an extension to honour prefers-reduced-motion, no live region for price ticks, and no high contrast palette.

Rather than inventing a second mechanism, the new code follows the existing matchMedia subscription pattern in src/hooks/use-mobile.ts, reuses formatPrice from utils/formatters.ts for locale-aware prices, and reuses checkContrast from utils/searchA11yUtils.ts to prove the high contrast palette meets 7:1 instead of asserting it in prose.

What was built

File What it contains
ui-extensions/hooks/useFocusTrap.ts useFocusTrap, getFocusableElements, FOCUSABLE_SELECTOR. Registers each open trap, resolves the owning trap as the deepest one containing document.activeElement (falling back to most-recently activated), wraps Tab/Shift+Tab, re-queries focusables per keypress so dynamically added elements are included, skips hidden, [inert], aria-hidden, disabled, aria-disabled and tabindex="-1", keeps focus on the dialog when nothing is focusable, dispatches onEscape only to the owning trap, and restores focus to the trigger on deactivation when it is still connected.
ui-extensions/components/FocusTrap.tsx FocusTrap wrapper adding role="dialog", aria-modal, optional aria-label/aria-labelledby (fallback label only rendered when the caller supplied neither, so ids are never duplicated), and a pass-through for initialFocus/restoreFocus/onEscape. Inactive renders children without a wrapper.
ui-extensions/hooks/useReducedMotion.ts useReducedMotion, prefersReducedMotion (SSR-safe), reducedMotionClass, useReducedMotionClass, motionDuration (collapses to 0), REDUCED_MOTION_QUERY, REDUCED_MOTION_CLASS, and observeReducedMotion for non-React animation owners. Uses addEventListener with a addListener fallback.
ui-extensions/components/PriceUpdateAnnouncer.tsx PriceUpdateAnnouncer (role="status", aria-live="polite", aria-atomic, sr-only) plus the pure percentChange, isSignificantChange, formatPriceAnnouncement and createPriceAnnouncementGate helpers. Threshold defaults to 5%, throttle to 5000 ms; the gate takes an injected clock so timing is testable. Updates already seen are ignored, so a re-render cannot re-announce.
ui-extensions/components/highContrastTheme.ts HIGH_CONTRAST_LIGHT/HIGH_CONTRAST_DARK palettes, HIGH_CONTRAST_PAIRS (9 foreground/background combinations), highContrastPairs, highContrastStyle (the --hc-* custom properties), HIGH_CONTRAST_MIN_RATIO = 7.
ui-extensions/components/HighContrastTheme.tsx Scoped HighContrastTheme wrapper (hc-root, data-hc-theme="high", data-hc-base) and useHighContrastTheme with localStorage persistence, prefers-contrast: more support and an opt-out.
ui-extensions/styles/high-contrast.css --hc-* custom properties for light and dark base themes, plus overrides for text, links, buttons, inputs/selects/textareas, cards/tables/dialogs, :focus-visible outlines and disabled controls (dashed outline rather than opacity, so nothing is hidden).
ui-extensions/styles/reduced-motion.css prefers-reduced-motion fallback and the .motion-reduced class, both collapsing animation/transition duration, iteration count and delay.
ui-extensions/stories/HighContrastTheme.stories.tsx Four stories (light base, dark base, inlined custom properties, disabled) rendering real controls and the contrast-pair table; the axe addon runs against them.
ui-extensions/tests/focusTrap.test.tsx 15 tests.
ui-extensions/tests/useReducedMotion.test.ts 11 tests.
ui-extensions/tests/priceUpdateAnnouncer.test.tsx 17 tests.
ui-extensions/tests/highContrastTheme.test.tsx 14 tests.

Integration changes outside <module>/

No existing files modified, only additions, so regression risk is low. Every file added is inside ui-extensions/, as the isolation statement requires.

Acceptance criteria coverage (primary issue)

Closes #1367 — Focus Trap for Modal Dialogs

  • Traps Tab and Shift+Tab within modal (ui-extensions/tests/focusTrap.test.tsx: wraps on Tab / wraps on Shift+Tab)
  • Restores focus to trigger element on close (focusTrap.test.tsx: restores focus to the trigger element on close)
  • Handles dynamically added focusable elements (focusTrap.test.tsx: picks up focusable elements added after mount)
  • Skips hidden and disabled elements (focusTrap.test.tsx: getFocusableElements skips hidden, disabled and tabindex=-1 elements)
  • Works with nested modals (focusTrap.test.tsx: traps focus in the innermost modal when modals are nested; calls onEscape only for the owning trap)
  • Configurable initial focus element (focusTrap.test.tsx: focuses the configured initial focus element instead of the first one)
  • Unit tests included (15 tests, 4 suites total in this PR)

Closes #1371 — Reduced Motion Support for Animations

  • Detects prefers-reduced-motion media query (useReducedMotion.test.ts: queries the reduced motion media query)
  • Provides useReducedMotion hook (useReducedMotion.test.ts: returns the current preference and reacts to changes)
  • Returns boolean for motion preference (same suite)
  • Provides reduced motion CSS class (useReducedMotion.test.ts: exposes a CSS class name)
  • Works with Tailwind motion-reduce variant (.motion-reduced compiles the same media query as motion-reduce:, so the two compose; this cannot be asserted in jsdom, CSS is in styles/reduced-motion.css)
  • Falls back to no-animation when preference detected (useReducedMotion.test.ts: collapses durations to zero when motion is reduced; CSS clamps duration to 0.01ms)
  • Unit tests included (11 tests)

Closes #1369 — ARIA Live Regions for Real-Time Price Updates

  • Uses aria-live='polite' for price updates (priceUpdateAnnouncer.test.tsx: renders a visually hidden polite live region)
  • Throttles announcements (max 1 per 5 seconds) (priceUpdateAnnouncer.test.tsx: throttles rapid status changes to one announcement per window; drops changes below the threshold without consuming the throttle)
  • Announces significant changes only (above 5% change) (priceUpdateAnnouncer.test.tsx: defaults to a five percent threshold)
  • Formats price with locale support (priceUpdateAnnouncer.test.tsx: supports other locales and currencies)
  • Hidden from visual layout (priceUpdateAnnouncer.test.tsx: renders a visually hidden polite live region; sr-only)
  • Configurable threshold (priceUpdateAnnouncer.test.tsx: stays silent below the configurable threshold; honours a custom threshold)
  • Unit tests included (17 tests)

Closes #1365 — High Contrast Theme for All Extension Components

  • Defines high contrast color palette (min 7:1 ratio) (highContrastTheme.test.tsx: meets 7:1 for every pair on the light/dark base theme, checked with checkContrast)
  • Provides CSS custom properties for theming (highContrastTheme.test.tsx: exposes CSS custom properties for both base themes)
  • Overrides for all common UI patterns (styles/high-contrast.css: text, links, buttons, inputs, cards, tables, dialogs, focus, disabled)
  • Button, input, card, and text overrides (styles/high-contrast.css: .hc-button, .hc-input, .hc-card, .hc-text*)
  • Works with both light and dark base themes (highContrastTheme.test.tsx: uses different colours for the light and dark base themes; HighContrastTheme scopes the palette to a wrapper with data attributes)
  • No loss of functionality in high contrast (no display:none; disabled controls stay legible via dashed outline)
  • Includes Storybook story demonstrating theme (stories/HighContrastTheme.stories.tsx: 4 stories)

Deliberately deferred

None. All four issues assigned to this contributor are implemented in full; each Closes keyword above refers to work contained in this diff.

Test plan

  • npx jest ui-extensions/tests/{focusTrap,useReducedMotion,priceUpdateAnnouncer,highContrastTheme}: 57/57 passing (57 new: 15 + 11 + 17 + 14)
  • npx jest --watchAll=false --ci: 2372/2464 passing across 249 suites (before: 2315/2407 across 245 suites). The same 25 pre-existing suites / 92 pre-existing tests fail before and after; this PR adds 4 suites and 57 passing tests and no new failures.
  • npm run typecheck (tsc --noEmit): 482 errors before and 482 after — zero new, and no error mentions ui-extensions. The baseline src/ errors (e.g. src/utils/seo.ts, src/utils/security/*) are untouched by this PR.
  • Type check of the new modules that no story imports, via a temporary tsconfig extending the repo config with ui-extensions/** included: 0 errors in the 7 new source files.
  • npx eslint ui-extensions: 11 errors after vs 10 before. All are the same Parsing error: Unexpected token { in ui-extensions/stories/*.stories.tsx, because eslint.config.mjs only applies the TypeScript parser to src/** and .storybook/**; the new story inherits that pre-existing gap. See Notes.
  • npm run build: cannot pass at base. npm run build runs npm run typecheck && next build, and tsc --noEmit exits 2 on main (482 errors) while next.config.ts sets typescript.ignoreBuildErrors: false. The gate is red before this PR and this PR adds no errors to it.
  • Manual: open a FocusTrap with a keyboard, press Tab/Shift+Tab at both ends, Escape, and confirm focus returns to the trigger.

Env vars / Notes

No new environment variables.

Consumers must import the stylesheets they use; they are not imported by the components so that Jest does not need a CSS transform:

import '../styles/reduced-motion.css';   // .motion-reduced + prefers-reduced-motion fallback
import '../styles/high-contrast.css';    // .hc-root palette and control overrides

Known pre-existing gates (unchanged by this PR, documented for reviewers): typescript, lint and therefore build already fail on main because ui-extensions/** is absent from tsconfig.json's include and from the TypeScript parser files list in eslint.config.mjs. Adding ui-extensions/**/*.{ts,tsx} to both would fix all 10 existing story parse errors, but it is a repo-wide config change outside this issue's isolation boundary, so it is left out of this diff.

Extension dialogs had no shared focus management, so Tab escaped into the
page behind a modal and focus was not restored to the trigger on close.

Adds useFocusTrap/FocusTrap (DOM-depth resolution for nested modals,
restores the trigger, re-reads focusables on every Tab) along with the
three other accessibility primitives assigned to this contributor:
reduced-motion handling, a throttled polite price live region, and a
7:1 high contrast theme with a Storybook story.
@drips-wave

drips-wave Bot commented Nov 23, 2026

Copy link
Copy Markdown

@precy41 Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

@nanaf6203-bit nanaf6203-bit left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks solid — good addition. Thanks!

@nanaf6203-bit
nanaf6203-bit merged commit 6866c97 into MettaChain:main Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants