Skip to content

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

TypeScript

refactor(Layer): modals hand toasts back through a callback ref (#10351)

Cindy Zhang8ba5bbcc3886
diff --git a/.changeset/modal-outlet-hand-back-ref.md b/.changeset/modal-outlet-hand-back-ref.md
new file mode 100644
index 0000000000..972c116f95
--- /dev/null
+++ b/.changeset/modal-outlet-hand-back-ref.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: `Dialog`, `Drawer` and `BottomSheet` hand the toast viewport back to the page through a callback ref when they close or unmount, in place of a layout cleanup. A toast still stays on screen while the modal closes. Apps see no change.
+
+@cixzhang
diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsx
index 17e6a5548c..dba6c48503 100644
--- a/packages/core/src/BottomSheet/BottomSheet.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.tsx
@@ -719,7 +719,7 @@ function StandaloneBottomSheet({
// top one closes. A Dialog opened from a sheet stays above every sheet. A
// closing sheet stops supplying when it starts to close. Passive: it runs
// after the layout effects that present.
- useModalOutlet(
+ const outletRef = useModalOutlet(
dialogRef,
isOpen && hasScrim,
stackView.isTop,
@@ -991,6 +991,7 @@ function StandaloneBottomSheet({
onScrimOpacity={handleScrimOpacity}
onScrimFadeDuration={handleScrimFadeDuration}
onElementChange={handlePanelElementChange}
+ handleRef={outletRef}
onMotionStart={handleMotionStart}
onMotionComplete={handleMotionComplete}>
<ModalAnnounceProvider
diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsx
index 73795e6545..5b150fbfbe 100644
--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx
@@ -28,6 +28,7 @@ import {
useRef,
useSyncExternalStore,
type ReactNode,
+ type Ref,
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
@@ -497,6 +498,11 @@ interface BottomSheetPanelProps extends BaseProps<HTMLDivElement> {
*/
onScrimFadeDuration?: (panel: HTMLElement, ms: number | null) => void;
onElementChange?: (element: HTMLDivElement | null) => void;
+ /**
+ * A ref for the grab handle's element. The handle stays mounted with the
+ * panel and carries no other ref.
+ */
+ handleRef?: Ref<HTMLDivElement>;
onMotionStart?: (motion: BottomSheetPanelMotion) => void;
onMotionComplete?: (motion: BottomSheetPanelMotion) => void;
}
@@ -675,6 +681,7 @@ export function BottomSheetPanel({
onScrimOpacity,
onScrimFadeDuration,
onElementChange,
+ handleRef,
onMotionStart,
onMotionComplete,
...props
@@ -1149,6 +1156,7 @@ export function BottomSheetPanel({
},
)}>
<div
+ ref={handleRef}
{...stylex.props(styles.handleBar)}
{...handleProps}
aria-hidden="true"
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
index 3abb91f987..01527cabf5 100644
--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
@@ -67,7 +67,7 @@ import {dispatchLayerEscapeKeyDown} from '../Layer/layerStack';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {composeEventHandlers} from '../utils';
import {mergeRefs} from '../utils/mergeRefs';
-import {useModalOutlet} from '../Layer/modalOutlet';
+import {useModalOutletWithoutRef} from '../Layer/modalOutlet';
import {BottomSheetHostContext} from './BottomSheetHostContext';
import {
BOTTOM_SHEET_STACK_DEFAULT_VIEW,
@@ -540,7 +540,10 @@ export function BottomSheetSwitcher({
// `hostSheet` across a handoff, and the fading retained dialog is never the
// outlet. A closing flow stops supplying at once. Passive: it runs after the
// layout effects that present the step dialogs.
- useModalOutlet(
+ // The flow has no element for the outlet's ref. Its wrapper's ref is the
+ // sheet stack's tree-order anchor, which the stack reads in the closing
+ // commit, and the element of its host step changes on a handoff.
+ useModalOutletWithoutRef(
hostDialogRef,
isModal && isFlowOpen,
stackView.isTop || !stackView.isStacked,
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index 7118e2faad..4dc26d04fe 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -715,7 +715,7 @@ export function Dialog({
// Host app-global surfaces (toasts) inside this modal while it is open, so
// they stay visible and operable above it.
- useModalOutlet(dialogRef, isOpen && !isInline);
+ const outletRef = useModalOutlet(dialogRef, isOpen && !isInline);
// Lock body scroll when dialog is open (iOS Safari workaround)
// Skip for inline rendering — no modal overlay to compensate for.
@@ -803,6 +803,7 @@ export function Dialog({
const innerContent = (
<div
+ ref={outletRef}
{...stylex.props(
styles.inner,
...container(
diff --git a/packages/core/src/Drawer/Drawer.tsx b/packages/core/src/Drawer/Drawer.tsx
index 92b392f430..1c03ea9bd5 100644
--- a/packages/core/src/Drawer/Drawer.tsx
+++ b/packages/core/src/Drawer/Drawer.tsx
@@ -507,7 +507,7 @@ export function Drawer({
// Toasts outside an open modal are inert, so the open drawer hosts them.
// It releases them when its exit starts.
// showModal() must run first, so keep this call after useDrawerDialogPresence.
- useModalOutlet(dialogRef, isOpen && hasScrim);
+ const outletRef = useModalOutlet(dialogRef, isOpen && hasScrim);
const handleDismiss = useCallback(() => {
onOpenChange(false);
@@ -641,6 +641,7 @@ export function Drawer({
{/* Scrollable content area — tabIndex so the dialog's focusing steps
land on the panel body rather than the first button inside. */}
<div
+ ref={outletRef}
tabIndex={-1}
{...stylex.props(
styles.content,
diff --git a/packages/core/src/Layer/modalOutlet.ts b/packages/core/src/Layer/modalOutlet.ts
index 640ea1d652..7e9f962251 100644
--- a/packages/core/src/Layer/modalOutlet.ts
+++ b/packages/core/src/Layer/modalOutlet.ts
@@ -5,7 +5,9 @@
/**
* @file modalOutlet.ts
* @input The open Dialog and scrim BottomSheet `<dialog>` elements
- * @output Exports useModalOutlet (a modal supplies its outlet),
+ * @output Exports useModalOutlet (a modal supplies its outlet, and withdraws
+ * it through the ref it returns), useModalOutletWithoutRef (the same for a
+ * modal with no element for that ref),
* getActiveModalOutlet, subscribeModalOutlets (a global host follows the
* latest one), and notifyTopLayerEntry (a non-modal surface entered the
* top layer above the hosts)
@@ -30,7 +32,14 @@
* - /docs/architecture/layer-runtime.md
*/
-import {useEffect, useLayoutEffect, useRef, type RefObject} from 'react';
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ type RefCallback,
+ type RefObject,
+} from 'react';
const outlets: HTMLDialogElement[] = [];
// Outlets whose order among themselves is decided by their caller (a stack of
@@ -168,6 +177,10 @@ export function notifyTopLayerEntry(): void {
* above an outlet of another group supplied later, such as a Dialog opened
* from the sheet — and when it turns false the outlet stays supplied (every
* open modal supplies one) but is no longer the group's latest.
+ *
+ * Returns a callback ref that withdraws the outlet in the commit that closes
+ * or unmounts the modal. Attach it to an element the modal owns that stays
+ * mounted while the modal is open and has no other ref.
*/
export function useModalOutlet(
ref: RefObject<HTMLDialogElement | null>,
@@ -175,7 +188,54 @@ export function useModalOutlet(
isLatest: boolean = true,
group?: string,
hostKey?: string | null,
+): RefCallback<HTMLElement> {
+ const withdraw = useOutletSupply(ref, isActive, isLatest, group, hostKey);
+ // The commit that closes the modal hides the dialog, so a host still inside
+ // it paints nothing. The passive cleanup of the supply can run after the
+ // next paint, or after React removes the dialog. The ref changes with
+ // `isActive`, so React detaches the open modal's ref in the closing commit,
+ // before the paint. On unmount, React detaches it before it removes the
+ // dialog, so hosts leave while they are still in the document.
+ return useCallback(
+ (element: HTMLElement | null) =>
+ isActive && element != null ? withdraw : undefined,
+ [isActive, withdraw],
+ );
+}
+
+/**
+ * The same as `useModalOutlet`, for a modal that owns no element for the
+ * returned ref: no element that stays mounted while the modal is open and has
+ * no other ref. A layout cleanup then withdraws the outlet in the commit that
+ * closes or unmounts the modal.
+ */
+export function useModalOutletWithoutRef(
+ ref: RefObject<HTMLDialogElement | null>,
+ isActive: boolean,
+ isLatest: boolean = true,
+ group?: string,
+ hostKey?: string | null,
): void {
+ const withdraw = useOutletSupply(ref, isActive, isLatest, group, hostKey);
+ // Syncs the outlet registry in the commit that closes or unmounts the
+ // modal, before the paint.
+ useLayoutEffect(
+ () => (isActive ? withdraw : undefined),
+ [isActive, withdraw],
+ );
+}
+
+/**
+ * Supplies the outlet while the modal is active, and returns a stable
+ * function that withdraws the supplied outlet at once.
+ */
+function useOutletSupply(
+ ref: RefObject<HTMLDialogElement | null>,
+ isActive: boolean,
+ isLatest: boolean,
+ group: string | undefined,
+ hostKey: string | null | undefined,
+): () => void {
// `hostKey` names which element `ref` currently resolves to, for a caller
// whose ref moves between dialogs while it stays active (a switcher flow
// whose host dialog changes on a handoff): a change re-supplies the outlet
@@ -235,19 +295,10 @@ export function useModalOutlet(
raiseWithinGroup(element);
}, [ref, isActive, isLatest, hostKey]);
- // Syncs the outlet registry in the commit that closes or unmounts the modal.
- // That commit hides the dialog, so a host still inside it paints nothing. A
- // passive cleanup can run after the next paint, or after React detaches the
- // dialog.
- useLayoutEffect(() => {
- if (!isActive) {
- return;
+ return useCallback(() => {
+ const supplied = suppliedRef.current;
+ if (supplied != null) {
+ removeOutlet(supplied);
}
- return () => {
- const supplied = suppliedRef.current;
- if (supplied != null) {
- removeOutlet(supplied);
- }
- };
- }, [isActive]);
+ }, []);
}
diff --git a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
index 45755bc8ec..61694efbb0 100644
--- a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
+++ b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
@@ -89,31 +89,10 @@ function DialogFixture({
}
/**
- * A Dialog with a probe after it. The probe calls `onClosingCommit` in the
- * layout phase of the commit that closes the Dialog. That is after every
- * layout cleanup and before the browser can paint.
+ * Calls `onClosingCommit` in the layout phase of the commit in which `isOpen`
+ * turns false. That is after every layout cleanup and before the browser can
+ * paint.
*/
-function ClosingCommitFixture({
- onClosingCommit,
-}: {
- onClosingCommit: () => void;
-}) {
- const [isOpen, setIsOpen] = useState(false);
- return (
- <>
- <button type="button" onClick={() => setIsOpen(true)}>
- Open Edit
- </button>
- <Dialog isOpen={isOpen} onOpenChange={setIsOpen} aria-label="Edit">
- <button type="button" onClick={() => setIsOpen(false)}>
- Close Edit
- </button>
- </Dialog>
- <ClosingCommitProbe isOpen={isOpen} onClosingCommit={onClosingCommit} />
- </>
- );
-}
-
function ClosingCommitProbe({
isOpen,
onClosingCommit,
@@ -487,30 +466,6 @@ describe('ToastViewport modal hosting', () => {
expect(getDialog('Outer').contains(getViewport())).toBe(true);
});
- it('returns to its place in the commit that closes the Dialog, before anything paints', () => {
- // The closing commit stops displaying the dialog. After a close outside a
- // click, the browser can paint before passive effects run. A viewport
- // still inside the dialog then paints nothing.
- const isInDialogAtClose: boolean[] = [];
- const {container} = render(
- <ToastViewport>
- <ToastButton />
- <ClosingCommitFixture
- onClosingCommit={() => {
- isInDialogAtClose.push(getDialog('Edit').contains(getViewport()));
- }}
- />
- </ToastViewport>,
- );
- fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
- fireEvent.click(screen.getByRole('button', {name: 'Open Edit'}));
- expect(getDialog('Edit').contains(getViewport())).toBe(true);
-
- fireEvent.click(screen.getByRole('button', {name: 'Close Edit'}));
- expect(isInDialogAtClose).toEqual([false]);
- expect(container.contains(getViewport())).toBe(true);
- });
-
it('returns to its place when the open Dialog unmounts', () => {
const {container} = render(
<ToastViewport>
@@ -1114,3 +1069,150 @@ describe('ToastViewport above a BottomSheetSwitcher flow', () => {
expect(container.contains(getViewport())).toBe(true);
});
});
+
+describe('ToastViewport leaves each kind of modal before the paint', () => {
+ type ModalKind = 'Dialog' | 'Drawer' | 'BottomSheet' | 'BottomSheetSwitcher';
+
+ /** A modal of `kind` named "Edit", with a button inside that closes it. */
+ function EditModal({
+ kind,
+ isOpen,
+ onClose,
+ }: {
+ kind: ModalKind;
+ isOpen: boolean;
+ onClose: () => void;
+ }) {
+ const close = (
+ <button type="button" onClick={onClose}>
+ Close Edit
+ </button>
+ );
+ switch (kind) {
+ case 'Dialog':
+ return (
+ <Dialog isOpen={isOpen} onOpenChange={onClose} aria-label="Edit">
+ {close}
+ </Dialog>
+ );
+ case 'Drawer':
+ return (
+ <Drawer isOpen={isOpen} onOpenChange={onClose} label="Edit">
+ {close}
+ </Drawer>
+ );
+ case 'BottomSheet':
+ return (
+ <BottomSheet isOpen={isOpen} onOpenChange={onClose} label="Edit">
+ {close}
+ </BottomSheet>
+ );
+ case 'BottomSheetSwitcher':
+ return (
+ <BottomSheetSwitcher
+ activeSheet={isOpen ? 'edit' : null}
+ onActiveSheetChange={onClose}>
+ <BottomSheet sheetId="edit" label="Edit">
+ {close}
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ );
+ }
+ }
+
+ /**
+ * A modal with a probe after it. The probe calls `onEndingCommit` in the
+ * layout phase of the commit that closes or unmounts the modal. That is
+ * after the modal's ref cleanups and layout cleanups, and before the browser
+ * can paint.
+ */
+ function EndingCommitFixture({
+ kind,
+ onEndingCommit,
+ }: {
+ kind: ModalKind;
+ onEndingCommit: () => void;
+ }) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [isMounted, setIsMounted] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Open Edit
+ </button>
+ <button type="button" onClick={() => setIsMounted(false)}>
+ Unmount Edit
+ </button>
+ {isMounted ? (
+ <EditModal
+ kind={kind}
+ isOpen={isOpen}
+ onClose={() => setIsOpen(false)}
+ />
+ ) : null}
+ <ClosingCommitProbe
+ isOpen={isMounted && isOpen}
+ onClosingCommit={onEndingCommit}
+ />
+ </>
+ );
+ }
+
+ /** Where the viewport is: in a dialog, and in the document. */
+ function viewportPlace() {
+ const viewport = getViewport();
+ return {
+ isInDialog: viewport.closest('dialog') != null,
+ isInDocument: viewport.isConnected,
+ };
+ }
+
+ function renderOpen(kind: ModalKind) {
+ const places: ReturnType<typeof viewportPlace>[] = [];
+ const result = render(
+ <ToastViewport>
+ <ToastButton />
+ <EndingCommitFixture
+ kind={kind}
+ onEndingCommit={() => places.push(viewportPlace())}
+ />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Open Edit'}));
+ expect(getDialog('Edit').contains(getViewport())).toBe(true);
+ return {...result, places};
+ }
+
+ const kinds: ModalKind[] = [
+ 'Dialog',
+ 'Drawer',
+ 'BottomSheet',
+ 'BottomSheetSwitcher',
+ ];
+
+ it.each(kinds)(
+ 'returns to its place in the commit that closes a %s',
+ kind => {
+ // The closing commit can stop displaying the dialog. After a close
+ // outside a click, the browser can paint before passive effects run. A
+ // viewport still inside the dialog then paints nothing.
+ const {container, places} = renderOpen(kind);
+ fireEvent.click(screen.getByRole('button', {name: 'Close Edit'}));
+ expect(places).toEqual([{isInDialog: false, isInDocument: true}]);
+ expect(container.contains(getViewport())).toBe(true);
+ },
+ );
+
+ it.each(kinds)(
+ 'returns to its place in the commit that unmounts an open %s, while still in the document',
+ kind => {
+ const {container, places} = renderOpen(kind);
+ const toast = screen.getByText('Saved');
+ fireEvent.click(screen.getByRole('button', {name: 'Unmount Edit'}));
+ expect(places).toEqual([{isInDialog: false, isInDocument: true}]);
+ expect(container.contains(getViewport())).toBe(true);
+ expect(screen.getByText('Saved')).toBe(toast);
+ },
+ );
+});
diff --git a/packages/core/src/Toast/__tests__/ToastViewport.hostMove.interaction.browser.spec.ts b/packages/core/src/Toast/__tests__/ToastViewport.hostMove.interaction.browser.spec.ts
index 70180b1125..72e1da0dbc 100644
--- a/packages/core/src/Toast/__tests__/ToastViewport.hostMove.interaction.browser.spec.ts
+++ b/packages/core/src/Toast/__tests__/ToastViewport.hostMove.interaction.browser.spec.ts
@@ -478,28 +478,33 @@ test.describe('a toast in a top-layer viewport', () => {
test('a toast stays painted when the Dialog that hosts it closes after a save', async ({
page,
}) => {
- await openStory(page, storybook(), SAVE_STORY);
- const dialog = await openDialog(page);
- await watchHiddenCard(page);
- await startRecording(page);
- // Save shows the toast, then closes the dialog when the save finishes.
- // That close is outside a click, so the browser can paint before the
- // passive effects run.
- await dialog.getByRole('button', {name: 'Save'}).click();
- await expect(dialog).toBeHidden();
- await waitForRest(toastRow(page));
- const {frames, starts} = await stopRecording(page);
- await expect(toastRow(page).getByText('Saving the item.')).toBeVisible();
- await expectRowShown(page);
- expect(placesOf(frames)).toEqual(['dialog', 'page']);
- // No DOM change left the card in a dialog that no longer displays.
- expect(await hiddenCardCount(page)).toBe(0);
- expect(frames.every(frame => frame.hasBox)).toBe(true);
- // At 1×, the card's opacity and the row's grid each start once.
- // Transition events arrive however late the frames are.
- expect(starts.filter(start => start === 'card opacity')).toHaveLength(1);
- expect(
- starts.filter(start => start === 'row grid-template-rows'),
- ).toHaveLength(1);
+ test.setTimeout(180_000);
+ // A frame without the toast does not show at every close, so the case
+ // closes the Dialog in eight fresh documents.
+ for (let session = 0; session < 8; session += 1) {
+ await openStory(page, storybook(), SAVE_STORY);
+ const dialog = await openDialog(page);
+ await watchHiddenCard(page);
+ await startRecording(page);
+ // Save shows the toast, then closes the dialog when the save finishes.
+ // That close is outside a click, so the browser can paint before the
+ // passive effects run.
+ await dialog.getByRole('button', {name: 'Save'}).click();
+ await expect(dialog).toBeHidden();
+ await waitForRest(toastRow(page));
+ const {frames, starts} = await stopRecording(page);
+ await expect(toastRow(page).getByText('Saving the item.')).toBeVisible();
+ await expectRowShown(page);
+ expect(placesOf(frames)).toEqual(['dialog', 'page']);
+ // No DOM change left the card in a dialog that no longer displays.
+ expect(await hiddenCardCount(page)).toBe(0);
+ expect(frames.every(frame => frame.hasBox)).toBe(true);
+ // At 1×, the card's opacity and the row's grid each start once.
+ // Transition events arrive however late the frames are.
+ expect(starts.filter(start => start === 'card opacity')).toHaveLength(1);
+ expect(
+ starts.filter(start => start === 'row grid-template-rows'),
+ ).toHaveLength(1);
+ }
});
});