Skip to content

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

TypeScript

fix(Drawer): a modal drawer hosts the toast viewport, so its toasts can be pressed and reached (#9590)

Cindy Zhangc5c11496a803
diff --git a/.changeset/drawer-modal-outlet.md b/.changeset/drawer-modal-outlet.md
new file mode 100644
index 0000000000..07e70df4f6
--- /dev/null
+++ b/.changeset/drawer-modal-outlet.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A toast shown while a modal `Drawer` is open now appears inside the drawer, above it, and can be pressed and reached with Tab, as it already does over a `Dialog` or a `BottomSheet`. Before, the toast stayed outside the drawer's modal dialog: it was inert there (a press on Undo did nothing, and Tab never reached it), and a wide drawer hid it completely. Toasts go back to the page as the drawer starts to close. A drawer without a scrim is unchanged.
+
+@cixzhang @duytbp
diff --git a/apps/storybook/stories/Toast.stories.tsx b/apps/storybook/stories/Toast.stories.tsx
index 59d2eca559..f61bb76fb2 100644
--- a/apps/storybook/stories/Toast.stories.tsx
+++ b/apps/storybook/stories/Toast.stories.tsx
@@ -17,6 +17,7 @@ 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 {Drawer} from '@astryxdesign/core/Drawer';
import {Text} from '@astryxdesign/core/Text';
import {
colorVars,
@@ -785,6 +786,52 @@ export const AppToastOverBottomSheet: StoryObj = {
},
};
+export const AppToastOverDrawer: StoryObj = {
+ render: function AppToastOverDrawerStory() {
+ const [isOpen, setIsOpen] = useState(false);
+ const [status, setStatus] = useState('The candidate is in Screening.');
+ const toast = useToast();
+ return (
+ <ToastViewport>
+ <Button label="Open candidate" onClick={() => setIsOpen(true)} />
+ <Drawer isOpen={isOpen} onOpenChange={setIsOpen} label="Candidate">
+ <Stack gap={3}>
+ <p>{status}</p>
+ <Button
+ label="Move to Interview"
+ onClick={() => {
+ setStatus('The candidate is in Interview.');
+ toast({
+ body: 'Moved to Interview',
+ isAutoHide: false,
+ endContent: (
+ <Button
+ label="Undo"
+ variant="secondary"
+ size="sm"
+ onClick={() =>
+ setStatus('The candidate is back in Screening.')
+ }
+ />
+ ),
+ });
+ }}
+ />
+ </Stack>
+ </Drawer>
+ </ToastViewport>
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "The app's own `ToastViewport` and a modal `Drawer`: while the drawer is open the viewport moves into it, so a toast fired from the drawer paints above it and its action stays clickable and reachable with Tab.",
+ },
+ },
+ },
+};
+
function SheetToastContent({openLabel}: {openLabel: string}) {
const [isOpen, setIsOpen] = useState(false);
const [status, setStatus] = useState('The item is in your inbox.');
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 2515f6f035..8a6ee9e8e2 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -398,7 +398,8 @@ separate React root under `document.body` and mirrors root theme attributes onto
it.
ToastViewport uses `popover="manual"` for top-layer promotion. Each open modal
-Dialog and each open scrim BottomSheet supplies its `<dialog>` as an outlet
+Dialog, each open modal Drawer, and each open scrim BottomSheet supplies its
+`<dialog>` as an outlet
through the private `Layer/modalOutlet.ts` registry (`spec:AST-003` FR18:
every active native modal supplies one, a covered sheet included); a modal
BottomSheetSwitcher flow supplies its active step's dialog, following each
@@ -413,7 +414,8 @@ sheet it reveals is the latest again and takes the host back; a sheet is
raised only among sheet outlets, so a Dialog opened from a sheet and
supplied later stays the latest until it closes. 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 element
+animation, but inert. A modal Drawer also releases its outlet when it starts
+closing, so toasts do not slide out with it. A top-layer viewport renders into a host element
it owns, moves that host into the latest open outlet, returns it to the
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 inside
diff --git a/docs/specs/components/Drawer/Drawer.spec.md b/docs/specs/components/Drawer/Drawer.spec.md
index 791b55d7bf..09ff0736c7 100644
--- a/docs/specs/components/Drawer/Drawer.spec.md
+++ b/docs/specs/components/Drawer/Drawer.spec.md
@@ -173,6 +173,7 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`.
| FR15 | `purpose` takes the same values and default as Dialog's prop. `info` (default) lets Escape, platform close, and a modal scrim click request close; `form` lets Escape and platform close request close and ignores scrim clicks; `required` lets none request close, registers with the shared stack as `block` so the request does not reach a lower layer, and exposes a modal drawer as `role="alertdialog"`. Without a scrim, `form` and `info` behave the same. | DEC-1; purpose suite; `family:overlay-dismissal` Escape behavior |
| FR16 | The Content area pads caller content by the drawer's container inset, `--spacing-4` by default as in Dialog, and publishes the applied inset to descendants as a container publisher would; `architecture:container-padding` does not yet admit Drawer as one (Current-state impact). Its block-end edge applies the container inset plus the home-indicator safe area while publishing the inset alone, so a bleed child subtracts only the inset and the safe area survives below it. The root dialog keeps the container-padding reset (FR12). | `architecture:container-padding`; container padding suite |
| FR17 | A Drawer open on the server renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed Drawer) and opens in the render after hydration, the first that can enter its native host; it never claims a modality it does not have (`spec:AST-020` FR1, WCAG 2.2 SC 4.1.2). The server and hydrating renders produce the same markup (`spec:AST-013` FR9), and the open after hydration is settled, with no entry motion; later opens and closes animate as usual (`spec:AST-013` FR13). | `spec:AST-020` FR1 |
+| FR18 | While a modal Drawer (`hasScrim`) is open it supplies its `<dialog>` as the passive global outlet, so app-global surfaces such as toasts render inside it, paint above it, and stay operable and reachable by keyboard; it stops supplying when it starts to close, so they return to their place and are not carried out with the exit. Moving them keeps toast entries, timers, and focus handoff (`spec:AST-003` FR18, FR19). A non-modal Drawer supplies no outlet (`architecture:layer-runtime`). | `spec:AST-003` FR18 |
### Allowed variation
@@ -310,19 +311,20 @@ block is optional during migration, so the map is deferred.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| --------------- | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
-| FR1–FR7 | `Drawer.test.tsx` render, initial-mode, click, sizing, side, and control suites | closed/open, both edges, initial modal/non-modal modes, mobile widths | Layout reflows; an initial mode gains the wrong semantics; uncanceled root-click or full-mobile sizing becomes nondeterministic. | `audit:Drawer/behavior` |
-| FR11 | Drawer source and focused keyboard composition/cancellation tests | filtered `open`, merged styling/ref, forwarded unclaimed props, owned ARIA/cancel, composed click, forwarded keydown | Current forwarding changes without review or shared-stack Escape ignores documented consumer cancellation. | `audit:Drawer/public-api` |
-| FR8, AR1–AR5 | `Drawer.test.tsx` label forwarding, autofocus, close, and focus-return suites plus the browser guard's final-focus checks | initial modal/non-modal modes, autofocus target, connected previously focused element, close listener retargeting focus | Focus moves before presentation, completed controlled close fails to restore focus, the synthetic close overrides a consumer listener's focus target, or label forwarding/dismissal naming breaks. | `audit:Drawer/accessibility` |
-| FR9, PR1–PR2 | close timing tests, browser close-visibility guard, and presence-hook source inspection | controlled close, transform end, unrelated transition, lost-event backstop | Native presentation ends before visible exit, the host is stranded, cleanup paths retain resources, or an intermediate frame paints outside native presentation. | `audit:Drawer/motion` |
-| FR10, FR13, AR3 | Drawer shared-stack suites plus `useLayerDismissal` and family tests | siblings, closing top, reopen, unmount, nested descendant | One Escape closes two surfaces, a closing host drops ownership, or a reopened sibling keeps stale order. | `audit:Drawer/layers` |
-| FR14 | Drawer source plus `spec:AST-027` impact inventory and native-host browser guard | modal host, manual-popover host, reduced fallback | Non-modal presentation returns to a page-level band or loses native-host ordering. | `audit:Drawer/layers` |
-| FR15 | `Drawer.test.tsx` purpose suite | `info`, `form`, `required`; modal and non-modal; a sibling behind a required drawer | A `form` drawer closes on a scrim click, a `required` drawer closes or lets Escape reach the drawer behind it, or its role semantics drift. | `audit:Drawer/behavior` |
-| FR12 | source, `Drawer.doc.mjs`, and current target discovery | start/end root Panel and inherited container context | Current root target/axis or padding reset changes, or the record claims an unreachable child target or decides future admission. | `audit:Drawer/theming` |
-| FR16 | `Drawer.test.tsx` container padding suites; `defineTheme.test.ts` drawer mapping; browser evidence | default, `padding` prop, theme `padding`, lone padded Section child, Layout composition | The published inset differs from the applied padding, the default drawer changes geometry, or the block-end safe area is lost or double-subtracted. | `audit:Drawer/theming` |
-| AR6 | `DrawerDirection.test.tsx` DOM-direction and closed/entry parity suites plus exact-head Storybook RTL evidence | start/end; self-applied, inherited, and nested opposite `dir`; closed and opening transforms | Any effective DOM direction or local override moves the panel from a different edge than its logical placement, or closed and opening transforms diverge. | `audit:Drawer/accessibility` |
-| FR17 | `Drawer.ssr.test.tsx` | Open on the server; hydration; a closed Drawer's markup | An open server render with `aria-modal`, open styles, or markup unlike a closed one, a hydration error, no `showModal()` after hydration, an entry motion on the open right after hydration, or none on a later open fails. | `audit:Drawer/accessibility` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
+| FR1–FR7 | `Drawer.test.tsx` render, initial-mode, click, sizing, side, and control suites | closed/open, both edges, initial modal/non-modal modes, mobile widths | Layout reflows; an initial mode gains the wrong semantics; uncanceled root-click or full-mobile sizing becomes nondeterministic. | `audit:Drawer/behavior` |
+| FR11 | Drawer source and focused keyboard composition/cancellation tests | filtered `open`, merged styling/ref, forwarded unclaimed props, owned ARIA/cancel, composed click, forwarded keydown | Current forwarding changes without review or shared-stack Escape ignores documented consumer cancellation. | `audit:Drawer/public-api` |
+| FR8, AR1–AR5 | `Drawer.test.tsx` label forwarding, autofocus, close, and focus-return suites plus the browser guard's final-focus checks | initial modal/non-modal modes, autofocus target, connected previously focused element, close listener retargeting focus | Focus moves before presentation, completed controlled close fails to restore focus, the synthetic close overrides a consumer listener's focus target, or label forwarding/dismissal naming breaks. | `audit:Drawer/accessibility` |
+| FR9, PR1–PR2 | close timing tests, browser close-visibility guard, and presence-hook source inspection | controlled close, transform end, unrelated transition, lost-event backstop | Native presentation ends before visible exit, the host is stranded, cleanup paths retain resources, or an intermediate frame paints outside native presentation. | `audit:Drawer/motion` |
+| FR10, FR13, AR3 | Drawer shared-stack suites plus `useLayerDismissal` and family tests | siblings, closing top, reopen, unmount, nested descendant | One Escape closes two surfaces, a closing host drops ownership, or a reopened sibling keeps stale order. | `audit:Drawer/layers` |
+| FR14 | Drawer source plus `spec:AST-027` impact inventory and native-host browser guard | modal host, manual-popover host, reduced fallback | Non-modal presentation returns to a page-level band or loses native-host ordering. | `audit:Drawer/layers` |
+| FR15 | `Drawer.test.tsx` purpose suite | `info`, `form`, `required`; modal and non-modal; a sibling behind a required drawer | A `form` drawer closes on a scrim click, a `required` drawer closes or lets Escape reach the drawer behind it, or its role semantics drift. | `audit:Drawer/behavior` |
+| FR12 | source, `Drawer.doc.mjs`, and current target discovery | start/end root Panel and inherited container context | Current root target/axis or padding reset changes, or the record claims an unreachable child target or decides future admission. | `audit:Drawer/theming` |
+| FR16 | `Drawer.test.tsx` container padding suites; `defineTheme.test.ts` drawer mapping; browser evidence | default, `padding` prop, theme `padding`, lone padded Section child, Layout composition | The published inset differs from the applied padding, the default drawer changes geometry, or the block-end safe area is lost or double-subtracted. | `audit:Drawer/theming` |
+| AR6 | `DrawerDirection.test.tsx` DOM-direction and closed/entry parity suites plus exact-head Storybook RTL evidence | start/end; self-applied, inherited, and nested opposite `dir`; closed and opening transforms | Any effective DOM direction or local override moves the panel from a different edge than its logical placement, or closed and opening transforms diverge. | `audit:Drawer/accessibility` |
+| FR17 | `Drawer.ssr.test.tsx` | Open on the server; hydration; a closed Drawer's markup | An open server render with `aria-modal`, open styles, or markup unlike a closed one, a hydration error, no `showModal()` after hydration, an entry motion on the open right after hydration, or none on a later open fails. | `audit:Drawer/accessibility` |
+| FR18 | `ToastViewport.modalHost.test.tsx` "ToastViewport above a Drawer" suite; `DrawerToastOutlet.a11y.chromium.spec.ts` (hit testing, click and Tab at desktop and phone widths) | modal drawer opened over a page toast; toast raised from inside the drawer; drawer closing; drawer without a scrim | A toast viewport left outside an open modal drawer, a toast carried out with the closing drawer, a remounted toast row, or a non-modal drawer that takes the viewport fails. | `audit:Drawer/accessibility` |
Read from source, with no focused test yet:
diff --git a/docs/specs/components/Toast/Toast.spec.md b/docs/specs/components/Toast/Toast.spec.md
index 231a87bb68..6e29506136 100644
--- a/docs/specs/components/Toast/Toast.spec.md
+++ b/docs/specs/components/Toast/Toast.spec.md
@@ -112,8 +112,8 @@ Consumer migration instructions belong in consumer docs and release notes.
toast that renders no control can be dismissed only by a swipe, and an error
toast does not auto-hide. `spec:AST-094` FR39 keeps every drag action
reachable without a drag.
-- **Some modals supply no outlet.** A modal Drawer, Lightbox, or MobileNav
- opens without supplying an outlet, so toasts stay behind it; `spec:AST-003`
+- **Some modals supply no outlet.** A modal Lightbox or MobileNav opens
+ without supplying an outlet, so toasts stay behind it; `spec:AST-003`
FR18 rehosts globally hosted layers above every native modal.
- **A toast collapsing through an outlet move can linger.** A toast that is
still collapsing when its viewport moves into or out of any outlet FR12
@@ -193,7 +193,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR9 | Each shown toast has one announcement owner (`spec:AST-086` FR1): the viewport announces it once, when it is shown, `error` assertively and `info` politely, using the toast's text content, through its own persistent polite and assertive containers, which move with it into a modal (`spec:AST-086` FR10). Unrelated renders do not re-announce. Implementation gaps: the viewport announces through the shared body-level channel, which a modal hides, and announces at dispatch rather than when a toast appears (Current-state impact). | `spec:AST-086`; tests |
| FR10 | F6 moves focus to the first control in the newest toast. Focus entering the viewport, by F6, Tab or a click, records where it was. Dismissing a toast that holds focus moves focus to a control in a remaining toast, or back to the remembered element when none remain. Implementation gap: with no control in the target toast, F6 leaves focus where it was and the handoff drops focus to the page (Current-state impact). | Current source and tests |
| FR11 | While a toast is visible the viewport is a `region` landmark named by `@astryx.toast.viewport`, without `aria-modal`; it exposes no landmark when empty, so an empty nested viewport adds none. Implementation gap: nested viewports that each hold a toast expose two landmarks (Current-state impact). | Current source and tests |
-| FR12 | A top-layer viewport moves into the latest open Dialog, scrim sheet, or modal flow step, following the top of a stack and handing back to the one beneath when it closes, and returns to its place when none remains, keeping each toast, its timer, and focus inside the viewport. It re-enters the top layer in place when a non-modal sheet opens after it, and stays in place when rendered in place, or when an inline dialog, a sheet without a scrim, or a non-modal flow opens. | `spec:AST-003`; tests |
+| FR12 | A top-layer viewport moves into the latest open Dialog, modal Drawer, scrim sheet, or modal flow step, following the top of a stack and handing back to the one beneath when it closes, and returns to its place when none remains, keeping each toast, its timer, and focus inside the viewport. It re-enters the top layer in place when a non-modal sheet opens after it, and stays in place when rendered in place, or when an inline dialog, a sheet without a scrim, or a non-modal flow opens. | `spec:AST-003`; tests |
### Allowed variation
@@ -260,7 +260,7 @@ button), so no anatomy part can own the `toast` target.
| FR4, FR5 | `ToastViewport.test.tsx` gesture and motion tests | Pen and touch thresholds, short drag, horizontal intent, second touch, interactive descendant, RTL | A dismissal from a rejected gesture, a lost snap-back, or off-axis drift fails. | `audit:Toast/behavior` |
| FR6–FR8 | `ToastViewport.test.tsx` placement, cap, and uniqueID tests; `Layer/LayerProvider.test.tsx` inset tests | Each position, cap 1 and an explicit cap, overwrite, ignore | Wrong order, cap, or collision fails. | `audit:Toast/layout` |
| FR9–FR11 | `ToastViewport.test.tsx` announcement, F6, focus, landmark tests | Info, error, StrictMode, nested viewports | A repeated or wrong-urgency announcement, or focus to the body after F6 entry, fails. | `audit:Toast/accessibility` |
-| FR12 | `ToastViewport.modalHost.test.tsx` | Dialog, nested dialogs, sheets and sheet stacks, modal flows | A lost toast, timer, or focus, or the wrong outlet, fails. | `audit:Toast/layering` |
+| FR12 | `ToastViewport.modalHost.test.tsx` | Dialog, nested dialogs, modal drawers, sheets and sheet stacks, modal flows | A lost toast, timer, or focus, or the wrong outlet, fails. | `audit:Toast/layering` |
Read from source, with no focused test yet:
diff --git a/packages/core/src/Drawer/Drawer.tsx b/packages/core/src/Drawer/Drawer.tsx
index 984cb93495..5bbe6bb1d5 100644
--- a/packages/core/src/Drawer/Drawer.tsx
+++ b/packages/core/src/Drawer/Drawer.tsx
@@ -77,6 +77,7 @@ import {LayerDepthProvider, useLayerDismissal} from '../Layer';
import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
+import {useModalOutlet} from '../Layer/modalOutlet';
import {layerClickBoundary} from '../Layer/layerClickBoundary';
import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {composeEventHandlers, mergeProps, themeProps} from '../utils';
@@ -497,6 +498,11 @@ export function Drawer({
setIsRendered,
});
+ // 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 handleDismiss = useCallback(() => {
onOpenChange(false);
}, [onOpenChange]);
diff --git a/packages/core/src/Drawer/__tests__/DrawerToastOutlet.a11y.chromium.spec.ts b/packages/core/src/Drawer/__tests__/DrawerToastOutlet.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..6fd556b517
--- /dev/null
+++ b/packages/core/src/Drawer/__tests__/DrawerToastOutlet.a11y.chromium.spec.ts
@@ -0,0 +1,103 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope core/Drawer core/Toast ^apps/storybook/stories/Toast
+
+/**
+ * @file DrawerToastOutlet.a11y.chromium.spec.ts
+ * @input The built Core/Toast AppToastOverDrawer story; real Chromium hit
+ * testing, mouse and keyboard input
+ * @output Browser evidence that a toast fired from an open modal Drawer is
+ * hit-testable above the drawer, takes a click, and is reached with Tab
+ * @position Chromium proof for Drawer'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, type Page} 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();
+});
+
+async function openDrawerAndToast(page: Page) {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-toast--app-toast-over-drawer&viewMode=story`,
+ );
+ await holdMotionStill(page);
+ await page.getByRole('button', {name: 'Open candidate', exact: true}).click();
+ const drawer = page.getByRole('dialog', {name: 'Candidate'});
+ await expect(drawer).toBeVisible();
+ await drawer.getByRole('button', {name: 'Move to Interview'}).click();
+ await expect(
+ drawer.getByText('The candidate is in Interview.'),
+ ).toBeVisible();
+ return drawer;
+}
+
+// Desktop: the toast's corner sits beside or under the drawer. Phone: the
+// drawer covers the whole width, so a toast left outside it is hidden.
+for (const viewport of [
+ {width: 1280, height: 800},
+ {width: 390, height: 844},
+]) {
+ test.describe(`at ${viewport.width}px`, () => {
+ test.use({viewport});
+
+ test('a toast action above a modal drawer takes the click', async ({
+ page,
+ }) => {
+ const drawer = await openDrawerAndToast(page);
+ 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 drawer's modal, or under it, loses this point to the
+ // drawer.
+ 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(
+ drawer.getByText('The candidate is back in Screening.'),
+ ).toBeVisible();
+ });
+ });
+}
+
+test('Tab reaches the toast action from inside a modal drawer', async ({
+ page,
+}) => {
+ await page.setViewportSize({width: 1280, height: 800});
+ await openDrawerAndToast(page);
+ let reached = false;
+ for (let i = 0; i < 12 && !reached; i++) {
+ await page.keyboard.press('Tab');
+ reached = await page.evaluate(
+ () => document.activeElement?.textContent === 'Undo',
+ );
+ }
+ expect(reached).toBe(true);
+});
diff --git a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
index 6dd193b4c7..cdbf1c0629 100644
--- a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
+++ b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
@@ -23,6 +23,7 @@ import {ToastViewport} from './ToastViewport';
import {useToast} from './useToast';
import {BottomSheet, BottomSheetSwitcher} from '../BottomSheet';
import {Dialog} from '../Dialog';
+import {Drawer} from '../Drawer/Drawer';
import {getActiveModalOutlet} from '../Layer/modalOutlet';
import type {ToastDismissReason} from './types';
@@ -171,6 +172,35 @@ function SheetFixture({label, hasScrim}: {label: string; hasScrim?: boolean}) {
);
}
+function DrawerFixture({
+ label,
+ hasScrim,
+ children,
+}: {
+ label: string;
+ hasScrim?: boolean;
+ children?: ReactNode;
+}) {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ {`Open ${label}`}
+ </button>
+ <Drawer
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label={label}
+ hasScrim={hasScrim}>
+ <button type="button" onClick={() => setIsOpen(false)}>
+ {`Close ${label}`}
+ </button>
+ {children}
+ </Drawer>
+ </>
+ );
+}
+
/**
* jsdom's popover stand-ins are stateless: track which elements are shown so
* `:popover-open` answers as a browser would.
@@ -667,6 +697,65 @@ describe('ToastViewport above a BottomSheet', () => {
});
});
+describe('ToastViewport above a Drawer', () => {
+ beforeEach(() => {
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+ });
+
+ it('moves into an open modal drawer and back to its place when it closes', () => {
+ const {container} = render(
+ <ToastViewport>
+ <ToastButton />
+ <DrawerFixture label="Candidate" />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
+ const toast = screen.getByText('Saved');
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open Candidate'}));
+ expect(getViewport().closest('dialog')).toBe(getDialog('Candidate'));
+ expect(getActiveModalOutlet()).toBe(getDialog('Candidate'));
+ // Same node: the rows were moved, not remounted.
+ expect(screen.getByText('Saved')).toBe(toast);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close Candidate'}));
+ // The drawer stops supplying as soon as it starts to close, so toasts do
+ // not slide out with it.
+ expect(getViewport().closest('dialog')).toBeNull();
+ expect(container.contains(getViewport())).toBe(true);
+ expect(screen.getByText('Saved')).toBe(toast);
+ });
+
+ it('hosts a toast raised from inside it', () => {
+ render(
+ <ToastViewport>
+ <DrawerFixture label="Candidate">
+ <ToastButton label="Move to Interview" />
+ </DrawerFixture>
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open Candidate'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Move to Interview'}));
+ expect(screen.getByText('Saved').closest('dialog')).toBe(
+ getDialog('Candidate'),
+ );
+ });
+
+ it('stays in place when a drawer without a scrim opens', () => {
+ trackPopoverState();
+ const {container} = render(
+ <ToastViewport>
+ <DrawerFixture label="Candidate" hasScrim={false} />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open Candidate'}));
+ // A non-modal drawer leaves the page operable, so it supplies no outlet.
+ expect(getViewport().closest('dialog')).toBeNull();
+ expect(container.contains(getViewport())).toBe(true);
+ expect(getActiveModalOutlet()).toBeNull();
+ });
+});
+
describe('ToastViewport above a BottomSheetSwitcher flow', () => {
function finishHandoff(entering: HTMLElement, retained: HTMLElement) {
for (const panel of Array.from(