An open source design system that's fully customizable and agent ready
TypeScript
fix(BottomSheet): keep toasts visible and clickable above an open sheet (#7781)
Christopher Chedeau7cb897b4ec3d
diff --git a/.changeset/bottom-sheet-toast-outlet.md b/.changeset/bottom-sheet-toast-outlet.mdnew file mode 100644index 0000000000..f6d7fe0ba4--- /dev/null+++ b/.changeset/bottom-sheet-toast-outlet.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Toasts stay visible and clickable above an open BottomSheet. The `ToastViewport` from `LayerProvider` (or the one `useToast` mounts on its own) now moves into a standalone BottomSheet while it is open, as it already does into an open Dialog, and back as soon as the sheet starts closing. Before, the sheet covered the viewport and made it inert, so a click on a toast's action landed on the sheet instead and could dismiss it. A sheet with `hasScrim={false}` is not modal and leaves the viewport in place. Sheets inside a `BottomSheetSwitcher` are unchanged.++@vjeuxdiff --git a/apps/storybook/stories/Toast.stories.tsx b/apps/storybook/stories/Toast.stories.tsxindex 002fa57cb7..59d2eca559 100644--- a/apps/storybook/stories/Toast.stories.tsx+++ b/apps/storybook/stories/Toast.stories.tsx@@ -16,6 +16,7 @@ import {Card} from '@astryxdesign/core/Card';import {Stack} from '@astryxdesign/core/Stack';import {Heading} from '@astryxdesign/core/Text';import {Dialog} from '@astryxdesign/core/Dialog';+import {BottomSheet} from '@astryxdesign/core/BottomSheet';import {Text} from '@astryxdesign/core/Text';import {colorVars,@@ -755,6 +756,72 @@ function DialogToastContent({onClose}: {onClose: () => void}) {);}+export const AppToastOverBottomSheet: StoryObj = {+ render: function AppToastOverBottomSheetStory() {+ const [isDialogOpen, setIsDialogOpen] = useState(false);+ return (+ // Toasts at the top, clear of the sheet rising from the bottom.+ <ToastViewport position="topEnd">+ <Stack gap={2}>+ <SheetToastContent openLabel="Open sheet" />+ <Button label="Open dialog" onClick={() => setIsDialogOpen(true)} />+ <Dialog+ isOpen={isDialogOpen}+ onOpenChange={() => setIsDialogOpen(false)}+ aria-label="Edit item">+ <SheetToastContent openLabel="Open sheet from the dialog" />+ </Dialog>+ </Stack>+ </ToastViewport>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ "The app's own `ToastViewport` and a `BottomSheet`, opened on its own or from a dialog: while the sheet is open the viewport moves into it, so a toast fired from the sheet paints above it and its action stays clickable.",+ },+ },+ },+};++function SheetToastContent({openLabel}: {openLabel: string}) {+ const [isOpen, setIsOpen] = useState(false);+ const [status, setStatus] = useState('The item is in your inbox.');+ const toast = useToast();+ return (+ <>+ <Button label={openLabel} onClick={() => setIsOpen(true)} />+ <BottomSheet+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ label="Item actions">+ <Stack gap={3}>+ <p>{status}</p>+ <Button+ label="Archive"+ onClick={() => {+ setStatus('The item is archived.');+ toast({+ body: 'Item archived',+ isAutoHide: false,+ endContent: (+ <Button+ label="Undo"+ variant="secondary"+ size="sm"+ onClick={() => setStatus('The item is back in your inbox.')}+ />+ ),+ });+ }}+ />+ </Stack>+ </BottomSheet>+ </>+ );+}+// =============================================================================// Theming// =============================================================================diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex 79852f4bc7..7c13e10f55 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -313,11 +313,13 @@ separate React root under `document.body` and mirrors root theme attributes ontoit.ToastViewport uses `popover="manual"` for top-layer promotion. Each open modal-Dialog supplies its `<dialog>` as an outlet through the private-`Layer/modalOutlet.ts` registry. A top-layer viewport renders into a host element+Dialog and each open scrim BottomSheet supplies its `<dialog>` as an outlet+through the private `Layer/modalOutlet.ts` registry. A BottomSheet releases its+outlet when it starts closing: its dialog stays modal through the exit+animation, but inert. A top-layer viewport renders into a host elementit owns, moves that host into the latest open outlet, returns it to the-viewport's tree position when no Dialog is open, and enters the top layer again-after each move. Toasts therefore paint above the Dialog and stay operable inside+viewport's tree position when no outlet is open, and enters the top layer again+after each move. Toasts therefore paint above the modal and stay operable insideit. Moving the host does not remount the rows, so entries, timers, and focushandoff survive. Toast state lives inside the viewport. A viewport rendered with`isTopLayer={false}` stays in place.@@ -393,7 +395,7 @@ Current gaps are observable facts, not current target behavior:- Backdrop, manual outside, touch, and swipe paths do not share the existinggesture claim or one association model.- Toast's root and fallback hosts remain behind the other native modals:- Lightbox, MobileNav, and a scrim BottomSheet or BottomSheetSwitcher.+ Lightbox, MobileNav, and a scrim BottomSheetSwitcher.- The reduced browser fallback is not documented as non-equivalent.- Existing tests simulate Popover `toggle` and DOM nesting; they do not provenative pointer light dismissal, top-layer/modal ordering, real anchor geometry,diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsxindex 3ecca09133..12e49da63c 100644--- a/packages/core/src/BottomSheet/BottomSheet.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.tsx@@ -4,7 +4,7 @@/*** @file BottomSheet.tsx- * @input Uses React, StyleX, core hooks, shared layer dismissal, the shared interaction modality, named BottomSheetPanel, BottomSheetSwitcherContext+ * @input Uses React, StyleX, core hooks, shared layer dismissal, the modal outlet registry, the shared interaction modality, named BottomSheetPanel, BottomSheetSwitcherContext* @output Exports BottomSheet component and BottomSheetProps* @position Public BottomSheet router plus private standalone/switcher hosts*@@ -27,6 +27,9 @@* in a switcher, handing one scrim between two dialogs and keeping focus in* the active sheet when a retained dialog closes.*+ * While a standalone modal sheet is open, its dialog is the outlet that+ * app-global surfaces (toasts) render into (Layer/modalOutlet.ts).+ ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/BottomSheet/BottomSheetPanel.tsx* - /packages/core/src/BottomSheet/BottomSheetEdgeTint.tsx@@ -36,6 +39,7 @@* - /packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx* - /packages/core/src/Layer/layerDismissalFamilies.test.tsx* - /packages/core/src/Layer/layerDismissalInvariants.test.tsx+ * - /packages/core/src/Toast/ToastViewport.modalHost.test.tsx* - /apps/storybook/stories/BottomSheet.stories.tsx* - /packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetShowcase.tsx*/@@ -58,6 +62,7 @@ import {colorVars, durationVars, easeVars} from '../theme/tokens.stylex';import {useDevWarning, useScrollLock} from '../hooks';import {mergeProps} from '../utils';import {LayerDepthProvider} from '../Layer/LayerDepthContext';+import {useModalOutlet} from '../Layer/modalOutlet';import {useLayerDismissal} from '../Layer/useLayerDismissal';import {focusForLastInput} from '../utils/focusReturn';import {useInteractionModalityTracking} from '../utils/interactionModality';@@ -373,6 +378,12 @@ function StandaloneBottomSheet({}}, [hasScrim, isOpen]);+ // Host app-global surfaces (toasts) inside this sheet while it is an open+ // modal, so they stay visible and operable above it. A closing sheet stays+ // modal through its exit animation, but inert and hidden, so it hands them+ // back as soon as it starts closing.+ useModalOutlet(dialogRef, isOpen && hasScrim);+useEffect(() => {if (!isOpen && isPresented && hasScrim) {handleScrimOpacity(0);diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetToastOutlet.a11y.chromium.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetToastOutlet.a11y.chromium.spec.tsnew file mode 100644index 0000000000..c024fa7792--- /dev/null+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetToastOutlet.a11y.chromium.spec.ts@@ -0,0 +1,82 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BottomSheetToastOutlet.a11y.chromium.spec.ts+ * @input The built Core/Toast AppToastOverBottomSheet story; real Chromium hit+ * testing and mouse input+ * @output Browser evidence that a toast fired from an open BottomSheet, on its+ * own or over a Dialog, is hit-testable above the sheet and takes a click+ * @position Chromium proof for BottomSheet's modal outlet+ * (Layer/modalOutlet.ts). jsdom has no top layer and no modal inertness, so+ * Toast/ToastViewport.modalHost.test.tsx can only check where the viewport+ * lives.+ */++import {expect, test} from '@playwright/test';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++// Phone width: where an app presents its dialogs as bottom sheets.+test.use({viewport: {width: 390, height: 844}});++const SCENARIOS = [+ {name: 'on its own', opens: ['Open sheet']},+ {name: 'over a Dialog', opens: ['Open dialog', 'Open sheet from the dialog']},+];++for (const {name, opens} of SCENARIOS) {+ test(`a toast action above a sheet opened ${name} takes the click`, async ({+ page,+ }) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-toast--app-toast-over-bottom-sheet&viewMode=story`,+ );+ await holdMotionStill(page);+ for (const label of opens) {+ await page.getByRole('button', {name: label, exact: true}).click();+ }+ const sheet = page.getByRole('dialog', {name: 'Item actions'});+ await expect(sheet).toBeVisible();+ await sheet.getByRole('button', {name: 'Archive'}).click();+ await expect(sheet.getByText('The item is archived.')).toBeVisible();++ const undo = page.locator('[popover] button', {hasText: 'Undo'});+ await expect(undo).toBeVisible();+ const box = await undo.boundingBox();+ if (box == null) {+ throw new Error('the Undo button has no box');+ }+ const x = box.x + box.width / 2;+ const y = box.y + box.height / 2;++ // Hit testing skips inert content and follows top-layer order: a toast+ // left outside the sheet's modal, or under it, loses this point to the+ // sheet.+ const hit = await page.evaluate(+ ([px, py]) =>+ document.elementFromPoint(px, py)?.closest('button')?.textContent ??+ null,+ [x, y],+ );+ expect(hit).toBe('Undo');++ await page.mouse.click(x, y);+ await expect(+ sheet.getByText('The item is back in your inbox.'),+ ).toBeVisible();+ });+}diff --git a/packages/core/src/Layer/modalOutlet.ts b/packages/core/src/Layer/modalOutlet.tsindex 3a4733c44d..41e46ebe74 100644--- a/packages/core/src/Layer/modalOutlet.ts+++ b/packages/core/src/Layer/modalOutlet.ts@@ -4,7 +4,7 @@/*** @file modalOutlet.ts- * @input The open Dialog `<dialog>` elements+ * @input The open Dialog and scrim BottomSheet `<dialog>` elements* @output Exports useModalOutlet (a modal supplies its outlet),* getActiveModalOutlet, and subscribeModalOutlets (a global host follows* the latest one)diff --git a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx b/packages/core/src/Toast/ToastViewport.modalHost.test.tsxindex 5d3471325d..e4588c541d 100644--- a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx+++ b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx@@ -2,14 +2,17 @@/*** @file ToastViewport.modalHost.test.tsx- * @input Uses vitest, @testing-library/react, ToastViewport, useToast, Dialog+ * @input Uses vitest, @testing-library/react, ToastViewport, useToast, Dialog,+ * BottomSheet* @output Tests that a top-layer ToastViewport moves into the latest open- * native modal and back without remounting its toasts+ * native modal (a Dialog or a scrim BottomSheet) and back without remounting+ * its toasts* @position Testing; validates ToastViewport.tsx with Layer/modalOutlet.ts** SYNC: When ToastViewport hosting or Layer/modalOutlet.ts changes, update* these tests. jsdom has no top layer: paint order and hit testing above the- * modal need a real browser (see the Core/Toast AppToastOverDialog story).+ * modal need a real browser (see the Core/Toast AppToastOverDialog story and+ * BottomSheet/__tests__/BottomSheetToastOutlet.a11y.chromium.spec.ts).*/import {useState, type ReactNode} from 'react';@@ -17,16 +20,20 @@ import {describe, it, expect, vi, afterEach, beforeEach} from 'vitest';import {act, fireEvent, render, screen} from '@testing-library/react';import {ToastViewport} from './ToastViewport';import {useToast} from './useToast';+import {BottomSheet} from '../BottomSheet';import {Dialog} from '../Dialog';import type {ToastDismissReason} from './types';-// jsdom does not implement the native modal methods.+// jsdom does not implement the native dialog methods.beforeEach(() => {HTMLDialogElement.prototype.showModal = vi.fn(function (this: HTMLDialogElement,) {this.setAttribute('open', '');});+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {+ this.setAttribute('open', '');+ });HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {this.removeAttribute('open');});@@ -78,6 +85,19 @@ function getViewport(): HTMLElement {return document.querySelector<HTMLElement>('[popover="manual"]')!;}+/** Call order of `fn`'s latest call on `context`, or -1 if it has none. */+function lastCallOrder(+ fn: {mock: {contexts: unknown[]; invocationCallOrder: number[]}},+ context: unknown,+): number {+ return Math.max(+ -1,+ ...fn.mock.invocationCallOrder.filter(+ (_, index) => fn.mock.contexts[index] === context,+ ),+ );+}+function TimedToastButton({onHide,}: {@@ -109,6 +129,26 @@ function UnmountFixture() {);}+function SheetFixture({label, hasScrim}: {label: string; hasScrim?: boolean}) {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <button type="button" onClick={() => setIsOpen(true)}>+ {`Open ${label}`}+ </button>+ <BottomSheet+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ label={label}+ hasScrim={hasScrim}>+ <button type="button" onClick={() => setIsOpen(false)}>+ {`Close ${label}`}+ </button>+ </BottomSheet>+ </>+ );+}+describe('ToastViewport modal hosting', () => {it('moves into an open Dialog and back when it closes, keeping the toast', () => {const {container} = render(@@ -264,3 +304,98 @@ describe('ToastViewport modal hosting', () => {expect(container.contains(viewport)).toBe(true);});});++describe('ToastViewport above a BottomSheet', () => {+ beforeEach(() => {+ // Closing the sheet releases its scroll lock, which restores the scroll+ // position; jsdom does not implement scrolling.+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});+ });++ it('moves into an open scrim sheet and back to its place when it closes', () => {+ const {container} = render(+ <ToastViewport>+ <ToastButton />+ <SheetFixture label="Filters" />+ </ToastViewport>,+ );+ fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));+ const toast = screen.getByText('Saved');++ fireEvent.click(screen.getByRole('button', {name: 'Open Filters'}));+ expect(getViewport().closest('dialog')).toBe(getDialog('Filters'));+ expect(screen.getByText('Saved')).toBe(toast);++ fireEvent.click(screen.getByRole('button', {name: 'Close Filters'}));+ expect(getViewport().closest('dialog')).toBeNull();+ expect(container.contains(getViewport())).toBe(true);+ expect(screen.getByText('Saved')).toBe(toast);+ });++ it('follows a sheet opened over a Dialog, above it in the top layer', () => {+ const showPopover = vi.spyOn(HTMLElement.prototype, 'showPopover');+ render(+ <ToastViewport>+ <DialogFixture label="Edit">+ <SheetFixture label="Filters" />+ </DialogFixture>+ </ToastViewport>,+ );+ const viewport = getViewport();+ const showsOnViewport = () =>+ showPopover.mock.contexts.filter(context => context === viewport).length;++ fireEvent.click(screen.getByRole('button', {name: 'Toggle Edit'}));+ expect(viewport.closest('dialog')).toBe(getDialog('Edit'));+ const showsInDialog = showsOnViewport();++ fireEvent.click(screen.getByRole('button', {name: 'Open Filters'}));+ // The sheet's modal makes everything outside it inert, the Dialog+ // included, so the viewport has to be inside the sheet.+ expect(viewport.closest('dialog')).toBe(getDialog('Filters'));+ expect(viewport.closest('[inert]')).toBeNull();+ // Shown again once the sheet is in the top layer, so it paints above it.+ expect(showsOnViewport()).toBe(showsInDialog + 1);+ expect(lastCallOrder(showPopover, viewport)).toBeGreaterThan(+ lastCallOrder(+ vi.mocked(HTMLDialogElement.prototype.showModal),+ getDialog('Filters'),+ ),+ );+ });++ it('returns to the Dialog as soon as the sheet starts closing', () => {+ render(+ <ToastViewport>+ <DialogFixture label="Edit">+ <SheetFixture label="Filters" />+ </DialogFixture>+ </ToastViewport>,+ );+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Edit'}));+ fireEvent.click(screen.getByRole('button', {name: 'Open Filters'}));+ const viewport = getViewport();+ expect(viewport.closest('dialog')).toBe(getDialog('Filters'));++ fireEvent.click(screen.getByRole('button', {name: 'Close Filters'}));+ // The sheet stays an open modal through its exit animation, but inert and+ // hidden; toasts must not go down with it.+ expect(getDialog('Filters')).toHaveAttribute('open');+ expect(getDialog('Filters')).toHaveAttribute('inert');+ expect(viewport.closest('dialog')).toBe(getDialog('Edit'));+ expect(viewport.closest('[inert], [aria-hidden="true"]')).toBeNull();+ });++ it('stays in place when a sheet without a scrim opens', () => {+ const {container} = render(+ <ToastViewport>+ <SheetFixture label="Filters" hasScrim={false} />+ </ToastViewport>,+ );+ fireEvent.click(screen.getByRole('button', {name: 'Open Filters'}));+ // A non-modal sheet leaves the page operable, so the viewport stays put.+ expect(getDialog('Filters')).toHaveAttribute('open');+ expect(getViewport().closest('dialog')).toBeNull();+ expect(container.contains(getViewport())).toBe(true);+ });+});