Skip to content

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

TypeScript

fix(useFocusTrap): only restore focus when focus actually entered the trap (#5681)

Trakshan Mishra684aaeaf5e99
diff --git a/.changeset/focus-trap-restore-only-when-focus-entered.md b/.changeset/focus-trap-restore-only-when-focus-entered.md
new file mode 100644
index 0000000000..d3720a5388
--- /dev/null
+++ b/.changeset/focus-trap-restore-only-when-focus-entered.md
@@ -0,0 +1,21 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] useFocusTrap only restores focus when focus actually entered the trap while it was active. (#5651)
+
+`useFocusTrap` captured `document.activeElement` on activation and restored
+focus to it on deactivation whenever focus would otherwise be lost to `<body>`.
+For popups that deliberately keep DOM focus on their trigger — a Typeahead or
+PowerSearch listbox opened with `role: "none"` and `hasAutoFocus: false` — the
+trap never receives focus, so the restore fired on outside-click dismissal and
+re-focused the anchor input. Because the input was then already focused,
+clicking it again fired no `focus` event and `hasEntriesOnFocus` could not
+reopen the menu — the control was stuck until a second outside click.
+
+The restore effect now tracks whether focus entered the trap container at any
+point while it was active (via a `focusin` listener). If focus never entered,
+the restore is skipped entirely. Popups that do take focus — Dialog,
+DropdownMenu, a Typeahead option click — are unaffected.
+
+@trakshan-mishra
diff --git a/packages/core/src/hooks/useFocusTrap.doc.mjs b/packages/core/src/hooks/useFocusTrap.doc.mjs
index a459902462..c171432e98 100644
--- a/packages/core/src/hooks/useFocusTrap.doc.mjs
+++ b/packages/core/src/hooks/useFocusTrap.doc.mjs
@@ -39,7 +39,7 @@ 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. 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.',
+ '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 or never entered the trap (so popups that keep focus on their trigger, like comboboxes, are unaffected). 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.' },
@@ -68,7 +68,7 @@ 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. 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.',
+ '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 or never entered the trap. 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.' },
diff --git a/packages/core/src/hooks/useFocusTrap.test.tsx b/packages/core/src/hooks/useFocusTrap.test.tsx
index b8a652a309..bfa643aa14 100644
--- a/packages/core/src/hooks/useFocusTrap.test.tsx
+++ b/packages/core/src/hooks/useFocusTrap.test.tsx
@@ -451,4 +451,52 @@ describe('useFocusTrap focus restoration', () => {
rerender(<RestoreFixture isActive={true} showTrap={false} />);
expect(prev).toHaveFocus();
});
+
+ it('does not restore focus when focus never entered the trap', () => {
+ // Reproduces the Typeahead/PowerSearch scenario from #5651: a popup that
+ // opens with role="none" and hasAutoFocus={false} keeps DOM focus on its
+ // anchor input. The trap is active but focus never enters the container.
+ const {rerender} = render(<RestoreFixture isActive={false} />);
+ const prev = screen.getByTestId('prev');
+ prev.focus();
+ expect(prev).toHaveFocus();
+
+ // Activate the trap — focus stays on prev (outside the container).
+ rerender(<RestoreFixture isActive={true} />);
+
+ // Simulate an outside click: the browser blurs the input and focus falls
+ // to <body> before the layer's light dismiss hides it.
+ (document.activeElement as HTMLElement).blur();
+ expect(document.body).toHaveFocus();
+
+ // Deactivating should NOT restore focus to prev — focus never entered the
+ // trap, so restoring would cancel the blur the user asked for.
+ rerender(<RestoreFixture isActive={false} />);
+ expect(prev).not.toHaveFocus();
+ expect(document.body).toHaveFocus();
+ });
+
+ it('still restores focus when focus entered the trap and was then lost', () => {
+ // Complement to the test above: focus DID enter the trap (Dialog,
+ // DropdownMenu, a Typeahead option click), then the element was blurred
+ // so activeElement falls to <body>. The restore should still fire.
+ const {rerender} = render(<RestoreFixture isActive={false} />);
+ const prev = screen.getByTestId('prev');
+ prev.focus();
+
+ rerender(<RestoreFixture isActive={true} />);
+ // Focus enters the trap, as auto-focus or a keyboard user would.
+ screen.getByTestId('inside').focus();
+ expect(screen.getByTestId('inside')).toHaveFocus();
+
+ // Focus is lost from inside the trap — e.g. the trap content was removed
+ // or the user tabbed away — so activeElement falls to <body>.
+ (document.activeElement as HTMLElement).blur();
+ expect(document.body).toHaveFocus();
+
+ // Because focus was inside the trap at some point, the restore fires and
+ // returns focus to the element that was focused before activation.
+ rerender(<RestoreFixture isActive={false} />);
+ expect(prev).toHaveFocus();
+ });
});
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index ce8997599f..7d460f1469 100644
--- a/packages/core/src/hooks/useFocusTrap.ts
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -158,7 +158,9 @@ export interface UseFocusTrapReturn<T extends HTMLElement = HTMLElement> {
* - 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)
+ * (so consumers that restore focus themselves are unaffected) or focus
+ * never entered the trap (so popups that keep focus on their trigger, like
+ * comboboxes, are unaffected)
*
* @example
* ```
@@ -243,6 +245,18 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
* 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.
+ *
+ * The restore is also skipped when focus never entered the trap while it
+ * was active. Some popups — a Typeahead/PowerSearch listbox anchored to its
+ * own input — deliberately keep DOM focus on the trigger and never move it
+ * into the trap container (they open with `role: "none"` and
+ * `hasAutoFocus: false`). For those, the restore would cancel a blur the
+ * user asked for on outside-click dismissal, re-focusing the trigger so a
+ * second click no longer fires a `focus` event and cannot reopen the menu.
+ * Tracking `focusin` inside the container distinguishes "focus was here and
+ * we should rescue it" from "focus was never here and we should leave it
+ * alone" — popups that do take focus (Dialog, DropdownMenu, a Typeahead
+ * option click) are unaffected.
*/
useEffect(() => {
if (!isActive) {
@@ -253,7 +267,27 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
// Snapshot the container now; by cleanup it may be detached or unmounted.
const container = containerRef.current;
+ // Whether focus ever entered the trap container while it was active.
+ // Initialized from the current active element in case focus was already
+ // inside at activation (e.g. a programmatic focus before the effect ran).
+ let hadFocusInside =
+ container != null && container.contains(document.activeElement);
+
+ const markFocusInside = (event: FocusEvent) => {
+ const target = event.target as Node | null;
+ if (target != null && containerRef.current?.contains(target)) {
+ hadFocusInside = true;
+ }
+ };
+ document.addEventListener('focusin', markFocusInside, true);
+
return () => {
+ document.removeEventListener('focusin', markFocusInside, true);
+
+ if (!hadFocusInside) {
+ return;
+ }
+
const active = document.activeElement;
const focusWasLost =
active == null ||