Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(Dialog, AlertDialog, CommandPalette, BottomSheet, Lightbox): Tab wraps inside the open modal through the shared focus-region module (#8883)

Cindy Zhang7eee90594d74
diff --git a/.changeset/modal-focus-region-tab-wrap.md b/.changeset/modal-focus-region-tab-wrap.md
new file mode 100644
index 0000000000..a4d1970d87
--- /dev/null
+++ b/.changeset/modal-focus-region-tab-wrap.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Dialog, AlertDialog, CommandPalette, BottomSheet, Lightbox: Tab now wraps inside an open modal Dialog, AlertDialog, CommandPalette, modal BottomSheet or Lightbox. Tab from the last control moves to the first, and Shift+Tab from the first moves to the last, so keyboard and screen-reader users no longer land in the browser's toolbar from inside these modals. They now use the same focus-region module that Drawer and Popover use. When modals nest, the innermost one handles Tab. Non-modal sheets and inline dialogs do not trap focus. Fixes #8841.
+
+@cixzhang
diff --git a/packages/core/src/AlertDialog/AlertDialog.test.tsx b/packages/core/src/AlertDialog/AlertDialog.test.tsx
index fdf99ec2a5..f2f28dd189 100644
--- a/packages/core/src/AlertDialog/AlertDialog.test.tsx
+++ b/packages/core/src/AlertDialog/AlertDialog.test.tsx
@@ -31,6 +31,7 @@ import {getGestureHost} from '../gestures/GestureHost';
import {isTrackedByGroup} from '../privateAttributes/pressGroupItem.stylex';
import {AlertDialog} from './AlertDialog';
import {useImperativeAlertDialog} from './useImperativeAlertDialog';
+import {getFocusableElements} from '../hooks/useFocusTrap';
// The gesture host reads `(pointer: coarse)` once per document and keeps that
// query for the document's life: it gets this live one (see beforeAll), whose
@@ -823,3 +824,37 @@ describe('useImperativeAlertDialog', () => {
expect(screen.getByTestId('is-open')).toHaveTextContent('true');
});
});
+
+// Tab from the last tabbable control wraps to the first and Shift+Tab from the
+// first wraps to the last, so focus never leaves the modal for the browser's
+// own UI.
+function expectTabWrapsInside(modal: HTMLElement) {
+ const tabbables = getFocusableElements(modal);
+ expect(tabbables.length).toBeGreaterThan(0);
+ const first = tabbables[0];
+ const last = tabbables[tabbables.length - 1];
+
+ last.focus();
+ expect(last).toHaveFocus();
+ expect(fireEvent.keyDown(last, {key: 'Tab'})).toBe(false);
+ expect(first).toHaveFocus();
+
+ expect(fireEvent.keyDown(first, {key: 'Tab', shiftKey: true})).toBe(false);
+ expect(last).toHaveFocus();
+}
+
+describe('AlertDialog focus region (Dialog DEC-2)', () => {
+ it('wraps Tab and Shift+Tab inside the open modal', () => {
+ render(
+ <AlertDialog
+ isOpen
+ onOpenChange={() => {}}
+ title="Delete item?"
+ description="This action cannot be undone."
+ actionLabel="Delete"
+ onAction={() => {}}
+ />,
+ );
+ expectTabWrapsInside(screen.getByRole('alertdialog'));
+ });
+});
diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsx
index ae30e3f75d..e1426a874a 100644
--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx
@@ -24,6 +24,7 @@ import {BottomSheet} from './BottomSheet';
import {BottomSheetEscapeContext} from './bottomSheetEscape';
import {resetBottomSheetStackForTests} from './bottomSheetStack';
import {BottomSheetSwitcher} from './BottomSheetSwitcher';
+import {getFocusableElements} from '../hooks/useFocusTrap';
import {__resetInteractionModalityForTest} from '../utils/interactionModality';
import {__focusTakeoverCallersForTest} from '../keyboard/keyboardHeight';
import {__resetRevealsAtReportForTest} from '../keyboard/useMobileKeyboard';
@@ -4365,3 +4366,48 @@ describe('BottomSheet', () => {
});
});
});
+
+// Tab from the last tabbable control wraps to the first and Shift+Tab from the
+// first wraps to the last, so focus never leaves the modal for the browser's
+// own UI.
+function expectTabWrapsInside(modal: HTMLElement) {
+ const tabbables = getFocusableElements(modal);
+ expect(tabbables.length).toBeGreaterThan(0);
+ const first = tabbables[0];
+ const last = tabbables[tabbables.length - 1];
+
+ last.focus();
+ expect(last).toHaveFocus();
+ expect(fireEvent.keyDown(last, {key: 'Tab'})).toBe(false);
+ expect(first).toHaveFocus();
+
+ expect(fireEvent.keyDown(first, {key: 'Tab', shiftKey: true})).toBe(false);
+ expect(last).toHaveFocus();
+}
+
+describe('BottomSheet focus region (Dialog DEC-2)', () => {
+ it('wraps Tab and Shift+Tab inside an open modal sheet', () => {
+ render(
+ <BottomSheet isOpen onOpenChange={() => {}} label="Filters">
+ <button type="button">First</button>
+ <button type="button">Last</button>
+ </BottomSheet>,
+ );
+ expectTabWrapsInside(screen.getByRole('dialog'));
+ });
+
+ it('leaves Tab alone in a non-modal sheet', () => {
+ render(
+ <BottomSheet
+ isOpen
+ hasScrim={false}
+ onOpenChange={() => {}}
+ label="Filters">
+ <button type="button">Only</button>
+ </BottomSheet>,
+ );
+ const only = screen.getByRole('button', {name: 'Only'});
+ only.focus();
+ expect(fireEvent.keyDown(only, {key: 'Tab'})).toBe(true);
+ });
+});
diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsx
index cdadbdc113..dbdb5992ea 100644
--- a/packages/core/src/BottomSheet/BottomSheet.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.tsx
@@ -81,6 +81,7 @@ import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {useModalOutlet} from '../Layer/modalOutlet';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
+import {useFocusRegionContainment} from '../hooks/useFocusTrap';
import {focusForLastInput} from '../utils/focusReturn';
import {useInteractionModalityTracking} from '../utils/interactionModality';
import {
@@ -444,6 +445,10 @@ function StandaloneBottomSheet({
false,
);
const isEntrySettled = settledOpen && isOpen;
+ // Only a modal sheet contains Tab; a non-modal one leaves the page's focus
+ // order alone. A closing sheet stops containing as soon as it starts to
+ // leave.
+ useFocusRegionContainment(dialogRef, isOpen && hasScrim);
// Presentation outlives the controlled prop: a closing sheet stays mounted
// and in its native host through its exit, and only its motion completion
// (or a replace finishing) clears it. The open flip is derived during
diff --git a/packages/core/src/CommandPalette/CommandPalette.test.tsx b/packages/core/src/CommandPalette/CommandPalette.test.tsx
index 641e023341..5dcf25982b 100644
--- a/packages/core/src/CommandPalette/CommandPalette.test.tsx
+++ b/packages/core/src/CommandPalette/CommandPalette.test.tsx
@@ -13,6 +13,7 @@ import userEvent from '@testing-library/user-event';
import {useState} from 'react';
import {CommandPalette} from './CommandPalette';
import {CommandPaletteInput} from './CommandPaletteInput';
+import {getFocusableElements} from '../hooks/useFocusTrap';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {createStaticSource} from '@astryxdesign/core/Typeahead';
import type {SearchSource, SearchableItem} from '@astryxdesign/core/Typeahead';
@@ -917,3 +918,34 @@ describe('CommandPalette', () => {
});
});
});
+
+// Tab from the last tabbable control wraps to the first and Shift+Tab from the
+// first wraps to the last, so focus never leaves the modal for the browser's
+// own UI.
+function expectTabWrapsInside(modal: HTMLElement) {
+ const tabbables = getFocusableElements(modal);
+ expect(tabbables.length).toBeGreaterThan(0);
+ const first = tabbables[0];
+ const last = tabbables[tabbables.length - 1];
+
+ last.focus();
+ expect(last).toHaveFocus();
+ expect(fireEvent.keyDown(last, {key: 'Tab'})).toBe(false);
+ expect(first).toHaveFocus();
+
+ expect(fireEvent.keyDown(first, {key: 'Tab', shiftKey: true})).toBe(false);
+ expect(last).toHaveFocus();
+}
+
+describe('CommandPalette focus region (Dialog DEC-2)', () => {
+ it('keeps Tab inside the open palette', () => {
+ render(
+ <CommandPalette
+ isOpen
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ />,
+ );
+ expectTabWrapsInside(document.querySelector('dialog') as HTMLElement);
+ });
+});
diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsx
index 2e8cc4aea3..f7b3e33420 100644
--- a/packages/core/src/Dialog/Dialog.test.tsx
+++ b/packages/core/src/Dialog/Dialog.test.tsx
@@ -28,6 +28,7 @@ import {
resolveDialogPositionOffsets,
} from './Dialog';
import {DialogHeader} from './DialogHeader';
+import {getFocusableElements, useFocusTrap} from '../hooks/useFocusTrap';
import {defineTheme, generateThemeCSS} from '../theme';
import {
__resetInteractionModalityForTest,
@@ -1881,3 +1882,143 @@ describe('Dialog', () => {
});
});
});
+
+// Tab from the last tabbable control wraps to the first and Shift+Tab from the
+// first wraps to the last, so focus never leaves the modal for the browser's
+// own UI.
+function expectTabWrapsInside(modal: HTMLElement) {
+ const tabbables = getFocusableElements(modal);
+ expect(tabbables.length).toBeGreaterThan(0);
+ const first = tabbables[0];
+ const last = tabbables[tabbables.length - 1];
+
+ last.focus();
+ expect(last).toHaveFocus();
+ expect(fireEvent.keyDown(last, {key: 'Tab'})).toBe(false);
+ expect(first).toHaveFocus();
+
+ expect(fireEvent.keyDown(first, {key: 'Tab', shiftKey: true})).toBe(false);
+ expect(last).toHaveFocus();
+}
+
+function PanelRegion() {
+ const {containerRef} = useFocusTrap<HTMLDivElement>({isActive: true});
+ return (
+ <div ref={containerRef}>
+ <button type="button">Panel first</button>
+ <button type="button">Panel last</button>
+ </div>
+ );
+}
+
+describe('Dialog focus region (DEC-2)', () => {
+ it('lets a region opened last inside the Dialog answer its own Tab', () => {
+ // The panel's last control is also the Dialog's last Tab stop. The
+ // Dialog's listener runs first because it was activated first, so only
+ // the innermost-region rule keeps Tab inside the panel.
+ const {rerender} = render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Settings">
+ <button type="button">Dialog first</button>
+ </Dialog>,
+ );
+ rerender(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Settings">
+ <button type="button">Dialog first</button>
+ <PanelRegion />
+ </Dialog>,
+ );
+ const panelLast = screen.getByRole('button', {name: 'Panel last'});
+ panelLast.focus();
+
+ expect(fireEvent.keyDown(panelLast, {key: 'Tab'})).toBe(false);
+ expect(screen.getByRole('button', {name: 'Panel first'})).toHaveFocus();
+ });
+
+ it('leaves a Tab that the last control handles itself where it is', () => {
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Settings">
+ <button type="button">First</button>
+ <textarea
+ aria-label="Notes"
+ onKeyDown={event => {
+ if (event.key === 'Tab') {
+ // An editor that indents on Tab.
+ event.preventDefault();
+ }
+ }}
+ />
+ </Dialog>,
+ );
+ const notes = screen.getByRole('textbox', {name: 'Notes'});
+ notes.focus();
+
+ fireEvent.keyDown(notes, {key: 'Tab'});
+ expect(notes).toHaveFocus();
+ });
+
+ it('wraps Tab and Shift+Tab inside the open modal', () => {
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Settings">
+ <button type="button">First</button>
+ <button type="button">Last</button>
+ </Dialog>,
+ );
+ expectTabWrapsInside(screen.getByRole('dialog'));
+ });
+
+ it('wraps Shift+Tab from the focused title to the last control', () => {
+ render(
+ <Dialog isOpen onOpenChange={() => {}}>
+ <DialogHeader title="Settings" />
+ <button type="button">First</button>
+ <button type="button">Last</button>
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog');
+ const title = screen.getByRole('heading', {name: 'Settings'});
+ // The title takes programmatic focus (tabIndex -1) and is not a Tab stop.
+ title.focus();
+ expect(title).toHaveFocus();
+ const tabbables = getFocusableElements(dialog);
+ expect(tabbables).not.toContain(title);
+
+ expect(fireEvent.keyDown(title, {key: 'Tab', shiftKey: true})).toBe(false);
+ expect(tabbables[tabbables.length - 1]).toHaveFocus();
+ });
+
+ it('lets the inner modal answer Tab when a Dialog opens from a Dialog', () => {
+ function Nested({isInnerOpen}: {isInnerOpen: boolean}) {
+ return (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Outer">
+ <button type="button">Outer first</button>
+ <Dialog
+ isOpen={isInnerOpen}
+ onOpenChange={() => {}}
+ aria-label="Inner">
+ <button type="button">Inner first</button>
+ <button type="button">Inner last</button>
+ </Dialog>
+ </Dialog>
+ );
+ }
+ // The outer modal's region is active before the inner one opens, as when
+ // a person opens a Dialog from a Dialog.
+ const {rerender} = render(<Nested isInnerOpen={false} />);
+ rerender(<Nested isInnerOpen />);
+ expectTabWrapsInside(screen.getByRole('dialog', {name: 'Inner'}));
+ });
+
+ it('leaves Tab alone when the Dialog renders inline', () => {
+ render(
+ <>
+ <Dialog isOpen isInline onOpenChange={() => {}} aria-label="Preview">
+ <button type="button">Only</button>
+ </Dialog>
+ <button type="button">After</button>
+ </>,
+ );
+ const only = screen.getByRole('button', {name: 'Only'});
+ only.focus();
+ expect(fireEvent.keyDown(only, {key: 'Tab'})).toBe(true);
+ });
+});
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index 4b896e341b..74c6191112 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -55,6 +55,7 @@ import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {holdEntranceInput} from '../Layer/holdEntranceInput';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {useBackdropPress} from '../Layer/useBackdropPress';
+import {useFocusRegionContainment} from '../hooks/useFocusTrap';
import {useModalOutlet} from '../Layer/modalOutlet';
import {
colorVars,
@@ -549,6 +550,9 @@ export function Dialog({
props['aria-label'] != null || props['aria-labelledby'] != null;
const dialogRef = useRef<HTMLDialogElement>(null);
+ // Native showModal() lets Tab leave for the browser's own UI, so the shared
+ // module wraps it. An inline preview is not modal and contains nothing.
+ useFocusRegionContainment(dialogRef, isOpen && !isInline);
// Callback ref on the <dialog>: sync the default aria-labelledby from the
// DialogHeader title (if one rendered) in the same commit, with no second
diff --git a/packages/core/src/Lightbox/Lightbox.test.tsx b/packages/core/src/Lightbox/Lightbox.test.tsx
index c4b5d7e35d..8e441bccb7 100644
--- a/packages/core/src/Lightbox/Lightbox.test.tsx
+++ b/packages/core/src/Lightbox/Lightbox.test.tsx
@@ -4,6 +4,7 @@ import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import {Profiler, StrictMode, useState} from 'react';
import {Lightbox} from './Lightbox';
+import {getFocusableElements} from '../hooks/useFocusTrap';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {InternationalizationProvider} from '../i18n';
@@ -917,3 +918,37 @@ describe('Lightbox unmounting while open', () => {
expect(document.activeElement).toBe(opener);
});
});
+
+// Tab from the last tabbable control wraps to the first and Shift+Tab from the
+// first wraps to the last, so focus never leaves the modal for the browser's
+// own UI.
+function expectTabWrapsInside(modal: HTMLElement) {
+ const tabbables = getFocusableElements(modal);
+ expect(tabbables.length).toBeGreaterThan(0);
+ const first = tabbables[0];
+ const last = tabbables[tabbables.length - 1];
+
+ last.focus();
+ expect(last).toHaveFocus();
+ expect(fireEvent.keyDown(last, {key: 'Tab'})).toBe(false);
+ expect(first).toHaveFocus();
+
+ expect(fireEvent.keyDown(first, {key: 'Tab', shiftKey: true})).toBe(false);
+ expect(last).toHaveFocus();
+}
+
+describe('Lightbox focus region (Dialog DEC-2)', () => {
+ it('wraps Tab and Shift+Tab inside the open viewer', () => {
+ render(
+ <Lightbox
+ isOpen
+ onOpenChange={() => {}}
+ media={[
+ {src: '/one.jpg', alt: 'One'},
+ {src: '/two.jpg', alt: 'Two'},
+ ]}
+ />,
+ );
+ expectTabWrapsInside(document.querySelector('dialog') as HTMLElement);
+ });
+});
diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx
index 3a8a39ec31..a7df25271a 100644
--- a/packages/core/src/Lightbox/Lightbox.tsx
+++ b/packages/core/src/Lightbox/Lightbox.tsx
@@ -46,6 +46,7 @@ import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {overlayPaddingReset} from '../Layout/overlayPaddingReset.stylex';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
+import {useFocusRegionContainment} from '../hooks/useFocusTrap';
import {useMergedRefs} from '../hooks/useMergedRefs';
import {isRtlElement} from '../hooks/isRtlElement';
@@ -341,6 +342,9 @@ export function Lightbox({
const t = useComponentTranslator();
const dialogRef = useRef<HTMLDialogElement>(null);
const mergedDialogRef = useMergedRefs(ref, dialogRef);
+ // Native showModal() lets Tab leave for the browser's own UI, so the shared
+ // module wraps it.
+ useFocusRegionContainment(dialogRef, isOpen);
const containerRef = useRef<HTMLDivElement>(null);
const imageWrapperRef = useRef<HTMLDivElement>(null);
const triggerElementRef = useRef<Element | null>(null);
diff --git a/packages/core/src/Lightbox/LightboxKeyboard.a11y.browser.spec.ts b/packages/core/src/Lightbox/LightboxKeyboard.a11y.browser.spec.ts
index 086db40364..d179b26e6f 100644
--- a/packages/core/src/Lightbox/LightboxKeyboard.a11y.browser.spec.ts
+++ b/packages/core/src/Lightbox/LightboxKeyboard.a11y.browser.spec.ts
@@ -6,7 +6,8 @@
* @input Built Lightbox stories (LTR and the RTL story global) and real
* Chromium/WebKit keyboard input
* @output Browser evidence that the gallery's Left/Right arrow keys move in
- * the direction of the matching on-screen button, in both directions
+ * the direction of the matching on-screen button, in both directions, and
+ * that Tab and Shift+Tab wrap inside the open viewer at both ends
* @position Cross-browser proof for Lightbox's direction-aware gallery keys
* (design:bidirectionality DR6, DR11)
*/
@@ -76,3 +77,63 @@ for (const direction of ['ltr', 'rtl'] as const) {
await expect(dialog).toContainText('1 / 4');
});
}
+
+// Focuses the viewer's last tabbable control, presses Tab, and expects the
+// first; then the reverse with Shift+Tab. Focus must never reach the page or
+// the browser's own UI.
+async function expectTabWrapsInside(page: Page) {
+ const ends = async () =>
+ page.evaluate(() => {
+ const dialog = document.querySelector('dialog[open]');
+ if (dialog == null) {
+ return null;
+ }
+ const tabbable = [
+ ...dialog.querySelectorAll<HTMLElement>(
+ 'button, [href], input, select, textarea, [tabindex]',
+ ),
+ ].filter(
+ el =>
+ el.tabIndex >= 0 &&
+ !el.hasAttribute('disabled') &&
+ el.getClientRects().length > 0,
+ );
+ tabbable.forEach((el, i) => el.setAttribute('data-tab-index', String(i)));
+ return tabbable.length;
+ });
+ const count = await ends();
+ expect(count).toBeGreaterThan(0);
+ const at = (i: number) =>
+ page.locator(`dialog[open] [data-tab-index="${i}"]`);
+ const last = (count ?? 1) - 1;
+
+ await at(last).focus();
+ await page.keyboard.press('Tab');
+ await expect(at(0)).toBeFocused();
+
+ await at(0).focus();
+ await page.keyboard.press('Shift+Tab');
+ await expect(at(last)).toBeFocused();
+}
+
+test('Tab and Shift+Tab wrap inside an open gallery', async ({page}) => {
+ await openGallery(page, 'ltr');
+ await expectTabWrapsInside(page);
+});
+
+test('Tab and Shift+Tab wrap inside an open single image, zoomed or not', async ({
+ page,
+}) => {
+ await page.route(/picsum\.photos/, async route => route.abort());
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-lightbox--with-zoom&viewMode=story`,
+ );
+ await page.getByRole('button', {name: 'Open with zoom'}).click();
+ await expect(page.getByRole('dialog')).toBeVisible();
+ await expectTabWrapsInside(page);
+
+ // Zoomed in, the same controls stay the only stops.
+ await page.locator('dialog[open] [tabindex="0"]').first().focus();
+ await page.keyboard.press('+');
+ await expectTabWrapsInside(page);
+});
diff --git a/packages/core/src/hooks/useFocusTrap.test.tsx b/packages/core/src/hooks/useFocusTrap.test.tsx
index aa5622e051..9814ac842d 100644
--- a/packages/core/src/hooks/useFocusTrap.test.tsx
+++ b/packages/core/src/hooks/useFocusTrap.test.tsx
@@ -40,6 +40,32 @@ function Trap({children}: {children: React.ReactNode}) {
);
}
+function InnerRegion() {
+ const {containerRef} = useFocusTrap<HTMLDivElement>({isActive: true});
+ return (
+ <div ref={containerRef} data-testid="inner-region">
+ <button type="button" data-testid="inner-first">
+ Inner first
+ </button>
+ <button type="button" data-testid="inner-last">
+ Inner last
+ </button>
+ </div>
+ );
+}
+
+function OuterRegion({showInner}: {showInner: boolean}) {
+ const {containerRef} = useFocusTrap<HTMLDivElement>({isActive: true});
+ return (
+ <div ref={containerRef} data-testid="outer-region">
+ <button type="button" data-testid="outer-first">
+ Outer first
+ </button>
+ {showInner && <InnerRegion />}
+ </div>
+ );
+}
+
function EscapeTrap({
isActive,
onEscape,
@@ -296,6 +322,95 @@ describe('useFocusTrap tabbable model (infra-8)', () => {
expect(screen.getByTestId('first')).toHaveFocus();
});
+ it('leaves controls inside a closed dialog out of the Tab cycle', () => {
+ render(
+ <Trap>
+ <button type="button" data-testid="first">
+ First
+ </button>
+ <button type="button" data-testid="last">
+ Last
+ </button>
+ <dialog>
+ <button type="button" data-testid="hidden">
+ In a closed sheet
+ </button>
+ </dialog>
+ </Trap>,
+ );
+ const last = screen.getByTestId('last');
+ last.focus();
+
+ expect(fireEvent.keyDown(last, {key: 'Tab'})).toBe(false);
+ expect(screen.getByTestId('first')).toHaveFocus();
+ });
+
+ it('keeps controls inside a popover-open dialog in the Tab cycle', () => {
+ // A Popover opened inside a non-modal sheet: the sheet's <dialog> is shown
+ // with showPopover(), which never sets `open`.
+ render(
+ <dialog data-testid="sheet">
+ <Trap>
+ <button type="button" data-testid="first">
+ First
+ </button>
+ <button type="button" data-testid="second">
+ Second
+ </button>
+ </Trap>
+ </dialog>,
+ );
+ const sheet = screen.getByTestId('sheet');
+ const matches = vi
+ .spyOn(sheet, 'matches')
+ .mockImplementation((selector: string) => selector === ':popover-open');
+ const first = screen.getByTestId('first');
+ first.focus();
+
+ // First is not the last Tab stop, so the trap leaves the press to the
+ // browser instead of cancelling it for want of tabbable controls.
+ expect(fireEvent.keyDown(first, {key: 'Tab'})).toBe(true);
+ const second = screen.getByTestId('second');
+ second.focus();
+ expect(fireEvent.keyDown(second, {key: 'Tab'})).toBe(false);
+ expect(first).toHaveFocus();
+ matches.mockRestore();
+ });
+
+ it('lets the innermost region answer Tab when regions nest at the end', () => {
+ // A region (a Popover, say) opened at the end of an active region (an open
+ // Dialog): its last control is also the outer region's last Tab stop.
+ const {rerender} = render(<OuterRegion showInner={false} />);
+ rerender(<OuterRegion showInner />);
+ const innerLast = screen.getByTestId('inner-last');
+ innerLast.focus();
+
+ expect(fireEvent.keyDown(innerLast, {key: 'Tab'})).toBe(false);
+ expect(screen.getByTestId('inner-first')).toHaveFocus();
+ });
+
+ it('leaves Tab to an open dialog nested inside the trap', () => {
+ render(
+ <Trap>
+ <button type="button" data-testid="outer">
+ Outer
+ </button>
+ <dialog open>
+ <button type="button" data-testid="inner-last">
+ Continue
+ </button>
+ </dialog>
+ </Trap>,
+ );
+ const innerLast = screen.getByTestId('inner-last');
+ innerLast.focus();
+
+ // The nested dialog is its own focus context; the outer region does not
+ // cancel the press or pull focus to its own first control.
+ expect(fireEvent.keyDown(innerLast, {key: 'Tab'})).toBe(true);
+ expect(innerLast).toHaveFocus();
+ });
+
it('pulls focus back in when a Tab from inside leaves the trap', () => {
render(
<Trap>
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index 25402f01e0..4892e4d478 100644
--- a/packages/core/src/hooks/useFocusTrap.ts
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -5,7 +5,8 @@
/**
* @file useFocusTrap.ts
* @input Uses React useCallback, useEffect, useRef
- * @output Exports useFocusTrap, the deprecated Escape-state shim, and an
+ * @output Exports useFocusTrap, the internal focus-region Tab containment it
+ * composes, the deprecated Escape-state shim, and an
* internal compatibility-signal hook
* @position Core hook; used by dialogs, modals, date pickers
*
@@ -63,6 +64,19 @@ export function useFocusTrapEscapeCompatibilitySignal(isActive: boolean): void {
}, [isActive]);
}
+/**
+ * Whether an element is shown as a popover. jsdom and browsers without the
+ * Popover API do not recognize `:popover-open`, and nothing is popover-open
+ * there.
+ */
+function isPopoverOpen(el: Element): boolean {
+ try {
+ return el.matches(':popover-open');
+ } catch {
+ return false;
+ }
+}
+
/**
* Whether an element is currently perceivable/focusable — excludes ones hidden
* via `display:none`/`visibility:hidden` or inside an `inert`/`hidden` subtree,
@@ -77,6 +91,18 @@ function isVisiblyFocusable(el: HTMLElement): boolean {
if (el.hidden || el.closest('[hidden]')) {
return false;
}
+ // A closed <dialog> renders nothing, so nothing inside it can take focus.
+ // A dialog shown with showPopover() (a non-modal sheet or drawer) never
+ // sets `open`, so it counts as shown while it is popover-open.
+ for (
+ let dialog = el.closest('dialog');
+ dialog != null;
+ dialog = dialog.parentElement?.closest('dialog') ?? null
+ ) {
+ if (!dialog.open && !isPopoverOpen(dialog)) {
+ return false;
+ }
+ }
// closest() matches the element itself as well as any ancestor.
if (el.closest('[aria-hidden="true"]')) {
return false;
@@ -125,6 +151,15 @@ function isHTMLElement(node: Node | null): node is HTMLElement {
return view != null && node instanceof view.HTMLElement;
}
+/**
+ * Whether node `a` comes before node `b` in document order.
+ */
+function precedes(a: Node, b: Node): boolean {
+ return (
+ (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0
+ );
+}
+
/**
* Attempt to focus an element. Returns true if focus was successful.
*/
@@ -137,6 +172,18 @@ function attemptFocus(element: HTMLElement): boolean {
return element.ownerDocument.activeElement === element;
}
+/**
+ * Wrap focus to `target` for a Tab press, and cancel the press only when the
+ * target took focus. A target the browser refuses (inert behind a modal
+ * layered over this region) leaves the press to the browser instead of
+ * stranding focus where it was.
+ */
+function wrapFocus(event: KeyboardEvent, target: HTMLElement): void {
+ if (attemptFocus(target)) {
+ event.preventDefault();
+ }
+}
+
/**
* Focus the first focusable descendant of a container.
* Returns true if a focusable element was found and focused.
@@ -165,6 +212,223 @@ function focusLastDescendant(container: HTMLElement): boolean {
return false;
}
+// Containers of the focus regions currently active, in every document. A Tab
+// is answered by the innermost region that holds focus, so regions that nest
+// in the DOM never fight over one key press.
+const activeRegionContainers = new Set<HTMLElement>();
+
+function hasInnerRegionHolding(
+ container: HTMLElement,
+ active: Element,
+): boolean {
+ // An open <dialog> nested in the region that holds focus is its own focus
+ // context (a modal step over a covered sheet): it answers Tab, not us.
+ const dialog = active.closest('dialog[open]');
+ if (dialog != null && dialog !== container && container.contains(dialog)) {
+ return true;
+ }
+ for (const other of activeRegionContainers) {
+ if (
+ other !== container &&
+ container.contains(other) &&
+ other.contains(active)
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Tab containment for a focus region: Tab and Shift+Tab pressed inside wrap at
+ * either end, and a Tab that starts outside is left to the page. When regions
+ * nest, the innermost one holding focus answers.
+ *
+ * `useFocusTrap` composes this. Dialog, BottomSheet and Lightbox call it
+ * directly, because their native lifecycle already owns focus entry and
+ * return. Internal: not re-exported from `hooks`.
+ */
+export function useFocusRegionContainment(
+ containerRef: React.RefObject<HTMLElement | null>,
+ isActive: boolean,
+): void {
+ const lastFocusRef = useRef<Element | null>(null);
+ // Track if focus change was triggered by keyboard (Tab key)
+ const isKeyboardNavigationRef = useRef(false);
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!isActive || container == null) {
+ return;
+ }
+ activeRegionContainers.add(container);
+ return () => {
+ activeRegionContainers.delete(container);
+ };
+ }, [containerRef, isActive]);
+
+ /**
+ * Handle focus events - redirect focus back into container if it escapes.
+ * Only redirects for keyboard navigation, not mouse clicks.
+ */
+ useEffect(() => {
+ if (!isActive) {
+ return;
+ }
+
+ const doc = trapDocument(containerRef.current);
+
+ const handleFocus = (event: FocusEvent) => {
+ const container = containerRef.current;
+ if (!container) {
+ return;
+ }
+
+ const target = event.target as Node;
+
+ if (container.contains(target)) {
+ // Focus is inside the container - track it
+ lastFocusRef.current = target as Element;
+ } else if (isKeyboardNavigationRef.current) {
+ // Focus escaped via keyboard - redirect it back
+ const focusedFirst = focusFirstDescendant(container);
+
+ // If we're back at the same element (Shift+Tab from first element),
+ // try focusing the last element instead
+ if (focusedFirst && lastFocusRef.current === doc.activeElement) {
+ focusLastDescendant(container);
+ } else if (
+ !focusedFirst &&
+ isHTMLElement(lastFocusRef.current) &&
+ container.contains(lastFocusRef.current)
+ ) {
+ // A modal surface may intentionally have no tabbable controls and
+ // place initial focus on a tabIndex={-1} heading or panel. Preserve
+ // that programmatic focus target instead of letting Tab escape.
+ attemptFocus(lastFocusRef.current);
+ }
+
+ lastFocusRef.current = doc.activeElement;
+ }
+ // If focus escaped via mouse click, don't redirect - let light dismiss handle it
+
+ // Reset keyboard navigation flag
+ isKeyboardNavigationRef.current = false;
+ };
+
+ // Use capture phase to intercept focus before it settles
+ doc.addEventListener('focus', handleFocus, true);
+
+ return () => {
+ doc.removeEventListener('focus', handleFocus, true);
+ };
+ }, [containerRef, isActive]);
+
+ /**
+ * Handle Tab key to wrap focus at boundaries. Also tracks that keyboard
+ * navigation is occurring.
+ *
+ * No Escape here, and no IME guard: the shared layer dismissal stack owns
+ * that press, and each surface that applies a region decides its own
+ * dismissal (`useFocusTrap` through its `onEscape`).
+ */
+ useEffect(() => {
+ if (!isActive) {
+ return;
+ }
+
+ const doc = trapDocument(containerRef.current);
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ const container = containerRef.current;
+ if (!container) {
+ return;
+ }
+
+ if (event.key === 'Tab') {
+ if (event.defaultPrevented) {
+ // A control that handles Tab itself (an editor that indents) keeps
+ // focus where it is.
+ return;
+ }
+ const active = doc.activeElement;
+ // Any focused node counts, not only HTML elements: an SVG control
+ // inside the container is still inside.
+ if (active == null || !container.contains(active)) {
+ // The trap contains focus that is inside it; it does not pull in a
+ // Tab pressed elsewhere on the page. A layer can be open while focus
+ // legitimately sits outside it — a listbox popup anchored to its own
+ // input, a non-modal popover beside the content it annotates — and
+ // capturing that Tab would take the rest of the page away from
+ // keyboard users.
+ return;
+ }
+
+ if (hasInnerRegionHolding(container, active)) {
+ // A region nested in this one (a Dialog opened from a Dialog, a
+ // Popover inside a Drawer) holds focus; that region answers Tab.
+ return;
+ }
+
+ // Mark that keyboard navigation is leaving from inside the trap, so a
+ // focus that lands outside is redirected back in.
+ isKeyboardNavigationRef.current = true;
+
+ const focusable = getFocusableElements(container);
+ if (focusable.length === 0) {
+ // There is nowhere to advance to. Keep focus on the current
+ // programmatic target (for example a dialog panel with tabIndex=-1)
+ // rather than allowing the browser to move into background content.
+ event.preventDefault();
+ lastFocusRef.current = active;
+ isKeyboardNavigationRef.current = false;
+ return;
+ }
+
+ const first = focusable[0];
+ const last = focusable[focusable.length - 1];
+
+ if (doc.activeElement === container) {
+ // Programmatic initial focus can sit on the trap container itself
+ // (for example a dialog panel with no content controls). Move into
+ // the tabbable cycle instead of letting Tab escape to the page.
+ wrapFocus(event, event.shiftKey ? last : first);
+ return;
+ }
+
+ // Programmatic focus can also sit on an element that is not a Tab stop
+ // (a dialog title with tabIndex -1). Its place in document order
+ // decides the edge: nothing tabbable before it means Shift+Tab is
+ // leaving the region, nothing after it means Tab is.
+ const isProgrammaticStop = !(focusable as Element[]).includes(active);
+ if (event.shiftKey) {
+ // Shift+Tab: if on (or before) the first element, wrap to last
+ if (
+ active === first ||
+ (isProgrammaticStop && precedes(active, first))
+ ) {
+ wrapFocus(event, last);
+ }
+ } else {
+ // Tab: if on (or after) the last element, wrap to first
+ if (
+ active === last ||
+ (isProgrammaticStop && precedes(last, active))
+ ) {
+ wrapFocus(event, first);
+ }
+ }
+ }
+ };
+
+ doc.addEventListener('keydown', handleKeyDown);
+
+ return () => {
+ doc.removeEventListener('keydown', handleKeyDown);
+ };
+ }, [containerRef, isActive]);
+}
+
/**
* Configuration for focus trap behavior
*/
@@ -255,9 +519,9 @@ export function useFocusTrapInternal<T extends HTMLElement = HTMLElement>(
getRestoreTargetRef.current = getRestoreTarget;
const containerRef = useRef<T | null>(null);
- const lastFocusRef = useRef<Element | null>(null);
- // Track if focus change was triggered by keyboard (Tab key)
- const isKeyboardNavigationRef = useRef(false);
+
+ // Tab and Shift+Tab wrap inside the container while the trap is active.
+ useFocusRegionContainment(containerRef, isActive);
// Join the shared layer dismissal stack. The trap no longer listens for
// Escape itself: the stack owns one listener and routes each press to the
@@ -365,153 +629,6 @@ export function useFocusTrapInternal<T extends HTMLElement = HTMLElement>(
};
}, [isActive]);
- /**
- * Handle focus events - redirect focus back into container if it escapes.
- * Only redirects for keyboard navigation, not mouse clicks.
- */
- useEffect(() => {
- if (!isActive) {
- return;
- }
-
- const doc = trapDocument(containerRef.current);
-
- const handleFocus = (event: FocusEvent) => {
- const container = containerRef.current;
- if (!container) {
- return;
- }
-
- const target = event.target as Node;
-
- if (container.contains(target)) {
- // Focus is inside the container - track it
- lastFocusRef.current = target as Element;
- } else if (isKeyboardNavigationRef.current) {
- // Focus escaped via keyboard - redirect it back
- const focusedFirst = focusFirstDescendant(container);
-
- // If we're back at the same element (Shift+Tab from first element),
- // try focusing the last element instead
- if (focusedFirst && lastFocusRef.current === doc.activeElement) {
- focusLastDescendant(container);
- } else if (
- !focusedFirst &&
- isHTMLElement(lastFocusRef.current) &&
- container.contains(lastFocusRef.current)
- ) {
- // A modal surface may intentionally have no tabbable controls and
- // place initial focus on a tabIndex={-1} heading or panel. Preserve
- // that programmatic focus target instead of letting Tab escape.
- attemptFocus(lastFocusRef.current);
- }
-
- lastFocusRef.current = doc.activeElement;
- }
- // If focus escaped via mouse click, don't redirect - let light dismiss handle it
-
- // Reset keyboard navigation flag
- isKeyboardNavigationRef.current = false;
- };
-
- // Use capture phase to intercept focus before it settles
- doc.addEventListener('focus', handleFocus, true);
-
- return () => {
- doc.removeEventListener('focus', handleFocus, true);
- };
- }, [isActive]);
-
- /**
- * Handle Tab key to wrap focus at boundaries. Also tracks that keyboard
- * navigation is occurring.
- *
- * No Escape here, and no IME guard: the shared stack owns the press, claims
- * a composing Escape so no close request follows, and dismisses the trap
- * through `onEscape` above. The trap renders no element of its own, so it
- * has no `cancel` to answer either.
- */
- useEffect(() => {
- if (!isActive) {
- return;
- }
-
- const doc = trapDocument(containerRef.current);
-
- const handleKeyDown = (event: KeyboardEvent) => {
- const container = containerRef.current;
- if (!container) {
- return;
- }
-
- if (event.key === 'Tab') {
- const active = doc.activeElement;
- // Any focused node counts, not only HTML elements: an SVG control
- // inside the container is still inside.
- if (active == null || !container.contains(active)) {
- // The trap contains focus that is inside it; it does not pull in a
- // Tab pressed elsewhere on the page. A layer can be open while focus
- // legitimately sits outside it — a listbox popup anchored to its own
- // input, a non-modal popover beside the content it annotates — and
- // capturing that Tab would take the rest of the page away from
- // keyboard users.
- return;
- }
-
- // Mark that keyboard navigation is leaving from inside the trap, so a
- // focus that lands outside is redirected back in.
- isKeyboardNavigationRef.current = true;
-
- const focusable = getFocusableElements(container);
- if (focusable.length === 0) {
- // There is nowhere to advance to. Keep focus on the current
- // programmatic target (for example a dialog panel with tabIndex=-1)
- // rather than allowing the browser to move into background content.
- event.preventDefault();
- lastFocusRef.current = active;
- isKeyboardNavigationRef.current = false;
- return;
- }
-
- const first = focusable[0];
- const last = focusable[focusable.length - 1];
-
- if (doc.activeElement === container) {
- // Programmatic initial focus can sit on the trap container itself
- // (for example a dialog panel with no content controls). Move into
- // the tabbable cycle instead of letting Tab escape to the page.
- event.preventDefault();
- if (event.shiftKey) {
- last.focus();
- } else {
- first.focus();
- }
- return;
- }
-
- if (event.shiftKey) {
- // Shift+Tab: if on first element, wrap to last
- if (doc.activeElement === first) {
- event.preventDefault();
- last.focus();
- }
- } else {
- // Tab: if on last element, wrap to first
- if (doc.activeElement === last) {
- event.preventDefault();
- first.focus();
- }
- }
- }
- };
-
- doc.addEventListener('keydown', handleKeyDown);
-
- return () => {
- doc.removeEventListener('keydown', handleKeyDown);
- };
- }, [isActive, onEscape]);
-
return {
containerRef,
focusFirst,