Skip to content

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

TypeScript

fix(Dialog): a dialog that unmounts while open returns focus to its opener (#9627)

Cindy Zhangc0929c879b3a
diff --git a/.changeset/dialog-unmount-returns-focus.md b/.changeset/dialog-unmount-returns-focus.md
new file mode 100644
index 0000000000..039467a58e
--- /dev/null
+++ b/.changeset/dialog-unmount-returns-focus.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `Dialog` (and `AlertDialog`, `CommandPalette`): a dialog that unmounts while it is open, for example one rendered only while open (`{isEditing && <Dialog isOpen …>}`) or removed with the rest of a view, now returns focus to the control that opened it instead of dropping it to the page.
+
+@cixzhang @duytbp
diff --git a/docs/specs/components/Dialog/Dialog.spec.md b/docs/specs/components/Dialog/Dialog.spec.md
index e5eeb1f4d0..46e16f6cd2 100644
--- a/docs/specs/components/Dialog/Dialog.spec.md
+++ b/docs/specs/components/Dialog/Dialog.spec.md
@@ -144,14 +144,15 @@ component design and theming owners.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------ | ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
-| FR1–FR3, AR1 | shared modal-dialog binding in `Dialog.a11y.test.tsx` and `Dialog.a11y.chromium.spec.ts`; local DialogHeader focus tests | header default, explicit descendant, no request | the shared contract fails when focus is applied before native modality, misses the declared target, or leaves the visible modal on native fallback | audit:Dialog/accessibility |
-| FR4, AR2 | shared modal-dialog browser binding plus the local unavailable-invoker close test | external trigger, descendant mount focus, removed trigger | the shared contract records an exact current failure when descendant focus replaces the return owner; the local test keeps close safe after invoker removal | audit:Dialog/behavior |
-| FR5 | inline Dialog tests | DialogHeader and focusable children | inline preview steals focus or invokes native modal methods | audit:Dialog/behavior |
-| FR6, AR3 | shared modal-dialog binding plus the local composed-action focus fixture | DialogHeader heading, TextInput, action button | focus depends on a private React child type or strips semantics from the target | audit:Dialog/public-api |
-| FR7 | `Dialog.test.tsx`, `AlertDialog.test.tsx` and `CommandPalette.test.tsx` focus-region suites | last and first tabbable control, Dialog in Dialog, inline | Tab from the last control leaves the modal, or an outer Dialog answers an inner one's Tab | audit:Dialog/accessibility |
-| FR8 | `Dialog.ssr.test.tsx` | Open on the server; hydration; a closed Dialog's markup | An open server render with `aria-modal`, open styles, or markup unlike a closed one, a hydration error, no `showModal()` after hydration, an entry motion on the open right after hydration, or none on a later open fails. | audit:Dialog/accessibility |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------ | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
+| FR1–FR3, AR1 | shared modal-dialog binding in `Dialog.a11y.test.tsx` and `Dialog.a11y.chromium.spec.ts`; local DialogHeader focus tests | header default, explicit descendant, no request | the shared contract fails when focus is applied before native modality, misses the declared target, or leaves the visible modal on native fallback | audit:Dialog/accessibility |
+| FR4, AR2 | shared modal-dialog browser binding plus the local unavailable-invoker close test | external trigger, descendant mount focus, removed trigger | the shared contract records an exact current failure when descendant focus replaces the return owner; the local test keeps close safe after invoker removal | audit:Dialog/behavior |
+| AR2 | `Dialog.test.tsx` "unmounting while open" cases | dialog rendered only while open and unmounted by its own action; removed with its view; focus moved elsewhere first; StrictMode | focus left on the page body after an open dialog unmounts, or focus pulled back from where the user moved it, fails | audit:Dialog/behavior |
+| FR5 | inline Dialog tests | DialogHeader and focusable children | inline preview steals focus or invokes native modal methods | audit:Dialog/behavior |
+| FR6, AR3 | shared modal-dialog binding plus the local composed-action focus fixture | DialogHeader heading, TextInput, action button | focus depends on a private React child type or strips semantics from the target | audit:Dialog/public-api |
+| FR7 | `Dialog.test.tsx`, `AlertDialog.test.tsx` and `CommandPalette.test.tsx` focus-region suites | last and first tabbable control, Dialog in Dialog, inline | Tab from the last control leaves the modal, or an outer Dialog answers an inner one's Tab | audit:Dialog/accessibility |
+| FR8 | `Dialog.ssr.test.tsx` | Open on the server; hydration; a closed Dialog's markup | An open server render with `aria-modal`, open styles, or markup unlike a closed one, a hydration error, no `showModal()` after hydration, an entry motion on the open right after hydration, or none on a later open fails. | audit:Dialog/accessibility |
## Decision log
diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsx
index 1a9bb5c430..ceaa155b58 100644
--- a/packages/core/src/Dialog/Dialog.test.tsx
+++ b/packages/core/src/Dialog/Dialog.test.tsx
@@ -9,11 +9,12 @@
* SYNC: When Dialog.tsx changes, update tests to match new behavior
*/
-import {useState, type SyntheticEvent} from 'react';
+import {StrictMode, useState, type SyntheticEvent} from 'react';
import {readFileSync} from 'node:fs';
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import type {MockInstance} from 'vitest';
import {
+ act,
render,
screen,
fireEvent,
@@ -120,6 +121,283 @@ beforeEach(() => {
});
describe('Dialog', () => {
+ // AR2: a dialog that unmounts while open (rendered only while open, or
+ // removed with the rest of a view) returns focus to its opener, as a close
+ // does.
+ describe('unmounting while open', () => {
+ function Editor({unmountWith}: {unmountWith: 'save' | 'view'}) {
+ const [isEditing, setIsEditing] = useState(false);
+ const [showView, setShowView] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setIsEditing(true)}>
+ Edit
+ </button>
+ {showView && isEditing ? (
+ <Dialog
+ isOpen
+ onOpenChange={setIsEditing}
+ aria-label="Edit profile">
+ <button
+ type="button"
+ onClick={() =>
+ unmountWith === 'save'
+ ? setIsEditing(false)
+ : setShowView(false)
+ }>
+ Save
+ </button>
+ </Dialog>
+ ) : null}
+ </>
+ );
+ }
+
+ it.each([['save'], ['view']] as const)(
+ 'returns focus to the opener when the dialog unmounts (%s)',
+ async unmountWith => {
+ render(<Editor unmountWith={unmountWith} />);
+ const edit = screen.getByRole('button', {name: 'Edit'});
+ edit.focus();
+ fireEvent.click(edit);
+ const save = screen.getByRole('button', {name: 'Save'});
+ save.focus();
+
+ fireEvent.click(save);
+ await Promise.resolve();
+
+ expect(screen.queryByRole('button', {name: 'Save'})).toBeNull();
+ expect(document.activeElement).toBe(edit);
+ },
+ );
+
+ it('keeps focus inside an open dialog through StrictMode effects, then returns it on unmount', async () => {
+ render(
+ <StrictMode>
+ <Editor unmountWith="save" />
+ </StrictMode>,
+ );
+ const edit = screen.getByRole('button', {name: 'Edit'});
+ edit.focus();
+ fireEvent.click(edit);
+ const save = screen.getByRole('button', {name: 'Save'});
+ save.focus();
+ await Promise.resolve();
+ expect(document.activeElement).toBe(save);
+
+ fireEvent.click(save);
+ await Promise.resolve();
+
+ expect(document.activeElement).toBe(edit);
+ });
+
+ // The case table for a dialog that disappears while it is open. Focus
+ // goes back to the opener only when the removal lost it: it was inside
+ // the dialog, or nowhere. A control the user pressed outside the dialog
+ // (or outside the frame that holds it) keeps its focus, and an opener
+ // that left with a removed frame gets nothing.
+ type Place = 'page' | 'frame';
+ type Row = {
+ dialogIn: Place;
+ openerIn: Place;
+ removed: 'dialog' | 'frame';
+ focusBefore: 'inside' | 'pageControl' | 'nowhere';
+ expected: 'opener' | 'pageControl' | 'nothing';
+ };
+ const rows: Row[] = [
+ {
+ dialogIn: 'page',
+ openerIn: 'page',
+ removed: 'dialog',
+ focusBefore: 'inside',
+ expected: 'opener',
+ },
+ {
+ dialogIn: 'page',
+ openerIn: 'page',
+ removed: 'dialog',
+ focusBefore: 'nowhere',
+ expected: 'opener',
+ },
+ {
+ dialogIn: 'page',
+ openerIn: 'page',
+ removed: 'dialog',
+ focusBefore: 'pageControl',
+ expected: 'pageControl',
+ },
+ {
+ dialogIn: 'frame',
+ openerIn: 'page',
+ removed: 'dialog',
+ focusBefore: 'inside',
+ expected: 'opener',
+ },
+ {
+ dialogIn: 'frame',
+ openerIn: 'page',
+ removed: 'dialog',
+ focusBefore: 'nowhere',
+ expected: 'opener',
+ },
+ {
+ dialogIn: 'frame',
+ openerIn: 'page',
+ removed: 'dialog',
+ focusBefore: 'pageControl',
+ expected: 'pageControl',
+ },
+ {
+ dialogIn: 'frame',
+ openerIn: 'page',
+ removed: 'frame',
+ focusBefore: 'inside',
+ expected: 'opener',
+ },
+ {
+ dialogIn: 'frame',
+ openerIn: 'page',
+ removed: 'frame',
+ focusBefore: 'pageControl',
+ expected: 'pageControl',
+ },
+ {
+ dialogIn: 'frame',
+ openerIn: 'frame',
+ removed: 'dialog',
+ focusBefore: 'inside',
+ expected: 'opener',
+ },
+ {
+ dialogIn: 'frame',
+ openerIn: 'frame',
+ removed: 'dialog',
+ focusBefore: 'pageControl',
+ expected: 'pageControl',
+ },
+ {
+ dialogIn: 'frame',
+ openerIn: 'frame',
+ removed: 'frame',
+ focusBefore: 'inside',
+ expected: 'nothing',
+ },
+ {
+ dialogIn: 'frame',
+ openerIn: 'frame',
+ removed: 'frame',
+ focusBefore: 'pageControl',
+ expected: 'pageControl',
+ },
+ ];
+
+ it.each(rows)(
+ 'dialog in $dialogIn, opener in $openerIn, $removed removed, focus $focusBefore: focus goes to $expected',
+ async ({dialogIn, openerIn, removed, focusBefore, expected}) => {
+ const needsFrame = dialogIn === 'frame' || openerIn === 'frame';
+ const frame = needsFrame ? document.createElement('iframe') : null;
+ if (frame != null) {
+ document.body.append(frame);
+ // jsdom gives each document its own HTMLDialogElement prototype.
+ const {prototype} =
+ frame.contentDocument!.defaultView!.HTMLDialogElement;
+ prototype.showModal = HTMLDialogElement.prototype.showModal;
+ prototype.close = HTMLDialogElement.prototype.close;
+ }
+ const into = (place: Place, node: React.ReactNode): React.ReactNode =>
+ place === 'frame'
+ ? createPortal(node, frame!.contentDocument!.body)
+ : node;
+ let setOpen: (isOpen: boolean) => void = () => {};
+ function Harness() {
+ const [isOpen, setIsOpen] = useState(false);
+ setOpen = setIsOpen;
+ return (
+ <>
+ {into(
+ openerIn,
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Opener
+ </button>,
+ )}
+ {isOpen
+ ? into(
+ dialogIn,
+ <Dialog isOpen onOpenChange={setIsOpen} aria-label="Case">
+ <button type="button">Inside</button>
+ </Dialog>,
+ )
+ : null}
+ <button type="button">Page control</button>
+ </>
+ );
+ }
+ // Focus in a frame is also the frame element's focus in the page,
+ // as in a browser.
+ const focusIn = (element: HTMLElement) => {
+ if (frame != null && element.ownerDocument !== document) {
+ frame.focus();
+ }
+ element.focus();
+ };
+ const findIn = (place: Place, name: string) =>
+ Array.from(
+ (place === 'frame'
+ ? frame!.contentDocument!
+ : document
+ ).querySelectorAll('button'),
+ ).find(button => button.textContent === name)!;
+
+ const {unmount} = render(<Harness />);
+ const opener = findIn(openerIn, 'Opener');
+ focusIn(opener);
+ act(() => setOpen(true));
+ const pageControl = findIn('page', 'Page control');
+ if (focusBefore === 'inside') {
+ focusIn(findIn(dialogIn, 'Inside'));
+ } else if (focusBefore === 'pageControl') {
+ pageControl.focus();
+ } else {
+ (document.activeElement as HTMLElement | null)?.blur();
+ (frame?.contentDocument?.activeElement as HTMLElement | null)?.blur();
+ }
+
+ // The dialog unmounts; a removed frame goes in the same task,
+ // before the focus check runs.
+ act(() => setOpen(false));
+ if (removed === 'frame') {
+ frame!.remove();
+ // A browser drops a removed frame's window; jsdom keeps it.
+ Object.defineProperty(frame!.contentDocument ?? {}, 'defaultView', {
+ configurable: true,
+ get: () => null,
+ });
+ }
+ await Promise.resolve();
+
+ if (expected === 'opener') {
+ expect(opener.ownerDocument.activeElement).toBe(opener);
+ } else if (expected === 'pageControl') {
+ expect(document.activeElement).toBe(pageControl);
+ } else {
+ expect(opener.isConnected).toBe(false);
+ expect(document.activeElement).not.toBe(opener);
+ }
+
+ try {
+ unmount();
+ } catch (error) {
+ // jsdom empties a removed frame's document, so React can no longer
+ // take a portal out of it; a browser keeps the nodes.
+ if (removed !== 'frame' || !String(error).includes('not a child')) {
+ throw error;
+ }
+ }
+ frame?.remove();
+ },
+ );
+ });
+
it('restores focus to the opener when content mounts in the open commit', () => {
function Harness({
open,
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index 6e46c4a8e1..565ca54bda 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -80,7 +80,7 @@ import {themeProps} from '../utils/themeProps';
import type {DialogVariantMap} from './index';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {useInteractionModalityTracking} from '../utils/interactionModality';
-import {focusForLastInput} from '../utils/focusReturn';
+import {focusForLastInput, isFocusLost} from '../utils/focusReturn';
import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {useMergedRefs} from '../hooks/useMergedRefs';
@@ -634,6 +634,42 @@ export function Dialog({
}
}, [isOpen, isInline]);
+ // A dialog that unmounts while open (rendered only while open, or removed
+ // with the rest of a view) never runs the close branch above, and removing a
+ // <dialog> does not run the browser's own focus return. Focus left inside
+ // it, or dropped to the body by the removal, goes back to the opener.
+ useEffect(() => {
+ if (isInline) {
+ return;
+ }
+ const dialog = dialogRef.current;
+ // Read now: a removed iframe's document has no window, so its frame
+ // element can no longer be found once the dialog is gone.
+ const host = dialog?.ownerDocument.defaultView?.frameElement ?? null;
+ return () => {
+ const trigger = triggerElementRef.current;
+ if (dialog == null || trigger == null) {
+ return;
+ }
+ // Checked once the commit has finished: StrictMode's simulated unmount
+ // leaves the dialog in the document, and only a real removal returns
+ // focus.
+ queueMicrotask(() => {
+ if (dialog.isConnected || !trigger.isConnected) {
+ return;
+ }
+ // isFocusLost reads the dialog's own document. For a dialog in an
+ // iframe, the document that hosts the frame must also have lost focus
+ // or keep it on that frame, wherever the opener is: a control the
+ // user pressed outside the frame to remove the dialog, or the frame
+ // itself, keeps its focus.
+ if (isFocusLost(dialog) && (host == null || isFocusLost(host))) {
+ focusForLastInput(trigger);
+ }
+ });
+ };
+ }, [isInline]);
+
// Host app-global surfaces (toasts) inside this modal while it is open, so
// they stay visible and operable above it.
useModalOutlet(dialogRef, isOpen && !isInline);