An open source design system that's fully customizable and agent ready
TypeScript
fix(Layer): toasts leave a closing modal in the commit that closes it (#10251)
Christopher Chedeau9a8d14d6d5e7
diff --git a/.changeset/toast-stays-when-dialog-closes.md b/.changeset/toast-stays-when-dialog-closes.mdnew file mode 100644index 0000000000..9186b2455b--- /dev/null+++ b/.changeset/toast-stays-when-dialog-closes.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A toast shown over a `Dialog` no longer blinks out for a frame or more when the Dialog closes outside a click, for example when it closes once an awaited save finishes. The toast stays on screen while the Dialog closes. A close from a click, the Escape key or the backdrop already kept it.++@vjeuxdiff --git a/apps/storybook/stories/Toast.stories.tsx b/apps/storybook/stories/Toast.stories.tsxindex 792f370bc1..06d7597cdf 100644--- a/apps/storybook/stories/Toast.stories.tsx+++ b/apps/storybook/stories/Toast.stories.tsx@@ -769,6 +769,60 @@ export const AppToastOverDialog: StoryObj = {},};+export const AppToastOverDialogClosedAfterSave: StoryObj = {+ render: function AppToastOverDialogClosedAfterSaveStory() {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <ToastViewport>+ <Stack gap={2}>+ <Button label="Open dialog" onClick={() => setIsOpen(true)} />+ <Dialog+ isOpen={isOpen}+ onOpenChange={() => setIsOpen(false)}+ aria-label="Edit item">+ <SaveToastContent onSaved={() => setIsOpen(false)} />+ </Dialog>+ </Stack>+ </ToastViewport>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'Save raises a toast and closes the dialog when the save finishes, as an app that waits for a request does. The toast stays on screen while the dialog closes.',+ },+ },+ },+};++/** Stands in for a request that the app waits for before it closes. */+async function saveItem(): Promise<void> {+ await new Promise<void>(resolve => {+ setTimeout(resolve, 300);+ });+}++function SaveToastContent({onSaved}: {onSaved: () => void}) {+ const toast = useToast();+ const save = async () => {+ toast({body: 'Saving the item.'});+ await saveItem();+ onSaved();+ };+ return (+ <Stack gap={3}>+ <p>Save shows a toast, then closes this dialog when the save is done.</p>+ <Button+ label="Save"+ onClick={() => {+ void save();+ }}+ />+ </Stack>+ );+}+function DialogToastContent({onClose}: {onClose: () => void}) {const toast = useToast();return (diff --git a/packages/core/src/Layer/modalOutlet.ts b/packages/core/src/Layer/modalOutlet.tsindex c68a538d0e..640ea1d652 100644--- a/packages/core/src/Layer/modalOutlet.ts+++ b/packages/core/src/Layer/modalOutlet.ts@@ -235,15 +235,19 @@ export function useModalOutlet(raiseWithinGroup(element);}, [ref, isActive, isLatest, hostKey]);- // Unmounting removes the dialog without a close event, and a passive- // cleanup runs after React has detached it. A layout cleanup runs before,- // so hosts leave while still in the document and keep their focus.+ // 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(() => {- const element = ref.current;+ if (!isActive) {+ return;+ }return () => {- if (element != null) {- removeOutlet(element);+ const supplied = suppliedRef.current;+ if (supplied != null) {+ removeOutlet(supplied);}};- }, [ref]);+ }, [isActive]);}diff --git a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx b/packages/core/src/Toast/ToastViewport.modalHost.test.tsxindex 82b5bddf98..45755bc8ec 100644--- a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx+++ b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx@@ -16,7 +16,7 @@* BottomSheet/__tests__/BottomSheetToastOutlet.a11y.chromium.spec.ts).*/-import {useState, type ReactNode} from 'react';+import {useLayoutEffect, useRef, useState, type ReactNode} from 'react';import {describe, it, expect, vi, afterEach, beforeEach} from 'vitest';import {act, fireEvent, render, screen} from '@testing-library/react';import {ToastViewport} from './ToastViewport';@@ -88,6 +88,49 @@ 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.+ */+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,+}: {+ isOpen: boolean;+ onClosingCommit: () => void;+}) {+ const wasOpenRef = useRef(false);+ useLayoutEffect(() => {+ if (wasOpenRef.current && !isOpen) {+ onClosingCommit();+ }+ wasOpenRef.current = isOpen;+ }, [isOpen, onClosingCommit]);+ return null;+}+function NonModalSheetFixture({label}: {label: string}) {const [isOpen, setIsOpen] = useState(false);return (@@ -444,6 +487,30 @@ 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>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.tsindex 40c397948b..ff48daf7d7 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@@ -2,11 +2,12 @@/*** @file ToastViewport.hostMove.interaction.browser.spec.ts- * @input The AppToastOverDialog and AppToastOverDrawer stories, recorded- * frame by frame+ * @input The AppToastOverDialog, AppToastOverDialogClosedAfterSave and+ * AppToastOverDrawer stories, recorded frame by frame* @output Tests that a toast plays its entrance once. A Dialog or a modal* Drawer that opens or closes over it moves the viewport. The toast does not- * enter again: its row and card start no transition+ * enter again: its row and card start no transition. A Dialog that closes+ * after a save does not hide the toast for a frame* @position Testing; validates ToastViewport.tsx and Toast.tsx in a real* browser*/@@ -22,6 +23,7 @@ const storybook = withStorybook(test);const STORY = 'core-toast--app-toast-over-dialog';const DRAWER_STORY = 'core-toast--app-toast-over-drawer';+const SAVE_STORY = 'core-toast--app-toast-over-dialog-closed-after-save';const MESSAGE = 'Toast from inside the dialog!';/** The toast's card on one frame. */@@ -29,6 +31,8 @@ interface Frame {opacity: number;/** Whether the card was inside a dialog, the viewport's modal outlet. */isInDialog: boolean;+ /** Whether the card had a box. A dialog that no longer displays has none. */+ hasBox: boolean;}/** What the recorder saw of the toast's card. */@@ -91,6 +95,7 @@ async function startRecording(page: Page): Promise<void> {recorder.frames.push({opacity: Number(getComputedStyle(card).opacity),isInDialog: card.closest('dialog') != null,+ hasBox: card.getClientRects().length > 0,});for (const animation of card.getAnimations()) {if (@@ -166,6 +171,37 @@ function fadesBack(frames: Frame[]): boolean {return false;}+/**+ * Counts each DOM change after which the card sits in a dialog that no longer+ * displays. A frame painted then shows no toast.+ */+async function watchHiddenCard(page: Page): Promise<void> {+ await page.evaluate(() => {+ const watch = {count: 0};+ (window as unknown as {__hiddenCard: {count: number}}).__hiddenCard = watch;+ new MutationObserver(() => {+ const dialog = document+ .querySelector('[data-toast-id] .astryx-toast')+ ?.closest('dialog');+ if (dialog != null && getComputedStyle(dialog).display === 'none') {+ watch.count += 1;+ }+ }).observe(document.body, {+ subtree: true,+ childList: true,+ attributes: true,+ attributeFilter: ['class', 'open'],+ });+ });+}++async function hiddenCardCount(page: Page): Promise<number> {+ return page.evaluate(+ () =>+ (window as unknown as {__hiddenCard: {count: number}}).__hiddenCard.count,+ );+}+async function openDialog(page: Page) {await page.getByRole('button', {name: 'Open dialog'}).click();const dialog = page.getByRole('dialog');@@ -332,4 +368,26 @@ test.describe('a toast in a top-layer viewport', () => {expect(entrances).toBe(0);expect(starts).toEqual([]);});++ 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} = 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);+ });});