Skip to content

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

TypeScript

fix(Dialog): capture the opener before descendant autofocus effects (#6607)

Manohar Paturid150f7873806
diff --git a/.changeset/restore-dialog-focus-to-opener.md b/.changeset/restore-dialog-focus-to-opener.md
new file mode 100644
index 0000000000..48ee093ace
--- /dev/null
+++ b/.changeset/restore-dialog-focus-to-opener.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Restore focus to the element that opened a Dialog when its content mounts in the open commit. The opener was captured in the Dialog's passive effect, which runs after a freshly mounted DialogHeader's autofocus effect had already moved focus to the dialog's own title — closing then restored focus to that detached title and the user's focus landed on `<body>`. The capture now runs in a layout effect, before any descendant's passive effect. (#5637)
+
+@ManoharPaturi
diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsx
index 62fa2c4f94..5828d165db 100644
--- a/packages/core/src/Dialog/Dialog.test.tsx
+++ b/packages/core/src/Dialog/Dialog.test.tsx
@@ -110,6 +110,52 @@ beforeEach(() => {
});
describe('Dialog', () => {
+ it('restores focus to the opener when content mounts in the open commit', () => {
+ function Harness({
+ open,
+ onOpenChange,
+ }: {
+ open: boolean;
+ onOpenChange: (v: boolean) => void;
+ }) {
+ return (
+ <>
+ <button type="button" onClick={() => onOpenChange(true)}>
+ Open
+ </button>
+ <Dialog isOpen={open} onOpenChange={onOpenChange}>
+ {open ? (
+ <div>
+ <DialogHeader title="Review" />
+ <p>Body</p>
+ </div>
+ ) : null}
+ </Dialog>
+ </>
+ );
+ }
+
+ let open = false;
+ const setOpen = (v: boolean) => {
+ open = v;
+ };
+ const harness = render(<Harness open={open} onOpenChange={setOpen} />);
+ const opener = screen.getByRole('button', {name: 'Open'});
+ opener.focus();
+
+ fireEvent.click(opener);
+ harness.rerender(<Harness open={open} onOpenChange={setOpen} />);
+
+ // The freshly mounted header title is the focused screen reader anchor
+ // while the dialog is open...
+ expect(document.activeElement).toBe(screen.getByText('Review'));
+
+ // ...but closing restores the element that opened the dialog, not the
+ // (now unmounted) title.
+ harness.rerender(<Harness open={false} onOpenChange={setOpen} />);
+ expect(document.activeElement).toBe(opener);
+ });
+
it('renders when isOpen is true', () => {
render(
<Dialog isOpen={true} onOpenChange={() => {}}>
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index 297eeb309e..0803c1cfa4 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -32,6 +32,7 @@ import {
useCallback,
useEffect,
useId,
+ useLayoutEffect,
useMemo,
useRef,
type ReactNode,
@@ -505,12 +506,26 @@ export function Dialog({
const mergedDialogRef = useMergedRefs(ref, attachDialog);
- // Capture the element that was focused when the dialog opened,
- // for directional animation origin and focus restoration on close.
+ // Capture the element that was focused when the dialog opened, for
+ // directional animation origin and focus restoration on close.
const triggerElementRef = useRef<HTMLElement | null>(null);
useInteractionModalityTracking();
+ // This runs in a layout effect so the capture lands before any descendant's
+ // passive mount effect: all layout effects run before any passive effect,
+ // while a child's passive effect runs before this parent's passive effect.
+ // Content that mounts in the open commit — e.g. a DialogHeader focusing its
+ // own title on mount — would otherwise move document.activeElement inside
+ // the dialog before the capture ran, and closing would then restore focus
+ // to a detached node, stranding the user's focus on <body>.
+ useLayoutEffect(() => {
+ if (isInline || !isOpen) {
+ return;
+ }
+ triggerElementRef.current = document.activeElement as HTMLElement | null;
+ }, [isOpen, isInline]);
+
// Derive dismissal behavior from purpose
const allowEscape = purpose !== 'required';
const allowBackdropClick = purpose === 'info';
@@ -526,11 +541,9 @@ export function Dialog({
}
if (isOpen) {
- // Capture the currently focused element as the trigger — used for
- // directional animation origin and focus restoration on close.
- triggerElementRef.current = document.activeElement as HTMLElement | null;
-
- // Set directional CSS custom properties before opening
+ // Set directional CSS custom properties before opening. The trigger was
+ // captured by the layout effect above, before any descendant effect
+ // could move focus.
const trigger = triggerElementRef.current;
if (trigger && trigger !== document.body) {
const dir = getDialogDirection(trigger);
diff --git a/packages/core/src/Dialog/__tests__/Dialog.a11y.known-failures.ts b/packages/core/src/Dialog/__tests__/Dialog.a11y.known-failures.ts
index e4c1050f76..69cbde05cc 100644
--- a/packages/core/src/Dialog/__tests__/Dialog.a11y.known-failures.ts
+++ b/packages/core/src/Dialog/__tests__/Dialog.a11y.known-failures.ts
@@ -25,18 +25,4 @@ export const DIALOG_MODAL_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [
reason:
'This migration records the existing focus-order violation without changing the overlapping Dialog implementation path.',
},
- {
- expectation: 'modal-dialog.focus.restored',
- binding: 'Dialog',
- state: 'conditional-content-focus-restoration',
- evidenceLayer: 'real-browser',
- failureEquals:
- 'closing the modal dialog did not return focus to its still-available invoker',
- standardsReference:
- 'Astryx component:Dialog FR4 — closing a native Dialog must return focus to its still-connected invoker when it can receive focus.',
- userImpact:
- 'When focus-moving content mounts only while the dialog is open, closing can leave the user at the document body instead of the control that opened the task.',
- reason:
- 'This migration records the existing restoration violation without changing the overlapping Dialog implementation path.',
- },
];