An open source design system that's fully customizable and agent ready
TypeScript
fix(hooks): widen useFocusTrap focusable model (infra-8) (#3429)
Cindy Zhang7735f9c2b34c
diff --git a/.changeset/focustrap-tabbable-model.md b/.changeset/focustrap-tabbable-model.mdnew file mode 100644index 0000000000..7c70c81b29--- /dev/null+++ b/.changeset/focustrap-tabbable-model.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] useFocusTrap: the focusable-element detection now includes `contenteditable`, media with `controls`, `iframe`, and an open `<details>`'s `<summary>`, and excludes elements hidden via `display:none`/`visibility:hidden` or inside `inert`/`hidden` subtrees. Previously a trapped surface whose only interactive content was (e.g.) a contenteditable composer could let Tab escape (infra-8).+@cixzhangdiff --git a/packages/core/src/hooks/focusableSelector.ts b/packages/core/src/hooks/focusableSelector.tsnew file mode 100644index 0000000000..eb2395fb39--- /dev/null+++ b/packages/core/src/hooks/focusableSelector.ts@@ -0,0 +1,25 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file focusableSelector.ts+ * @input None (a plain CSS selector string constant)+ * @output Exports FOCUSABLE_SELECTOR+ * @position Internal utility; the canonical CSS selector for focusable+ * elements, shared by focus-management hooks (e.g. useFocusTrap) so the+ * selector isn't duplicated across components/hooks. Not exported from the+ * public barrel — internal implementation detail.+ */++/**+ * Canonical CSS selector for commonly focusable elements. Includes the+ * tabbable natives (button/link/input/select/textarea/[tabindex]) plus+ * editable and media elements the browser also puts in the tab order —+ * contenteditable, media with controls, iframe, and an open <details>'s+ * <summary> — which a naive selector misses, letting Tab escape a trap whose+ * only interactive content is (e.g.) a contenteditable composer (infra-8).+ *+ * This is the canonical focusable selector; prefer importing it here over+ * re-declaring the string so behavior stays consistent across hooks.+ */+export const FOCUSABLE_SELECTOR =+ 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled]), [contenteditable]:not([contenteditable="false"]), audio[controls], video[controls], iframe, details > summary:first-child';diff --git a/packages/core/src/hooks/useFocusTrap.test.tsx b/packages/core/src/hooks/useFocusTrap.test.tsxnew file mode 100644index 0000000000..b7c95258c1--- /dev/null+++ b/packages/core/src/hooks/useFocusTrap.test.tsx@@ -0,0 +1,68 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useFocusTrap.test.tsx+ * @input Uses vitest, @testing-library/react, useFocusTrap hook+ * @output Unit tests for useFocusTrap tabbable-element model+ * @position Testing; validates useFocusTrap.ts focusable detection+ *+ * SYNC: When useFocusTrap.ts changes, update tests to match new behavior+ */++import {describe, it, expect} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import {useFocusTrap} from './useFocusTrap';++function Trap({children}: {children: React.ReactNode}) {+ const {containerRef, focusFirst} = useFocusTrap<HTMLDivElement>({+ isActive: true,+ });+ return (+ <div>+ <button type="button" data-testid="outside">+ Outside+ </button>+ <div ref={containerRef} data-testid="trap">+ {children}+ </div>+ <button type="button" onClick={focusFirst} data-testid="focus-first">+ Focus first+ </button>+ </div>+ );+}++describe('useFocusTrap tabbable model (infra-8)', () => {+ it('treats a contenteditable as focusable (focusFirst lands on it)', () => {+ render(+ <Trap>+ <div+ contentEditable+ data-testid="editor"+ suppressContentEditableWarning>+ Type here+ </div>+ </Trap>,+ );+ fireEvent.click(screen.getByTestId('focus-first'));+ expect(screen.getByTestId('editor')).toHaveFocus();+ });++ it('ignores an inert subtree when finding focusables', () => {+ render(+ <Trap>+ <div inert>+ <button type="button" data-testid="inert-btn">+ Inert+ </button>+ </div>+ <button type="button" data-testid="real-btn">+ Real+ </button>+ </Trap>,+ );+ fireEvent.click(screen.getByTestId('focus-first'));+ // Focus skips the inert button and lands on the real one.+ expect(screen.getByTestId('real-btn')).toHaveFocus();+ });+});diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.tsindex 7f7c37a19b..0980deed20 100644--- a/packages/core/src/hooks/useFocusTrap.ts+++ b/packages/core/src/hooks/useFocusTrap.ts@@ -17,11 +17,30 @@import {useCallback, useEffect, useRef} from 'react';+import {FOCUSABLE_SELECTOR} from './focusableSelector';+/**- * Selector for commonly focusable elements.+ * 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.*/-const FOCUSABLE_SELECTOR =- 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])';+function isVisiblyFocusable(el: HTMLElement): boolean {+ if (el.hasAttribute('inert') || el.closest('[inert]')) {+ return false;+ }+ if (el.hidden || el.closest('[hidden]')) {+ 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) {+ const style = window.getComputedStyle(el);+ if (style.visibility === 'hidden' || style.display === 'none') {+ return false;+ }+ }+ return true;+}/*** Get all focusable elements within a container.@@ -29,7 +48,7 @@ const FOCUSABLE_SELECTOR =function getFocusableElements(container: HTMLElement): HTMLElement[] {return Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),- );+ ).filter(isVisiblyFocusable);}/**