Skip to content

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

TypeScript

fix(Toast): keep toasts visible and clickable above an open Dialog (#7238)

ksying4607f2fbcbce
diff --git a/.changeset/toast-viewport-modal-outlet.md b/.changeset/toast-viewport-modal-outlet.md
new file mode 100644
index 0000000000..31738345a1
--- /dev/null
+++ b/.changeset/toast-viewport-modal-outlet.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Toasts stay visible and clickable while a Dialog is open. The `ToastViewport` from `LayerProvider` (or the one `useToast` mounts on its own) now moves into the open Dialog, and back when it closes. Before, a Dialog opened after the viewport mounted painted over it, and clicking a toast's close button hit the backdrop and closed the Dialog. Moving the viewport does not reset visible toasts or their timers. A viewport rendered with `isTopLayer={false}` keeps rendering in place.
+
+@ksying
diff --git a/apps/storybook/stories/Toast.stories.tsx b/apps/storybook/stories/Toast.stories.tsx
index 3fd2a44eb2..002fa57cb7 100644
--- a/apps/storybook/stories/Toast.stories.tsx
+++ b/apps/storybook/stories/Toast.stories.tsx
@@ -703,14 +703,38 @@ export const ToastOverDialog: StoryObj = {
},
};
+export const AppToastOverDialog: StoryObj = {
+ render: function AppToastOverDialogStory() {
+ 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">
+ <DialogToastContent onClose={() => setIsOpen(false)} />
+ </Dialog>
+ </Stack>
+ </ToastViewport>
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "The app's own `ToastViewport` and no viewport in the dialog: while the dialog is open the viewport moves into it, so toasts fired from inside paint above the overlay and stay clickable.",
+ },
+ },
+ },
+};
+
function DialogToastContent({onClose}: {onClose: () => void}) {
const toast = useToast();
return (
<Stack gap={3}>
- <p>
- This dialog has its own toast viewport. Toasts fired here render inside
- the dialog, above its overlay.
- </p>
+ <p>Toasts fired here render inside the dialog, above its overlay.</p>
<Stack direction="horizontal" gap={2} wrap="wrap">
<Button label="Close" variant="secondary" onClick={onClose} />
<Button
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 228a13beb9..750ffcc37d 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -39,6 +39,7 @@ verified_by:
packages/core/src/hooks/useFocusTrap.test.tsx,
packages/core/src/hooks/useMenuHover.test.tsx,
packages/core/src/Toast/ToastViewport.test.tsx,
+ packages/core/src/Toast/ToastViewport.modalHost.test.tsx,
]
deciding_specs: [spec:AST-038, spec:AST-059]
---
@@ -313,10 +314,15 @@ general portal host for all layers. Without a provider, `useToast` creates a
separate React root under `document.body` and mirrors root theme attributes onto
it.
-ToastViewport uses `popover="manual"` for top-layer promotion and documents an
-above-dialog intent. A body-level manual popover remains behind an active native
-modal, so the current root/fallback host does not fulfill that intent. Toast
-state also lives inside the viewport.
+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
+it 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
+it. Moving the host does not remount the rows, so entries, timers, and focus
+handoff survive. Toast state lives inside the viewport. A viewport rendered with
+`isTopLayer={false}` stays in place.
CommandPalette composes native Dialog. Its normal launcher presentation therefore
uses `showModal()`; its documentation/showcase `isInline` path does not. It
@@ -386,7 +392,8 @@ Current gaps are observable facts, not current target behavior:
nested child branch through shared infrastructure.
- Backdrop, manual outside, touch, and swipe paths do not share the existing
gesture claim or one association model.
-- Toast's root and fallback hosts remain behind active native modals.
+- Toast's root and fallback hosts remain behind the other native modals:
+ Lightbox, MobileNav, and a scrim BottomSheet or BottomSheetSwitcher.
- CommandPalette's local Escape handler bypasses shared owner selection.
- The reduced browser fallback is not documented as non-equivalent.
- Existing tests simulate Popover `toggle` and DOM nesting; they do not prove
@@ -491,7 +498,7 @@ this current architecture record.
| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |
| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |
| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests | A current local channel silently changes ownership or policy |
-| INV10 | `LayerProvider.tsx`, `LayerProvider.test.tsx`, `useToast.tsx`, and `ToastViewport.test.tsx` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, or a default provider renders differently from no provider |
+| INV10 | `LayerProvider.tsx`, `LayerProvider.test.tsx`, `useToast.tsx`, `ToastViewport.test.tsx`, and `ToastViewport.modalHost.test.tsx` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, or a default provider renders differently from no provider |
Current unit coverage proves emitted styles, reducers, state transitions, and DOM
placement. Native Popover, `<dialog>`, focus, top-layer ordering, and rendered
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index f3898e68f5..91ed97e99d 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -4,7 +4,8 @@
/**
* @file Dialog.tsx
- * @input Uses React, DialogHTMLAttributes, ReactNode, container (Layout), DialogContext, layerTextReset, layerStructureReset
+ * @input Uses React, DialogHTMLAttributes, ReactNode, container (Layout), DialogContext, layerTextReset,
+ * layerStructureReset, modalOutlet
* @output Exports Dialog component, DialogProps, DialogVariant, DialogPurpose types
* @position Core implementation; consumed by index.ts, tested by Dialog.test.tsx
*
@@ -39,6 +40,7 @@ import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
+import {useModalOutlet} from '../Layer/modalOutlet';
import {
colorVars,
radiusVars,
@@ -551,6 +553,10 @@ export function Dialog({
}
}, [isOpen, isInline]);
+ // Host app-global surfaces (toasts) inside this modal while it is open, so
+ // they stay visible and operable above it.
+ useModalOutlet(dialogRef, isOpen && !isInline);
+
// Lock body scroll when dialog is open (iOS Safari workaround)
// Skip for inline rendering — no modal overlay to compensate for.
useScrollLock(isOpen && !isInline);
diff --git a/packages/core/src/Layer/modalOutlet.ts b/packages/core/src/Layer/modalOutlet.ts
new file mode 100644
index 0000000000..3a4733c44d
--- /dev/null
+++ b/packages/core/src/Layer/modalOutlet.ts
@@ -0,0 +1,106 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file modalOutlet.ts
+ * @input The open Dialog `<dialog>` elements
+ * @output Exports useModalOutlet (a modal supplies its outlet),
+ * getActiveModalOutlet, and subscribeModalOutlets (a global host follows
+ * the latest one)
+ * @position Private layer infrastructure; spec:AST-003 FR18
+ *
+ * A native modal makes everything outside it inert and paints over every
+ * earlier top-layer element. A passive global host (ToastViewport) therefore
+ * has to live in the DOM of the latest open modal to stay visible and
+ * operable. The registry is module-level because the top layer is
+ * document-wide: a host rendered in a separate React root (the useToast
+ * fallback) must see modals rendered by the app. Listeners run synchronously,
+ * so a host can leave a modal before React removes it from the document.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Toast/ToastViewport.modalHost.test.tsx
+ * - /docs/architecture/layer-runtime.md
+ */
+
+import {useEffect, useLayoutEffect, type RefObject} from 'react';
+
+const outlets: HTMLDialogElement[] = [];
+const listeners = new Set<() => void>();
+
+function notify(): void {
+ for (const listener of listeners) {
+ listener();
+ }
+}
+
+function addOutlet(element: HTMLDialogElement): void {
+ const index = outlets.indexOf(element);
+ if (index !== -1) {
+ outlets.splice(index, 1);
+ }
+ outlets.push(element);
+ notify();
+}
+
+function removeOutlet(element: HTMLDialogElement): void {
+ const index = outlets.indexOf(element);
+ if (index === -1) {
+ return;
+ }
+ outlets.splice(index, 1);
+ notify();
+}
+
+/** The latest open native modal, or null when none is open. */
+export function getActiveModalOutlet(): HTMLDialogElement | null {
+ return outlets[outlets.length - 1] ?? null;
+}
+
+/** Call `listener` whenever the latest open native modal may have changed. */
+export function subscribeModalOutlets(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/**
+ * Supply `ref`'s `<dialog>` as the passive global outlet while it is an open
+ * modal. Call it after the effect that runs `showModal()`, so the modal is
+ * already in the top layer when global hosts move into it.
+ */
+export function useModalOutlet(
+ ref: RefObject<HTMLDialogElement | null>,
+ isActive: boolean,
+): void {
+ useEffect(() => {
+ const element = ref.current;
+ if (!isActive || element == null) {
+ return;
+ }
+ // A native close (a `method="dialog"` form) ends the modal without a
+ // render.
+ const handleClose = () => {
+ removeOutlet(element);
+ };
+ element.addEventListener('close', handleClose);
+ addOutlet(element);
+ return () => {
+ element.removeEventListener('close', handleClose);
+ removeOutlet(element);
+ };
+ }, [ref, isActive]);
+
+ // 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.
+ useLayoutEffect(() => {
+ const element = ref.current;
+ return () => {
+ if (element != null) {
+ removeOutlet(element);
+ }
+ };
+ }, [ref]);
+}
diff --git a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
new file mode 100644
index 0000000000..5d3471325d
--- /dev/null
+++ b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
@@ -0,0 +1,266 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ToastViewport.modalHost.test.tsx
+ * @input Uses vitest, @testing-library/react, ToastViewport, useToast, Dialog
+ * @output Tests that a top-layer ToastViewport moves into the latest open
+ * native modal 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).
+ */
+
+import {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';
+import {useToast} from './useToast';
+import {Dialog} from '../Dialog';
+import type {ToastDismissReason} from './types';
+
+// jsdom does not implement the native modal methods.
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function ToastButton({label = 'Show toast'}: {label?: string}) {
+ const toast = useToast();
+ return (
+ <button type="button" onClick={() => toast({body: 'Saved'})}>
+ {label}
+ </button>
+ );
+}
+
+function DialogFixture({
+ label,
+ children,
+}: {
+ label: string;
+ children?: ReactNode;
+}) {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(open => !open)}>
+ {`Toggle ${label}`}
+ </button>
+ <Dialog isOpen={isOpen} onOpenChange={setIsOpen} aria-label={label}>
+ <button type="button" onClick={() => setIsOpen(false)}>
+ {`Close ${label}`}
+ </button>
+ {children}
+ </Dialog>
+ </>
+ );
+}
+
+function getDialog(label: string): HTMLDialogElement {
+ return document.querySelector<HTMLDialogElement>(
+ `dialog[aria-label="${label}"]`,
+ )!;
+}
+
+function getViewport(): HTMLElement {
+ return document.querySelector<HTMLElement>('[popover="manual"]')!;
+}
+
+function TimedToastButton({
+ onHide,
+}: {
+ onHide: (reason: ToastDismissReason) => void;
+}) {
+ const toast = useToast();
+ return (
+ <button
+ type="button"
+ onClick={() => toast({body: 'Saved', autoHideDuration: 5000, onHide})}>
+ Show timed toast
+ </button>
+ );
+}
+
+function UnmountFixture() {
+ const [isMounted, setIsMounted] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setIsMounted(false)}>
+ Unmount
+ </button>
+ {isMounted ? (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Edit">
+ <ToastButton />
+ </Dialog>
+ ) : null}
+ </>
+ );
+}
+
+describe('ToastViewport modal hosting', () => {
+ it('moves into an open Dialog and back when it closes, keeping the toast', () => {
+ const {container} = render(
+ <ToastViewport>
+ <ToastButton />
+ <DialogFixture label="Edit" />
+ </ToastViewport>,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
+ const toast = screen.getByText('Saved');
+ expect(container.contains(getViewport())).toBe(true);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Edit'}));
+ expect(getDialog('Edit').contains(getViewport())).toBe(true);
+ // Same node: the rows were moved, not remounted, so their auto-hide
+ // timers and gesture state carry on.
+ expect(screen.getByText('Saved')).toBe(toast);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close Edit'}));
+ expect(getDialog('Edit').contains(getViewport())).toBe(false);
+ expect(container.contains(getViewport())).toBe(true);
+ expect(screen.getByText('Saved')).toBe(toast);
+ });
+
+ it('shows the viewport popover again after each move', () => {
+ const showPopover = vi.spyOn(HTMLElement.prototype, 'showPopover');
+ render(
+ <ToastViewport>
+ <DialogFixture label="Edit" />
+ </ToastViewport>,
+ );
+ const viewport = getViewport();
+ const showsOnViewport = () =>
+ showPopover.mock.contexts.filter(context => context === viewport).length;
+ expect(showsOnViewport()).toBe(1);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Edit'}));
+ expect(showsOnViewport()).toBe(2);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close Edit'}));
+ expect(showsOnViewport()).toBe(3);
+ });
+
+ it("keeps each toast's auto-hide timer running across a move", () => {
+ vi.useFakeTimers();
+ try {
+ const onHide = vi.fn();
+ render(
+ <ToastViewport>
+ <TimedToastButton onHide={onHide} />
+ <DialogFixture label="Edit" />
+ </ToastViewport>,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Show timed toast'}));
+ act(() => {
+ vi.advanceTimersByTime(3000);
+ });
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Edit'}));
+ expect(getDialog('Edit').contains(getViewport())).toBe(true);
+ act(() => {
+ vi.advanceTimersByTime(2500);
+ });
+ // A remount would have restarted the 5s timer at the move.
+ expect(onHide).toHaveBeenCalledWith('auto');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('returns when the dialog closes natively while React holds it open', () => {
+ const {container} = render(
+ <ToastViewport>
+ <DialogFixture label="Edit" />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Edit'}));
+ const dialog = getDialog('Edit');
+ expect(dialog.contains(getViewport())).toBe(true);
+
+ act(() => {
+ dialog.removeAttribute('open');
+ dialog.dispatchEvent(new Event('close'));
+ });
+ expect(container.contains(getViewport())).toBe(true);
+ });
+
+ it('follows the latest open modal through nested dialogs', () => {
+ render(
+ <ToastViewport>
+ <DialogFixture label="Outer">
+ <DialogFixture label="Inner" />
+ </DialogFixture>
+ </ToastViewport>,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Outer'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Inner'}));
+ expect(getDialog('Inner').contains(getViewport())).toBe(true);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close Inner'}));
+ expect(getDialog('Inner').contains(getViewport())).toBe(false);
+ expect(getDialog('Outer').contains(getViewport())).toBe(true);
+ });
+
+ it('returns to its place when the open Dialog unmounts', () => {
+ const {container} = render(
+ <ToastViewport>
+ <UnmountFixture />
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
+ const toast = screen.getByText('Saved');
+ const dismiss = getViewport().querySelector('button')!;
+ dismiss.focus();
+
+ act(() => {
+ fireEvent.click(screen.getByRole('button', {name: 'Unmount'}));
+ });
+ expect(container.contains(getViewport())).toBe(true);
+ expect(screen.getByText('Saved')).toBe(toast);
+ // jsdom does not blur a moved node, so this guards only the end state;
+ // the browser blur is handled by ToastViewport's focus restore.
+ expect(document.activeElement).toBe(dismiss);
+ });
+
+ it('stays in place when the caller renders it in place', () => {
+ render(
+ <DialogFixture label="Edit">
+ <ToastViewport isTopLayer={false}>
+ <ToastButton />
+ </ToastViewport>
+ </DialogFixture>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Edit'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
+ expect(getDialog('Edit').contains(screen.getByText('Saved'))).toBe(true);
+ expect(document.querySelector('[popover="manual"]')).toBeNull();
+ });
+
+ it('does not move into an inline Dialog', () => {
+ const {container} = render(
+ <ToastViewport>
+ <Dialog isOpen isInline onOpenChange={() => {}} aria-label="Preview">
+ <ToastButton />
+ </Dialog>
+ </ToastViewport>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
+ const viewport = getViewport();
+ expect(viewport.closest('[aria-label="Preview"]')).toBeNull();
+ expect(container.contains(viewport)).toBe(true);
+ });
+});
diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsx
index 32bd28e73f..7202d40827 100644
--- a/packages/core/src/Toast/ToastViewport.tsx
+++ b/packages/core/src/Toast/ToastViewport.tsx
@@ -5,13 +5,13 @@
/**
* @file ToastViewport.tsx
* @input Uses React state/effects, ToastContext, content-provider boundary, useAnnounce, viewport tokens,
- * shared layer text reset, and placement-derived motion variables
+ * shared layer text reset, the active modal outlet, and placement-derived motion variables
* @output Exports the ToastViewport provider, stack, live announcement dispatch,
- * focus handoff, safe-area-aware edge gutters, and motion context
+ * focus handoff, safe-area-aware edge gutters, modal rehosting, and motion context
* @position Core provider/imperative viewport for useToast()
*
- * SYNC: When placement, stacking, focus, announcement, or safe-area behavior
- * changes, update ToastViewport.test.tsx, Toast.doc.mjs, and Toast.stories.tsx.
+ * SYNC: When placement, stacking, hosting, focus, announcement, or safe-area
+ * behavior changes, update ToastViewport.test.tsx, Toast.doc.mjs, and Toast.stories.tsx.
*/
import {
@@ -24,6 +24,7 @@ import {
useState,
} from 'react';
import type {ReactNode} from 'react';
+import {createPortal} from 'react-dom';
import * as stylex from '@stylexjs/stylex';
import {spacingVars, durationVars, easeVars} from '../theme/tokens.stylex';
import {mergeProps} from '../utils';
@@ -32,6 +33,10 @@ import {useAnnounce} from '../hooks/useAnnounce';
import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
+import {
+ getActiveModalOutlet,
+ subscribeModalOutlets,
+} from '../Layer/modalOutlet';
import {ToastSurface} from './Toast';
import {ToastContext, type ToastContextValue} from './ToastContext';
import type {ToastEntry, ToastPosition, ToastDismissReason} from './types';
@@ -47,6 +52,9 @@ const TOAST_EDGE_DRIFT = spacingVars['--spacing-2'];
const TOAST_EDGE_DRIFT_NEGATIVE = `calc(-1 * ${TOAST_EDGE_DRIFT})`;
const styles = stylex.create({
+ rootOutlet: {
+ display: 'contents',
+ },
viewport: {
position: 'fixed',
zIndex: 500,
@@ -197,8 +205,10 @@ export interface ToastViewportProps {
*/
layerInset?: LayerInset;
/**
- * Promote viewport to CSS top layer via popover="manual".
- * Set to false when inside a dialog or other top-layer element.
+ * Promote viewport to CSS top layer via popover="manual". While a Dialog
+ * is open, the viewport moves into the latest one so toasts stay visible
+ * and clickable above it. Set to false to render in place, e.g. a viewport you mount
+ * inside your own top-layer element.
* @default true
*/
isTopLayer?: boolean;
@@ -334,7 +344,6 @@ export function ToastViewport({
const toastsRef = useRef(toasts);
toastsRef.current = toasts;
- // Show the popover on mount so it enters the top layer.
const viewportRef = useRef<HTMLDivElement>(null);
// Toast ids whose exit has begun — guards onHide from double-firing (see
// removeToast). Mirrors exitingIds state, readable synchronously.
@@ -549,20 +558,69 @@ export function ToastViewport({
insetStyle.insetInlineEnd = inset.end;
}
- // Show the popover on mount so it enters the top layer
- useEffect(() => {
+ // A top-layer viewport renders into a host element this component owns, so
+ // the host can move into the latest open native modal and back without
+ // React remounting the rows: their timers and gesture state live there.
+ // Outside a modal the host sits at the viewport's own place in the tree.
+ const rootOutletRef = useRef<HTMLDivElement>(null);
+ const [host, setHost] = useState<HTMLDivElement | null>(null);
+
+ useLayoutEffect(() => {
if (!isTopLayer) {
return;
}
- const el = viewportRef.current;
- if (el && typeof el.showPopover === 'function') {
+ const element = document.createElement('div');
+ element.style.display = 'contents';
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- the host exists only on the client, so server and hydration markup carry no portal
+ setHost(element);
+ return () => {
+ element.remove();
+ setHost(null);
+ };
+ }, [isTopLayer]);
+
+ useLayoutEffect(() => {
+ if (!isTopLayer || host == null) {
+ return;
+ }
+ const place = () => {
+ const parent = getActiveModalOutlet() ?? rootOutletRef.current;
+ if (parent == null) {
+ return;
+ }
+ if (host.parentNode !== parent) {
+ // Moving a node blurs whatever inside it had focus.
+ const active = document.activeElement;
+ const hadFocus = active instanceof HTMLElement && host.contains(active);
+ parent.appendChild(host);
+ if (hadFocus) {
+ active.focus({preventScroll: true});
+ }
+ }
+ // Leaving the document hid the popover. Showing it again puts it above
+ // the modal that just opened, or above everything once the last modal
+ // closed.
+ const el = viewportRef.current;
+ if (el == null || typeof el.showPopover !== 'function') {
+ return;
+ }
+ let isShowing = false;
try {
- el.showPopover();
+ isShowing = el.matches(':popover-open');
} catch {
- /* already showing */
+ /* :popover-open unsupported */
}
- }
- }, [isTopLayer]);
+ if (!isShowing) {
+ try {
+ el.showPopover();
+ } catch {
+ /* already showing */
+ }
+ }
+ };
+ place();
+ return subscribeModalOutlets(place);
+ }, [isTopLayer, host]);
// F6 jumps focus into the toast viewport — the standard "go to
// notifications" affordance. Focus the first control in the newest toast,
@@ -613,42 +671,54 @@ export function ToastViewport({
: styles.bottomEnd;
const isReversed = position === 'topEnd' || position === 'topStart';
+ const viewport = (
+ <div
+ ref={viewportRef}
+ role={hasToasts ? 'region' : undefined}
+ aria-label={hasToasts ? t('@astryx.toast.viewport') : undefined}
+ tabIndex={hasToasts ? -1 : undefined}
+ // popover="manual" promotes to the top layer; the host effect above
+ // keeps it above the latest open modal. Omitted when the caller
+ // renders the viewport in place.
+ popover={isTopLayer ? 'manual' : undefined}
+ {...mergeProps(
+ stylex.props(
+ layerTextReset.reset,
+ layerStructureReset.reset,
+ styles.viewport,
+ styles.viewportInlineSpan,
+ posStyle,
+ ),
+ {
+ style: Object.keys(insetStyle).length > 0 ? insetStyle : undefined,
+ },
+ )}>
+ <LayerContentBoundary>
+ {visibleToasts.map(entry => (
+ <ToastRow
+ key={entry.id}
+ entry={entry}
+ isExiting={exitingIds.has(entry.id)}
+ isReversed={isReversed}
+ onExited={handleExited}
+ onDismiss={removeToast}
+ />
+ ))}
+ </LayerContentBoundary>
+ </div>
+ );
+
return (
<ToastContext value={contextValue}>
{children}
- <div
- ref={viewportRef}
- role={hasToasts ? 'region' : undefined}
- aria-label={hasToasts ? t('@astryx.toast.viewport') : undefined}
- tabIndex={hasToasts ? -1 : undefined}
- // popover="manual" promotes to the top layer (above dialogs).
- // Omitted inside dialogs where the viewport is already in a top layer.
- popover={isTopLayer ? 'manual' : undefined}
- {...mergeProps(
- stylex.props(
- layerTextReset.reset,
- layerStructureReset.reset,
- styles.viewport,
- styles.viewportInlineSpan,
- posStyle,
- ),
- {
- style: Object.keys(insetStyle).length > 0 ? insetStyle : undefined,
- },
- )}>
- <LayerContentBoundary>
- {visibleToasts.map(entry => (
- <ToastRow
- key={entry.id}
- entry={entry}
- isExiting={exitingIds.has(entry.id)}
- isReversed={isReversed}
- onExited={handleExited}
- onDismiss={removeToast}
- />
- ))}
- </LayerContentBoundary>
- </div>
+ {isTopLayer ? (
+ <>
+ <div ref={rootOutletRef} {...stylex.props(styles.rootOutlet)} />
+ {host != null ? createPortal(viewport, host) : null}
+ </>
+ ) : (
+ viewport
+ )}
</ToastContext>
);
}