Skip to content

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

TypeScript

fix(Lightbox): a viewer that unmounts while open returns focus to its opener (#9629)

Cindy Zhang709a28641fc7
diff --git a/.changeset/lightbox-unmount-returns-focus.md b/.changeset/lightbox-unmount-returns-focus.md
new file mode 100644
index 0000000000..8a9de4ecd7
--- /dev/null
+++ b/.changeset/lightbox-unmount-returns-focus.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `Lightbox`: a viewer that unmounts while it is open (rendered only while open, or removed with its view) now returns focus to the element that opened it, when that element is still on the page, instead of dropping it to the page. A control the user pressed to remove the viewer keeps its focus.
+
+@cixzhang @duytbp
diff --git a/docs/specs/components/Lightbox/Lightbox.spec.md b/docs/specs/components/Lightbox/Lightbox.spec.md
index 8c28a713c8..466ae57135 100644
--- a/docs/specs/components/Lightbox/Lightbox.spec.md
+++ b/docs/specs/components/Lightbox/Lightbox.spec.md
@@ -320,6 +320,7 @@ a decision that they must remain unthemeable.
| FR2 | Source inspection and `themingTargets.test.ts` | Viewer overlay, Media, Caption, and Counter | Removing the root target or documenting an unshipped child target fails evidence or inventory. | `audit:Lightbox/theming` |
| FR3 | Source inspection plus Button and IconButton public composition | Close and gallery navigation controls | Re-owning a control surface requires the delegated owner and this map to change. | `audit:Lightbox/theming` |
| FR4, AR3 | Browser keyboard test: Tab and Shift+Tab at both ends, Escape, arrows in LTR and RTL, `+`, `-`, `0`, close focus | Single image, gallery, zoomed image, removed opener | Focus leaving the viewer, a key without its action, or focus not returning to a connected opener fails. | `audit:Lightbox/accessibility` |
+| AR3 | `Lightbox.test.tsx` "Lightbox unmounting while open" suite | Viewer rendered only while open and removed by the page, with the opener still on the page; a page control that removes it keeps its focus; StrictMode | Focus left on the page body after an open viewer unmounts fails. | `audit:Lightbox/accessibility` |
| FR5–FR10 | Interaction tests on synthetic touch streams with explicit timestamps; Reduce Motion; a busy main thread | Below and past each commit point; a release moving back; a drag on a video's frame and on its scrubber; a tap beside the photo with the controls hidden | A literal timing, a second decision during a settle, a gesture that pages while pinching, a drag on a video's frame that does not page, a drag on its controls that pages, or a tap beside the photo that closes while the controls are hidden fails. | `audit:Lightbox/touch` |
| FR11 | Fine-pointer browser tests | Double-click, click on the photo, drag, ctrl-wheel, wheel | A double-click that does not zoom 2× about the point, a click that hides the controls, or a fine-pointer close that animates fails. | `audit:Lightbox/touch` |
| FR6, AR1 | Touch test double-tapping a photo shaped like the screen and a landscape photo | 9:16 photo on a phone viewport, 3:2 photo | A double tap that zooms less than 2×, or not about the tapped point, fails. | `audit:Lightbox/touch` |
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index 03b409480e..ebe3105173 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -81,7 +81,10 @@ import {themeProps} from '../utils/themeProps';
import type {DialogVariantMap} from './index';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {useInteractionModalityTracking} from '../utils/interactionModality';
-import {focusForLastInput, isFocusLost} from '../utils/focusReturn';
+import {
+ focusForLastInput,
+ prepareFocusReturnOnRemoval,
+} from '../utils/focusReturn';
import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {useMergedRefs} from '../hooks/useMergedRefs';
@@ -653,39 +656,15 @@ 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.
+ // with the rest of a view) never runs the close branch above. Focus the
+ // removal lost goes back to the opener.
useEffect(() => {
- if (isInline) {
+ const dialog = dialogRef.current;
+ if (isInline || dialog == null) {
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);
- }
- });
- };
+ const returnFocusOnRemoval = prepareFocusReturnOnRemoval(dialog);
+ return () => returnFocusOnRemoval(triggerElementRef.current);
}, [isInline]);
// Host app-global surfaces (toasts) inside this modal while it is open, so
diff --git a/packages/core/src/Lightbox/Lightbox.test.tsx b/packages/core/src/Lightbox/Lightbox.test.tsx
index 047862d78c..c4b5d7e35d 100644
--- a/packages/core/src/Lightbox/Lightbox.test.tsx
+++ b/packages/core/src/Lightbox/Lightbox.test.tsx
@@ -2,7 +2,7 @@
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
-import {Profiler} from 'react';
+import {Profiler, StrictMode, useState} from 'react';
import {Lightbox} from './Lightbox';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {InternationalizationProvider} from '../i18n';
@@ -835,3 +835,85 @@ describe('Lightbox with an unusable controlled index', () => {
).not.toThrow();
});
});
+
+// AR3: a viewer that unmounts while open (rendered only while open, or removed
+// with its view) returns focus to the element that opened it, as a close does.
+describe('Lightbox unmounting while open', () => {
+ const items = [
+ {src: 'a.jpg', alt: 'Sunrise'},
+ {src: 'b.jpg', alt: 'Sunset'},
+ ];
+ function Gallery() {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ View photos
+ </button>
+ {isOpen ? (
+ <Lightbox isOpen onOpenChange={setIsOpen} media={items} index={0} />
+ ) : null}
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Remove viewer
+ </button>
+ </>
+ );
+ }
+
+ it('returns focus to the opener when the viewer unmounts', async () => {
+ render(<Gallery />);
+ const opener = screen.getByRole('button', {name: 'View photos'});
+ opener.focus();
+ fireEvent.click(opener);
+ const next = screen.getByLabelText('Next');
+ next.focus();
+
+ fireEvent.click(
+ screen.getByRole('button', {name: 'Remove viewer', hidden: true}),
+ );
+ await Promise.resolve();
+
+ expect(document.querySelector('dialog')).toBeNull();
+ expect(document.activeElement).toBe(opener);
+ });
+
+ it('leaves focus on a page control the user pressed to remove the viewer', async () => {
+ render(<Gallery />);
+ const opener = screen.getByRole('button', {name: 'View photos'});
+ opener.focus();
+ fireEvent.click(opener);
+ const remove = screen.getByRole('button', {
+ name: 'Remove viewer',
+ hidden: true,
+ });
+ remove.focus();
+
+ fireEvent.click(remove);
+ await Promise.resolve();
+
+ expect(document.querySelector('dialog')).toBeNull();
+ expect(document.activeElement).toBe(remove);
+ });
+
+ it('keeps focus inside through StrictMode effects, then returns it on unmount', async () => {
+ render(
+ <StrictMode>
+ <Gallery />
+ </StrictMode>,
+ );
+ const opener = screen.getByRole('button', {name: 'View photos'});
+ opener.focus();
+ fireEvent.click(opener);
+ const next = screen.getByLabelText('Next');
+ next.focus();
+ await Promise.resolve();
+ expect(document.activeElement).toBe(next);
+
+ fireEvent.click(
+ screen.getByRole('button', {name: 'Remove viewer', hidden: true}),
+ );
+ await Promise.resolve();
+
+ expect(document.activeElement).toBe(opener);
+ });
+});
diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx
index 9a0e117ffd..4ba7244cf7 100644
--- a/packages/core/src/Lightbox/Lightbox.tsx
+++ b/packages/core/src/Lightbox/Lightbox.tsx
@@ -55,6 +55,7 @@ import {
} from '../i18n/useComponentTranslator';
import english from '../i18n/generated-english/Lightbox/Lightbox.generated';
import {isRenderable} from '../utils/isRenderable';
+import {prepareFocusReturnOnRemoval} from '../utils/focusReturn';
registerEnglishFallback(english);
/**
@@ -445,6 +446,23 @@ export function Lightbox({
}
}, [isOpen, hasItem]);
+ // A viewer that unmounts while open (rendered only while open, or removed
+ // with the rest of a view) never runs the close branch above. Focus the
+ // removal lost goes back to the opener while the opener is still on the
+ // page.
+ useEffect(() => {
+ const dialog = dialogRef.current;
+ if (dialog == null) {
+ return;
+ }
+ const returnFocusOnRemoval = prepareFocusReturnOnRemoval(dialog);
+ return () => {
+ if (dialog.open) {
+ returnFocusOnRemoval(triggerElementRef.current);
+ }
+ };
+ }, [hasItem]);
+
const handleClose = useCallback(() => {
onOpenChange(false);
}, [onOpenChange]);
diff --git a/packages/core/src/utils/focusReturn.ts b/packages/core/src/utils/focusReturn.ts
index cd7f305801..be45e0a653 100644
--- a/packages/core/src/utils/focusReturn.ts
+++ b/packages/core/src/utils/focusReturn.ts
@@ -151,3 +151,33 @@ export function focusForLastInput(
}
element.focus({...options, focusVisible: false});
}
+
+/**
+ * Prepares the focus return for an open surface that may be removed while
+ * open (rendered only while open, or removed with its view). Removing a
+ * `<dialog>` runs no close and no browser focus return. Call this while the
+ * surface is mounted: it reads the frame that hosts the surface now, because a
+ * removed frame's document has no window. Call the returned function from the
+ * effect cleanup with the opener.
+ *
+ * Once the commit has finished, focus moves to the opener only when the
+ * surface really left the document (StrictMode's simulated unmount keeps it),
+ * the opener is still on the page, and the removal lost focus, both in the
+ * surface's document and in the document that hosts its frame. A control the
+ * user pressed outside the surface, or outside its frame, keeps its focus.
+ */
+export function prepareFocusReturnOnRemoval(
+ surface: Element,
+): (opener: Element | null) => void {
+ const host = surface.ownerDocument.defaultView?.frameElement ?? null;
+ return opener => {
+ queueMicrotask(() => {
+ if (surface.isConnected || opener == null || !opener.isConnected) {
+ return;
+ }
+ if (isFocusLost(surface) && (host == null || isFocusLost(host))) {
+ focusForLastInput(opener as HTMLElement);
+ }
+ });
+ };
+}