Skip to content

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

TypeScript

fix(core): restore focus when a focus trap deactivates (#3732)

Baraa Hamodi9da3f6215d7d
diff --git a/.changeset/focustrap-restore-focus.md b/.changeset/focustrap-restore-focus.md
new file mode 100644
index 0000000000..353bd340d4
--- /dev/null
+++ b/.changeset/focustrap-restore-focus.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] useFocusTrap: focus now returns to the previously-focused element when a trap deactivates, so closing a Popover (Escape or light-dismiss) no longer drops keyboard focus to the page body. Components that already restore focus themselves are unaffected — the trap only restores when focus would otherwise be lost. (#3732)
+@bhamodi
diff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsx
index 3fd0837745..7713741a42 100644
--- a/packages/core/src/Popover/Popover.test.tsx
+++ b/packages/core/src/Popover/Popover.test.tsx
@@ -354,4 +354,69 @@ describe('Popover', () => {
expect(trigger).toHaveAttribute('aria-expanded', 'true');
});
});
+
+ describe('focus restoration', () => {
+ it('returns focus to the trigger when closed via Escape', () => {
+ render(
+ <Popover
+ content={
+ <button type="button" data-testid="inside-content">
+ Inside
+ </button>
+ }
+ label="Test">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ trigger.focus();
+ expect(trigger).toHaveFocus();
+
+ fireEvent.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // Move focus into the open popover, as a keyboard user would.
+ const inside = screen.getByTestId('inside-content');
+ inside.focus();
+ expect(inside).toHaveFocus();
+
+ fireEvent.keyDown(document, {key: 'Escape'});
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger).toHaveFocus();
+ });
+
+ it('returns focus to the trigger on light dismiss', () => {
+ render(
+ <Popover
+ content={
+ <button type="button" data-testid="inside-content">
+ Inside
+ </button>
+ }
+ label="Test">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ trigger.focus();
+
+ fireEvent.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ const inside = screen.getByTestId('inside-content');
+ inside.focus();
+ expect(inside).toHaveFocus();
+
+ // Simulate the browser's light dismiss for popover="auto": clicking
+ // outside fires a `toggle` event with newState "closed".
+ const popoverEl = document.querySelector('[popover]');
+ expect(popoverEl).not.toBeNull();
+ const toggleEvent = new Event('toggle');
+ Object.defineProperty(toggleEvent, 'newState', {value: 'closed'});
+ fireEvent(popoverEl as HTMLElement, toggleEvent);
+
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger).toHaveFocus();
+ });
+ });
});
diff --git a/packages/core/src/hooks/useFocusTrap.doc.mjs b/packages/core/src/hooks/useFocusTrap.doc.mjs
index bb3671af68..d504111afd 100644
--- a/packages/core/src/hooks/useFocusTrap.doc.mjs
+++ b/packages/core/src/hooks/useFocusTrap.doc.mjs
@@ -39,10 +39,11 @@ export const docs = {
],
usage: {
description:
- 'Traps focus within a container element following the WAI-ARIA dialog focus trap pattern. Listens to focus events on the document and redirects focus back into the container if it escapes via keyboard navigation. Handles both Tab and Shift+Tab wrapping. Mouse clicks outside the container are not intercepted; use a light-dismiss handler for that.',
+ 'Traps focus within a container element following the WAI-ARIA dialog focus trap pattern. Listens to focus events on the document and redirects focus back into the container if it escapes via keyboard navigation. Handles both Tab and Shift+Tab wrapping. When the trap deactivates or unmounts, focus is restored to the element that was focused before activation, unless focus was already moved elsewhere. Mouse clicks outside the container are not intercepted; use a light-dismiss handler for that.',
bestPractices: [
{ guidance: true, description: 'Call focusFirst() when opening a dialog/modal to move focus into the trapped region.' },
{ guidance: true, description: 'Provide an onEscape callback to close the dialog when Escape is pressed.' },
+ { guidance: true, description: 'Rely on the built-in focus restoration on close; only add your own onHide focus handling when you need to send focus somewhere other than the previously-focused element.' },
{ guidance: false, description: 'Use on non-modal content like tooltips or dropdowns; those need light-dismiss, not focus trapping.' },
],
},
@@ -67,10 +68,11 @@ export const docsDense = {
},
usage: {
description:
- 'Traps focus within container element following WAI-ARIA dialog focus trap pattern. Listens to document focus events + redirects focus back into container if it escapes via keyboard navigation. Handles both Tab + Shift+Tab wrapping. Mouse clicks outside container not intercepted; use light-dismiss handler for that.',
+ 'Traps focus within container element following WAI-ARIA dialog focus trap pattern. Listens to document focus events + redirects focus back into container if it escapes via keyboard navigation. Handles both Tab + Shift+Tab wrapping. On deactivate/unmount, restores focus to the element focused before activation unless focus already moved elsewhere. Mouse clicks outside container not intercepted; use light-dismiss handler for that.',
bestPractices: [
{ guidance: true, description: 'Call focusFirst() when opening dialog/modal to move focus into trapped region.' },
{ guidance: true, description: 'Provide onEscape callback to close dialog when Escape pressed.' },
+ { guidance: true, description: 'Rely on built-in focus restoration on close; add own onHide focus handling only to send focus somewhere other than previously-focused element.' },
{ guidance: false, description: 'Use on non-modal content like tooltips / dropdowns; those need light-dismiss, not focus trapping.' },
],
},
diff --git a/packages/core/src/hooks/useFocusTrap.test.tsx b/packages/core/src/hooks/useFocusTrap.test.tsx
index bb64bf0184..e5a9e0ffe6 100644
--- a/packages/core/src/hooks/useFocusTrap.test.tsx
+++ b/packages/core/src/hooks/useFocusTrap.test.tsx
@@ -50,6 +50,41 @@ function EscapeTrap({
);
}
+function RestoreTrap({isActive}: {isActive: boolean}) {
+ const {containerRef} = useFocusTrap<HTMLDivElement>({isActive});
+ return (
+ <div ref={containerRef} data-testid="restore-trap">
+ <button type="button" data-testid="inside">
+ Inside trap
+ </button>
+ </div>
+ );
+}
+
+function RestoreFixture({
+ isActive,
+ showPrev = true,
+ showTrap = true,
+}: {
+ isActive: boolean;
+ showPrev?: boolean;
+ showTrap?: boolean;
+}) {
+ return (
+ <div>
+ {showPrev && (
+ <button type="button" data-testid="prev">
+ Previously focused
+ </button>
+ )}
+ <button type="button" data-testid="other">
+ Other outside
+ </button>
+ {showTrap && <RestoreTrap isActive={isActive} />}
+ </div>
+ );
+}
+
describe('useFocusTrap tabbable model (infra-8)', () => {
it('treats a contenteditable as focusable (focusFirst lands on it)', () => {
render(
@@ -175,3 +210,71 @@ describe('useFocusTrap Escape coordination', () => {
expect(onEscape).not.toHaveBeenCalled();
});
});
+
+describe('useFocusTrap focus restoration', () => {
+ it('restores focus to the previously-focused element when deactivated', () => {
+ const {rerender} = render(<RestoreFixture isActive={false} />);
+ const prev = screen.getByTestId('prev');
+ prev.focus();
+ expect(prev).toHaveFocus();
+
+ // Activate the trap (captures `prev` as the restore target) and move focus
+ // inside it, as auto-focus or a keyboard user would.
+ rerender(<RestoreFixture isActive={true} />);
+ screen.getByTestId('inside').focus();
+ expect(screen.getByTestId('inside')).toHaveFocus();
+
+ // Deactivating returns focus to where it was before the trap opened.
+ rerender(<RestoreFixture isActive={false} />);
+ expect(prev).toHaveFocus();
+ });
+
+ it('does not steal focus when it was moved elsewhere outside the trap', () => {
+ const {rerender} = render(<RestoreFixture isActive={false} />);
+ const prev = screen.getByTestId('prev');
+ prev.focus();
+
+ rerender(<RestoreFixture isActive={true} />);
+ // The user (or a consumer that self-restores) moves focus to a different
+ // outside control while the trap is open.
+ const other = screen.getByTestId('other');
+ other.focus();
+
+ rerender(<RestoreFixture isActive={false} />);
+ // Focus is left where the user put it — not yanked back to `prev`.
+ expect(other).toHaveFocus();
+ expect(prev).not.toHaveFocus();
+ });
+
+ it('does not crash or restore when the captured element was removed', () => {
+ const {rerender} = render(<RestoreFixture isActive={false} />);
+ const prev = screen.getByTestId('prev');
+ prev.focus();
+
+ rerender(<RestoreFixture isActive={true} />);
+ screen.getByTestId('inside').focus();
+
+ // Remove the captured element from the DOM before the trap deactivates.
+ rerender(<RestoreFixture isActive={true} showPrev={false} />);
+ expect(() =>
+ rerender(<RestoreFixture isActive={false} showPrev={false} />),
+ ).not.toThrow();
+ });
+
+ it('restores focus when the trap unmounts while active', () => {
+ const {rerender} = render(
+ <RestoreFixture isActive={true} showTrap={false} />,
+ );
+ const prev = screen.getByTestId('prev');
+ prev.focus();
+
+ // Mounting the trap active captures `prev`; then focus moves inside it.
+ rerender(<RestoreFixture isActive={true} showTrap={true} />);
+ screen.getByTestId('inside').focus();
+ expect(screen.getByTestId('inside')).toHaveFocus();
+
+ // Unmounting the trap (cleanup path, not an isActive flip) still restores.
+ rerender(<RestoreFixture isActive={true} showTrap={false} />);
+ expect(prev).toHaveFocus();
+ });
+});
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index 13c91d7af3..417230c4c4 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 hook for trapping focus within a container
+ * @output Exports useFocusTrap hook for trapping focus within a container and
+ * restoring focus to the previously-focused element on deactivation
* @position Core hook; used by dialogs, modals, date pickers
*
* Based on WAI-ARIA dialog pattern:
@@ -178,6 +179,9 @@ export interface UseFocusTrapReturn<T extends HTMLElement = HTMLElement> {
* - Listens to focus events on the document
* - Redirects focus back into the container if it escapes
* - Handles both Tab and Shift+Tab navigation
+ * - Restores focus to the element that was focused before activation when the
+ * trap deactivates or unmounts, unless focus was already moved elsewhere
+ * (so consumers that restore focus themselves are unaffected)
*
* @example
* ```
@@ -217,6 +221,51 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
}
}, []);
+ /**
+ * Capture the element focused before the trap activated, and restore focus to
+ * it when the trap deactivates (or the component unmounts). Overlays are
+ * opened imperatively (e.g. `showPopover()`), so the browser's declarative
+ * popover focus restoration does not apply — without this, closing a Popover
+ * via Escape or light dismiss drops keyboard focus to `<body>`.
+ *
+ * The restore is guarded so it never steals focus a consumer moved on
+ * purpose: it only runs when focus would otherwise be lost — i.e. the active
+ * element is nothing, the document body/root, or still inside the (possibly
+ * now-unmounted) trap container. If focus already moved to some other element
+ * outside the trap (the user clicked elsewhere, or a consumer such as
+ * DropdownMenu already refocused its trigger), the restore is a no-op.
+ */
+ useEffect(() => {
+ if (!isActive) {
+ return;
+ }
+
+ const previouslyFocused = document.activeElement as HTMLElement | null;
+ // Snapshot the container now; by cleanup it may be detached or unmounted.
+ const container = containerRef.current;
+
+ return () => {
+ const active = document.activeElement;
+ const focusWasLost =
+ active == null ||
+ active === document.body ||
+ active === document.documentElement ||
+ (container != null && container.contains(active));
+
+ if (!focusWasLost) {
+ return;
+ }
+
+ if (
+ previouslyFocused != null &&
+ previouslyFocused.isConnected &&
+ typeof previouslyFocused.focus === 'function'
+ ) {
+ previouslyFocused.focus();
+ }
+ };
+ }, [isActive]);
+
/**
* Handle focus events - redirect focus back into container if it escapes.
* Only redirects for keyboard navigation, not mouse clicks.