Skip to content

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

TypeScript

perf(Layer): LayerProvider loads no Toast; Toast registers its viewport (#10012)

Christopher Chedeauaf7037b4a4c1
diff --git a/.changeset/layer-provider-toast-on-import.md b/.changeset/layer-provider-toast-on-import.md
new file mode 100644
index 0000000000..1d77ed39b5
--- /dev/null
+++ b/.changeset/layer-provider-toast-on-import.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[perf] LayerProvider no longer carries the toast viewport. An app that imports `LayerProvider` from `@astryxdesign/core/Layer` and never imports Toast loads about 42 KB less JavaScript (gzip). Toast registers its viewport when it is imported, and LayerProvider then renders it after the app. Without a Toast import, LayerProvider renders no empty viewport. A toast shown before the viewport mounts waits, then shows. On the server, LayerProvider renders no viewport; it mounts after hydration.
+
+@vjeux
diff --git a/.changeset/toast-fallback-early-dismiss.md b/.changeset/toast-fallback-early-dismiss.md
new file mode 100644
index 0000000000..42671f7d2d
--- /dev/null
+++ b/.changeset/toast-fallback-early-dismiss.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Toast: without a LayerProvider, a toast dismissed before the fallback viewport mounts no longer shows, and its `onHide` runs once with `'manual'`.
+
+@vjeux
diff --git a/apps/storybook/stories/Toast.stories.tsx b/apps/storybook/stories/Toast.stories.tsx
index 98fc3aa887..792f370bc1 100644
--- a/apps/storybook/stories/Toast.stories.tsx
+++ b/apps/storybook/stories/Toast.stories.tsx
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import type {Meta, StoryObj} from '@storybook/react';
-import {useState, useRef, type ReactNode} from 'react';
+import {useEffect, useState, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Toast, useToast, ToastViewport} from '@astryxdesign/core/Toast';
import type {
@@ -189,6 +189,43 @@ export const Default: StoryObj = {
},
};
+// =============================================================================
+// Shown on mount
+// =============================================================================
+
+export const ShownOnMount: StoryObj = {
+ // A toast that stays up would cover the docs page, so it shows only here.
+ tags: ['!autodocs'],
+ render: function ShownOnMountStory() {
+ const toast = useToast();
+ // The page can render a story more than once. The uniqueID keeps one
+ // toast, and the toast leaves with the story.
+ useEffect(
+ () =>
+ toast({
+ body: 'Shown as the page mounted',
+ isAutoHide: false,
+ uniqueID: 'shown-on-mount',
+ }),
+ [toast],
+ );
+ return (
+ <Button
+ label="Show another toast"
+ onClick={() => toast({body: 'This is an info toast'})}
+ />
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'A toast shown as the page mounts. LayerProvider holds it until the toast viewport mounts beside the app, then shows it. It stays up until it is dismissed.',
+ },
+ },
+ },
+};
+
// =============================================================================
// Types
// =============================================================================
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 984cdfaa4b..d31b043d89 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -29,6 +29,9 @@ verified_by:
packages/core/src/Layer/useLayer.test.tsx,
packages/core/src/Layer/layerViewportInset.test.ts,
packages/core/src/Layer/LayerProvider.test.tsx,
+ packages/core/src/Layer/toastHost.test.tsx,
+ packages/core/src/Layer/toastHost.lateRegistration.test.tsx,
+ scripts/layer-toast-bundle.test.mjs,
packages/core/src/Layer/layerHost.test.ts,
packages/core/src/Layer/anchorName.test.ts,
packages/core/src/Layer/useLayerDismissal.test.tsx,
@@ -403,10 +406,12 @@ text inheritance and visual appearance.
### Current global and nonparticipating surfaces
-LayerProvider supplies Toast configuration and mounts ToastViewport. It is not a
-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.
+LayerProvider supplies Toast configuration and an outlet for ToastViewport.
+LayerProvider alone renders no empty viewport; Toast registers its viewport when
+imported. The outlet then renders the viewport after the app, on the client
+only, and a toast shown before that waits in the outlet. It is not a 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. Each open modal
Dialog, each open modal Drawer, and each open scrim BottomSheet supplies its
@@ -491,7 +496,9 @@ layers use Layer rendering without joining Escape/platform dismissal.
closed a layer above the host does not also close the host
(`family:overlay-dismissal` FR11).
- **INV10 — LayerProvider is configuration, not a universal layer host.** It
- carries Toast configuration and the app-declared viewport inset. Trigger-
+ carries Toast configuration and the app-declared viewport inset.
+ LayerProvider alone renders no empty viewport; Toast registers its viewport
+ when imported. Trigger-
associated layers resolve near their JSX position independently of the
provider; the inset reaches them as a context value each layer carries on
itself, never by resolving placement through the provider, and a layer with
@@ -726,7 +733,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; `useBackdropPress.test.tsx`; `outsidePress.test.ts` | A current local channel silently changes ownership or policy |
-| 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 |
+| INV10 | `LayerProvider.tsx`, `toastHost.tsx`, `LayerProvider.test.tsx`, `toastHost.test.tsx`, `toastHost.lateRegistration.test.tsx`, `useToast.tsx`, `ToastViewport.test.tsx`, `ToastViewport.modalHost.test.tsx`, and `scripts/layer-toast-bundle.test.mjs` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, a default provider renders differently from no provider, a Layer import loads a Toast module, or a toast added before Toast loads is lost |
| INV14, INV15 | Source boundary check over Core for top-layer hosts, exit copies, backdrop elements, lift, and rectangle-morph code outside the runtime and the lift module | A component building its own copy of a mechanism INV14 lists (top-layer mounting, close-request delivery, hold, exit copy, or backdrop element), or re-implementing the lift or the grow |
| INV17 | One runtime suite over every kind of layer root: a `useLayer` layer, inline and portaled, and the Dialog, Drawer, Lightbox, MobileNav, BottomSheetPanel, and ToastViewport content roots, each inside a plain `onClick` wrapper and a Core clickable container; nested layers | A click inside a layer root that reaches an ancestor bubble-phase handler, a caller's wrapper included; an outer layer's handler that receives an inner layer's press; or a document listener or light dismiss that no longer receives it |
| INV18 | `useLayer.test.tsx` (a closed trigger has no anchor-name, and the trigger of a shown or fading layer does) and `TooltipClosedTriggerAnchor.interaction.browser.spec.ts` in Chromium and WebKit | A closed trigger with an anchor-name, a shown or fading layer placed away from its anchor, or a surface around a closed trigger that stops while the main thread is busy |
diff --git a/docs/specs/components/Layer/LayerProvider.spec.md b/docs/specs/components/Layer/LayerProvider.spec.md
index e948da61fe..dfad6c901b 100644
--- a/docs/specs/components/Layer/LayerProvider.spec.md
+++ b/docs/specs/components/Layer/LayerProvider.spec.md
@@ -13,6 +13,8 @@ review_triggers: [public-api, behavior, layout]
verified_by:
[
packages/core/src/Layer/LayerProvider.test.tsx,
+ packages/core/src/Layer/toastHost.test.tsx,
+ packages/core/src/Layer/toastHost.lateRegistration.test.tsx,
apps/storybook/stories/Layer.stories.tsx,
]
modules: []
@@ -30,10 +32,10 @@ system_specs: [spec:AST-059, spec:AST-038]
| Area | Contract |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Public contract | `LayerProvider` with `children`, `toast` (`{position, maxVisible, inset}`), and `inset` (`{blockStart, blockEnd, inlineStart, inlineEnd}`). |
-| Behavior | The outermost provider supplies layer configuration and mounts the app's one toast viewport around `children`. A nested provider renders its children unchanged, except that a nested `inset` narrows the inset for layers in its subtree. |
+| Behavior | The outermost provider supplies layer configuration and renders the one toast viewport once Toast is imported. A nested provider renders its children unchanged, except that a nested `inset` narrows the inset for layers in its subtree. |
| End-user impact | Toasts appear in one configured corner, and anchored layers and toasts stay clear of a declared floating bar. |
| Builder impact | None. |
-| Compatibility/readiness | Records shipped behavior; no public change. |
+| Compatibility/readiness | Records shipped behavior, except that the toast viewport waits for a Toast import (FR1); no public change. |
| Review checks | Reject a second toast viewport from a nested provider, a provider that hosts trigger-associated layers, or a default provider that renders layers differently from no provider. |
| Governing rules | `spec:AST-059` FR6 (the inset); `architecture:layer-runtime` INV10–INV11; `component:Toast`. |
@@ -49,7 +51,8 @@ This record owns what the provider itself renders.
## Compatibility and migration
- Released default preserved: `yes`
-- Compatibility class: records shipped behavior; no public change
+- Compatibility class: records shipped behavior, except that the toast
+ viewport waits for a Toast import (FR1); no public change
- Controlled/uncontrolled behavior: not applicable
- Migration decision: none
@@ -79,7 +82,7 @@ No component-local concept beyond the consumer props.
| ID | Invariant | Basis |
| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
-| FR1 | A provider with no LayerProvider above it supplies the layer context (`toast` configuration and `inset`) and wraps `children` in one toast viewport configured by `toast.position`, `toast.maxVisible`, `toast.inset`, and `inset`. | Current source and tests |
+| FR1 | A provider with no LayerProvider above it supplies the layer context (`toast` configuration and `inset`) and the toast context. Once Toast is imported, it renders one toast viewport after `children`, configured by `toast.position`, `toast.maxVisible`, `toast.inset`, and `inset`; before that, none. | Current source and tests |
| FR2 | A provider nested under another mounts no toast viewport. Without `inset` it renders its children unchanged; with `inset`, each edge it declares applies to the layers in its subtree, and it keeps the outer `toast` configuration. What an edge it leaves unset reads in that subtree is uncontracted here. | Current source; `spec:AST-059` FR6 |
| FR3 | With nothing declared, a provider changes no layer geometry, so layers under a default provider match layers with no provider. | `spec:AST-059` FR6; tests |
@@ -91,7 +94,7 @@ No component-local concept beyond the consumer props.
| State | Required invariant | Allowed variation |
| -------------------- | ----------------------------------------------- | ----------------- |
-| Root provider | One toast viewport; context supplied. | Toast config. |
+| Root provider | Context supplied; a viewport once Toast loads. | Toast config. |
| Nested without inset | Children unchanged; no second viewport. | — |
| Nested with inset | Subtree inset narrowed; toast config unchanged. | Inset. |
@@ -125,9 +128,9 @@ No component-local concept beyond the consumer props.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| -------- | ------------------------ | -------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------ |
-| FR1–FR3 | `LayerProvider.test.tsx` | Default, declared inset, nested, toast inset | A default-provider difference, or an inset that does not reach its layers, fails. | `audit:LayerProvider/behavior` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| -------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------ |
+| FR1–FR3 | `LayerProvider.test.tsx`; for FR1 also `toastHost.test.tsx` and `toastHost.lateRegistration.test.tsx` | Default, declared inset, nested, toast inset, no Toast import | A default-provider difference, an inset that does not reach its layers, or a viewport with no Toast import fails. | `audit:LayerProvider/behavior` |
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 31505266b9..8402216782 100644
--- a/docs/specs/components/Toast/Toast.spec.md
+++ b/docs/specs/components/Toast/Toast.spec.md
@@ -13,6 +13,8 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]
verified_by:
[
packages/core/src/Layer/LayerProvider.test.tsx,
+ packages/core/src/Layer/toastHost.test.tsx,
+ packages/core/src/Layer/toastHost.lateRegistration.test.tsx,
packages/core/src/Toast/ToastViewport.test.tsx,
packages/core/src/Toast/ToastViewport.modalHost.test.tsx,
packages/core/src/Toast/useToast.test.tsx,
@@ -109,10 +111,8 @@ Consumer migration instructions belong in consumer docs and release notes.
still collapsing when its viewport moves into or out of any outlet FR12
names comes back as an invisible zero-height row that never unmounts: it
keeps the notifications landmark exposed and F6 focuses its hidden dismiss
- button, and it holds one of the `maxVisible` places. With no provider
- above the caller a dismissal called before the fallback viewport
- mounts does nothing, so the toast shows and stays unless it
- auto-hides (FR3, FR5, FR7, FR10, FR11, FR12).
+ button, and it holds one of the `maxVisible` places (FR5, FR7, FR10,
+ FR11, FR12).
- **Announcement happens at dispatch, not when shown.** The viewport announces
a toast when it is raised rather than when it appears, so a toast shown and
dismissed in the same handler is announced although it never appears, and of
@@ -174,7 +174,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
| FR1 | A card carries `toast` with `type` and shows `body` and, on its first line, `endContent` then a dismiss Button named by `@astryx.toast.dismiss`; long body text wraps below. `renderContent` replaces that layout, receives `body`, `endContent`, `type`, timing, and a `dismiss` function, and gets no injected dismiss control. | Current source and tests |
| FR2 | With auto-hide on (the default for `info`, off for `error`), the card dismisses with reason `auto` after `autoHideDuration` ms. The timer pauses while the pointer is over the card, focus is inside it, a touch or pen gesture is active, or the window is blurred, and resumes with the remaining time (at least 1 s). Each pause condition holds the timer on its own: one ending resumes it only when no other still holds, and focus moving between the card's own controls keeps it held. A toast raised while the window is already blurred starts with its timer held. | Current source and tests |
-| FR3 | The dismiss button, a swipe, a `dismiss` call, or the returned dismiss function dismiss with reason `manual`; `onHide` fires at most once, when the toast is dismissed, even when dismissed twice during its exit. Implementation gap: with no provider above the caller, a dismissal called before the fallback viewport mounts does nothing, so the toast shows and stays unless it auto-hides (Current-state impact). A toast replaced through `uniqueID` is not dismissed and reports no `onHide`. | Current source and tests |
+| FR3 | The dismiss button, a swipe, a `dismiss` call, or the returned dismiss function dismiss with reason `manual`; `onHide` fires at most once, when the toast is dismissed, even when dismissed twice during its exit or before it shows. A toast replaced through `uniqueID` is not dismissed and reports no `onHide`. | Current source and tests |
| FR4 | A drag toward the position's block edge, from any pointer (`spec:AST-094` FR43), decides once, at release, per `spec:AST-094` FR36–FR37: projected travel past the commit point dismisses, and a release moving back toward the start cancels. A short drag snaps back; horizontal intent, a second touch, or a gesture starting on an interactive descendant does not dismiss. Native page scrolling continues until touch intent matches the dismiss edge. In the default layout the visible dismiss button stays as a non-gesture alternative; custom content supplies its own. Implementation gaps: the shipped rule dismisses on net travel past a distance threshold or a fast flick timed by its own average speed, even after the finger moves back, and recognizes only touch and pen drags, not a mouse (Current-state impact). | Current source and tests |
| FR5 | A new card slides in from its edge and fades in; a dismissed card collapses and fades before it unmounts; both slide only along the block axis. A dismissal without a swipe uses theme timing; a swipe's commit and snap-back start at the release velocity (`spec:AST-094` FR38). Under reduced motion the entrance and dismissal are an opacity-only fade of 200 ms or less on a coarse pointer or after a touch release (`design:reduced-motion` DR2) and immediate otherwise (DR3), and the card still unmounts. Implementation gaps: a swipe's settle is a CSS transition at theme timing, and under reduced motion every transition, including the row collapse and the swipe's throw, runs for 0.01 ms on every pointer (Current-state impact). | Current source and tests |
| FR6 | The viewport stacks toasts at `position`, newest nearest the configured edge, with an 8 px gap and no extra space at the edge beyond the safe-area gutter it keeps; it spans the inline axis within its inset, honoring start and end insets in either direction. Each edge sits at the provider's `layerInset`, and a `toast.inset` edge, when set, replaces it (`spec:AST-059` FR6). Implementation gaps: a `toast.inset` edge set to 0 does not replace the provider's value, and an edge opposite the position, such as `top` for a bottom stack, moves the stack to that edge (Current-state impact). | Current source and tests |
@@ -245,7 +245,7 @@ button), so no anatomy part can own the `toast` target.
| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | --------------------------- |
-| FR1, FR3 | `ToastViewport.test.tsx` layout, custom content, and onHide tests | Default, custom content, double dismiss | Dropped controls or a repeated `onHide` fails. | `audit:Toast/behavior` |
+| FR1, FR3 | `ToastViewport.test.tsx` layout, custom content, and onHide tests; `Layer/toastHost.test.tsx` and `toastHost.lateRegistration.test.tsx` toasts dismissed or replaced before they show | Default, custom content, double dismiss, a dismissal before the toast shows | Dropped controls or a repeated `onHide` fails. | `audit:Toast/behavior` |
| FR2 | `ToastViewport.test.tsx` blur-pause, pause-source and raised-while-blurred tests | Window blur, toast raised while blurred, new toast during pause, overlapping pointer/focus/window holds, focus moving inside | A timer running while paused, or resuming while another hold remains, fails. | `audit:Toast/behavior` |
| 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` |
diff --git a/packages/core/src/Layer/LayerProvider.test.tsx b/packages/core/src/Layer/LayerProvider.test.tsx
index 3e97216c71..34fd4a0774 100644
--- a/packages/core/src/Layer/LayerProvider.test.tsx
+++ b/packages/core/src/Layer/LayerProvider.test.tsx
@@ -11,6 +11,8 @@
import {describe, expect, it} from 'vitest';
import {fireEvent, render} from '@testing-library/react';
import {LayerProvider} from './LayerProvider';
+// The toast viewport these cases read registers itself as its module loads.
+import '../Toast/ToastViewport';
import {useLayer} from './useLayer';
import {layerInsetProperties} from './layerInset';
diff --git a/packages/core/src/Layer/LayerProvider.tsx b/packages/core/src/Layer/LayerProvider.tsx
index 4751fa17f8..a3a9e089b7 100644
--- a/packages/core/src/Layer/LayerProvider.tsx
+++ b/packages/core/src/Layer/LayerProvider.tsx
@@ -10,7 +10,7 @@ import {
type LayerInset,
type LayerToastConfig,
} from './LayerContext';
-import {ToastViewport} from '../Toast/ToastViewport';
+import {ToastHostOutlet} from './toastHost';
export interface LayerProviderProps {
children: ReactNode;
@@ -34,10 +34,11 @@ export interface LayerProviderProps {
* App-level provider for layer systems (toast, sheet, imperative modals).
*
* Optional — hooks fall back to a lazy self-mounting viewport when no
- * provider exists. Nested providers are no-ops, except that one declaring an
- * `inset` narrows it for the anchored layers in its subtree. `inset` declares
- * a persistent bar floating over a viewport edge once; anchored layers and
- * toasts both clear it.
+ * provider exists. The provider renders the toast viewport once Toast is
+ * imported; without Toast it renders no empty viewport. Nested providers are
+ * no-ops, except that one declaring an `inset` narrows it for the anchored
+ * layers in its subtree. `inset` declares a persistent bar floating over a
+ * viewport edge once; anchored layers and toasts both clear it.
*
* @example
* ```
@@ -78,18 +79,18 @@ export function LayerProvider({
// The declared inset reaches anchored layers through context — each layer
// writes it inline on itself, so a corrective portal cannot escape it — and
- // the toast viewport through its prop. Nothing resolves placement through
+ // the toast viewport through the outlet. Nothing resolves placement through
// the provider (spec:AST-059 FR6). With no inset nothing is written, so a
// surface with no provider renders as one under the default provider.
return (
<LayerContext value={contextValue}>
- <ToastViewport
+ <ToastHostOutlet
position={toastConfig.position}
maxVisible={toastConfig.maxVisible}
inset={toastConfig.inset}
layerInset={inset}>
{children}
- </ToastViewport>
+ </ToastHostOutlet>
</LayerContext>
);
}
diff --git a/packages/core/src/Layer/toastHost.lateRegistration.test.tsx b/packages/core/src/Layer/toastHost.lateRegistration.test.tsx
new file mode 100644
index 0000000000..e9a2306fda
--- /dev/null
+++ b/packages/core/src/Layer/toastHost.lateRegistration.test.tsx
@@ -0,0 +1,167 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file toastHost.lateRegistration.test.tsx
+ * @input LayerProvider and its toast context, with ToastViewport imported
+ * only inside a test
+ * @output Proves LayerProvider alone renders no viewport, that a toast added
+ * before Toast loads shows once it loads, and that the app stays mounted.
+ * A waiting toast that is removed reports onHide once and never shows. A
+ * waiting namesake follows the uniqueID rules and reports no onHide.
+ * @position Unit tests for Layer/toastHost.tsx. Each test reloads the
+ * modules, so Toast's registration is fresh in each one.
+ */
+
+import {act, render, screen} from '@testing-library/react';
+import {use, useEffect} from 'react';
+import {beforeEach, describe, expect, it, vi} from 'vitest';
+import type {ToastEntry} from '../Toast/types';
+
+beforeEach(() => {
+ vi.resetModules();
+});
+
+async function loadLayer() {
+ const {LayerProvider} = await import('./LayerProvider');
+ const {ToastContext} = await import('./toastHost');
+ return {LayerProvider, ToastContext};
+}
+
+function entry(
+ id: string,
+ body: string,
+ options: Pick<
+ ToastEntry['options'],
+ 'uniqueID' | 'onHide' | 'collisionBehavior'
+ > = {},
+): ToastEntry {
+ return {id, createdAt: Date.now(), options: {body, ...options}};
+}
+
+describe('LayerProvider before Toast is imported', () => {
+ it('renders no toast viewport', async () => {
+ const {LayerProvider} = await loadLayer();
+ const {container} = render(
+ <LayerProvider>
+ <p>App</p>
+ </LayerProvider>,
+ );
+ expect(container.innerHTML).toBe('<p>App</p>');
+ expect(document.querySelector('[popover]')).toBeNull();
+ });
+
+ it('shows a toast added before Toast loads once it loads, exactly once, and keeps the app mounted', async () => {
+ const {LayerProvider, ToastContext} = await loadLayer();
+ function AddsOnMount() {
+ const toasts = use(ToastContext);
+ useEffect(() => {
+ toasts?.addToast(entry('waits', 'Saved before the viewport'));
+ }, [toasts]);
+ return <p>App</p>;
+ }
+ const view = render(
+ <LayerProvider>
+ <AddsOnMount />
+ </LayerProvider>,
+ );
+ const app = view.getByText('App');
+ expect(screen.queryByText('Saved before the viewport')).toBeNull();
+ await act(async () => {
+ await import('../Toast/ToastViewport');
+ });
+ expect(
+ await screen.findByText('Saved before the viewport'),
+ ).toBeInTheDocument();
+ expect(document.querySelectorAll('[data-toast-id]')).toHaveLength(1);
+ expect(view.getByText('App')).toBe(app);
+ });
+
+ it('drops a waiting toast that is removed, reports its onHide once, and finds a waiting one by uniqueID', async () => {
+ const {LayerProvider, ToastContext} = await loadLayer();
+ const onHide = vi.fn();
+ let found: ToastEntry | undefined;
+ function AddsTwo() {
+ const toasts = use(ToastContext);
+ useEffect(() => {
+ toasts?.addToast(entry('first', 'Removed while waiting', {onHide}));
+ toasts?.addToast(
+ entry('second', 'Kept while waiting', {uniqueID: 'kept'}),
+ );
+ toasts?.removeToast('first', 'manual');
+ toasts?.removeToast('first', 'manual');
+ found = toasts?.findByUniqueID('kept');
+ }, [toasts]);
+ return null;
+ }
+ render(
+ <LayerProvider>
+ <AddsTwo />
+ </LayerProvider>,
+ );
+ expect(found?.id).toBe('second');
+ expect(onHide.mock.calls).toEqual([['manual']]);
+ await act(async () => {
+ await import('../Toast/ToastViewport');
+ });
+ expect(await screen.findByText('Kept while waiting')).toBeInTheDocument();
+ expect(screen.queryByText('Removed while waiting')).toBeNull();
+ expect(onHide).toHaveBeenCalledTimes(1);
+ });
+ it('replaces a waiting toast with a waiting namesake: dismissing the replaced one reports no onHide', async () => {
+ const {LayerProvider, ToastContext} = await loadLayer();
+ const onHide = vi.fn();
+ function AddsNamesakes() {
+ const toasts = use(ToastContext);
+ useEffect(() => {
+ toasts?.addToast(
+ entry('first', 'Replaced while waiting', {uniqueID: 'same', onHide}),
+ );
+ toasts?.addToast(entry('second', 'Its namesake', {uniqueID: 'same'}));
+ toasts?.removeToast('first', 'manual');
+ }, [toasts]);
+ return null;
+ }
+ render(
+ <LayerProvider>
+ <AddsNamesakes />
+ </LayerProvider>,
+ );
+ await act(async () => {
+ await import('../Toast/ToastViewport');
+ });
+ expect(await screen.findByText('Its namesake')).toBeInTheDocument();
+ expect(screen.queryByText('Replaced while waiting')).toBeNull();
+ expect(onHide).not.toHaveBeenCalled();
+ });
+
+ it('drops a waiting ignore namesake: dismissing it reports no onHide, and the first one shows', async () => {
+ const {LayerProvider, ToastContext} = await loadLayer();
+ const onHide = vi.fn();
+ function AddsNamesakes() {
+ const toasts = use(ToastContext);
+ useEffect(() => {
+ toasts?.addToast(entry('first', 'Shown first', {uniqueID: 'same'}));
+ toasts?.addToast(
+ entry('second', 'Ignored namesake', {
+ uniqueID: 'same',
+ collisionBehavior: 'ignore',
+ onHide,
+ }),
+ );
+ toasts?.removeToast('second', 'manual');
+ }, [toasts]);
+ return null;
+ }
+ render(
+ <LayerProvider>
+ <AddsNamesakes />
+ </LayerProvider>,
+ );
+ await act(async () => {
+ await import('../Toast/ToastViewport');
+ });
+ expect(await screen.findByText('Shown first')).toBeInTheDocument();
+ expect(screen.queryByText('Ignored namesake')).toBeNull();
+ expect(onHide).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/Layer/toastHost.test.tsx b/packages/core/src/Layer/toastHost.test.tsx
new file mode 100644
index 0000000000..440527e94c
--- /dev/null
+++ b/packages/core/src/Layer/toastHost.test.tsx
@@ -0,0 +1,229 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file toastHost.test.tsx
+ * @input LayerProvider, its toast outlet, the registered ToastViewport and
+ * useToast
+ * @output Proves the outlet renders the registered viewport after the app,
+ * once per React root and only on the client. A toast the app shows as it
+ * mounts still appears. Without a provider, the fallback root's queue drops
+ * a toast dismissed while it waits. The queue stays connected while the
+ * viewport's props change, and under StrictMode's replayed effects. An
+ * empty uniqueID names no toast, before the viewport connects and after.
+ * @position Unit tests for Layer/toastHost.tsx. The late registration has its
+ * own file, so this file's static Toast import cannot hide it.
+ */
+
+import {act, render, screen} from '@testing-library/react';
+import {StrictMode, useEffect, useRef} from 'react';
+import {createRoot, hydrateRoot} from 'react-dom/client';
+import {renderToString} from 'react-dom/server';
+import {describe, expect, it, vi} from 'vitest';
+import type {ToastDismissFn} from '../Toast/types';
+import {useToast} from '../Toast/useToast';
+import {LayerProvider} from './LayerProvider';
+
+/** Shows a toast from its first effect. */
+function ShowsOnMount({text}: {text: string}) {
+ const showToast = useToast();
+ useEffect(() => {
+ showToast({body: text, isAutoHide: false});
+ }, [showToast, text]);
+ return <p>{text} app</p>;
+}
+
+describe('LayerProvider toast outlet', () => {
+ it('renders the viewport after the app, which keeps its own position', () => {
+ const {container} = render(
+ <LayerProvider>
+ <p>App</p>
+ </LayerProvider>,
+ );
+ expect(container.firstElementChild?.textContent).toBe('App');
+ expect(container.querySelector('[popover="manual"]')).not.toBeNull();
+ });
+
+ it('shows a toast the app adds in its first effect, before the viewport takes toasts, once', async () => {
+ render(
+ <LayerProvider>
+ <ShowsOnMount text="Saved" />
+ </LayerProvider>,
+ );
+ expect(await screen.findByText('Saved')).toBeInTheDocument();
+ expect(document.querySelectorAll('[data-toast-id]')).toHaveLength(1);
+ });
+
+ it('gives each React root its own viewport and toasts', async () => {
+ const first = document.createElement('div');
+ const second = document.createElement('div');
+ document.body.append(first, second);
+ const firstRoot = createRoot(first);
+ const secondRoot = createRoot(second);
+ await act(async () => {
+ firstRoot.render(
+ <LayerProvider>
+ <ShowsOnMount text="First" />
+ </LayerProvider>,
+ );
+ secondRoot.render(
+ <LayerProvider>
+ <ShowsOnMount text="Second" />
+ </LayerProvider>,
+ );
+ });
+ expect(first.querySelectorAll('[popover="manual"]')).toHaveLength(1);
+ expect(second.querySelectorAll('[popover="manual"]')).toHaveLength(1);
+ expect(first.textContent).toContain('First app');
+ expect(first.textContent).not.toContain('Second');
+ expect(second.textContent).toContain('Second app');
+ expect(second.textContent).not.toContain('First');
+ await act(async () => {
+ firstRoot.unmount();
+ secondRoot.unmount();
+ });
+ first.remove();
+ second.remove();
+ });
+
+ it('renders no viewport on the server, and mounts it after hydration with no recoverable error', async () => {
+ const app = (
+ <LayerProvider>
+ <p>App</p>
+ </LayerProvider>
+ );
+ const html = renderToString(app);
+ expect(html).toBe('<p>App</p>');
+ const container = document.createElement('div');
+ container.innerHTML = html;
+ document.body.append(container);
+ const errors: unknown[] = [];
+ let root: ReturnType<typeof hydrateRoot> | null = null;
+ await act(async () => {
+ root = hydrateRoot(container, app, {
+ onRecoverableError: error => {
+ errors.push(error);
+ },
+ });
+ });
+ expect(errors).toEqual([]);
+ expect(container.querySelectorAll('p')).toHaveLength(1);
+ expect(container.firstElementChild?.textContent).toBe('App');
+ expect(container.querySelector('[popover="manual"]')).not.toBeNull();
+ await act(async () => {
+ root?.unmount();
+ });
+ container.remove();
+ });
+
+ it('keeps the queue connected when the viewport changes: a dismissal in that commit still reports onHide', async () => {
+ const onHide = vi.fn();
+ function DismissesOnCue({dismissNow}: {dismissNow: boolean}) {
+ const showToast = useToast();
+ const dismissRef = useRef<ToastDismissFn | null>(null);
+ useEffect(() => {
+ dismissRef.current = showToast({
+ body: 'Shown',
+ isAutoHide: false,
+ onHide,
+ });
+ }, [showToast]);
+ useEffect(() => {
+ if (dismissNow) {
+ dismissRef.current?.();
+ }
+ }, [dismissNow]);
+ return null;
+ }
+ const view = render(
+ <LayerProvider toast={{maxVisible: 3}}>
+ <DismissesOnCue dismissNow={false} />
+ </LayerProvider>,
+ );
+ expect(await screen.findByText('Shown')).toBeInTheDocument();
+ view.rerender(
+ <LayerProvider toast={{maxVisible: 4}}>
+ <DismissesOnCue dismissNow />
+ </LayerProvider>,
+ );
+ expect(onHide.mock.calls).toEqual([['manual']]);
+ });
+
+ it('treats an empty uniqueID as no ID, before the viewport connects and after', async () => {
+ function RaisesUnnamed({later}: {later: boolean}) {
+ const showToast = useToast();
+ useEffect(() => {
+ showToast({body: 'Early one', uniqueID: '', isAutoHide: false});
+ showToast({body: 'Early two', uniqueID: '', isAutoHide: false});
+ }, [showToast]);
+ useEffect(() => {
+ if (later) {
+ showToast({body: 'Late one', uniqueID: '', isAutoHide: false});
+ showToast({body: 'Late two', uniqueID: '', isAutoHide: false});
+ }
+ }, [later, showToast]);
+ return null;
+ }
+ const view = render(
+ <LayerProvider toast={{maxVisible: 0}}>
+ <RaisesUnnamed later={false} />
+ </LayerProvider>,
+ );
+ expect(await screen.findByText('Early two')).toBeInTheDocument();
+ expect(screen.getByText('Early one')).toBeInTheDocument();
+ view.rerender(
+ <LayerProvider toast={{maxVisible: 0}}>
+ <RaisesUnnamed later />
+ </LayerProvider>,
+ );
+ expect(await screen.findByText('Late two')).toBeInTheDocument();
+ expect(screen.getByText('Late one')).toBeInTheDocument();
+ expect(document.querySelectorAll('[data-toast-id]')).toHaveLength(4);
+ });
+
+ it('shows a toast once under StrictMode, whose replayed effects reconnect the queue', async () => {
+ const onHide = vi.fn();
+ let dismiss: ToastDismissFn | null = null;
+ function ShowsOnce() {
+ const showToast = useToast();
+ useEffect(() => {
+ dismiss = showToast({body: 'Strict', isAutoHide: false, onHide});
+ return () => dismiss?.();
+ }, [showToast]);
+ return null;
+ }
+ const view = render(
+ <StrictMode>
+ <LayerProvider>
+ <ShowsOnce />
+ </LayerProvider>
+ </StrictMode>,
+ );
+ expect(await screen.findByText('Strict')).toBeInTheDocument();
+ expect(document.querySelectorAll('[data-toast-id]')).toHaveLength(1);
+ act(() => {
+ dismiss?.();
+ });
+ expect(onHide).toHaveBeenCalledWith('manual');
+ view.unmount();
+ });
+
+ // Last in the file: the fallback root it creates lives for the whole file.
+ it('without a provider, drops a toast dismissed before the fallback viewport connects, and reports its onHide once', async () => {
+ const onHide = vi.fn();
+ function DismissesAtOnce() {
+ const showToast = useToast();
+ useEffect(() => {
+ showToast({body: 'Dismissed while waiting', onHide})();
+ showToast({body: 'Shown by the fallback', isAutoHide: false});
+ }, [showToast]);
+ return null;
+ }
+ render(<DismissesAtOnce />);
+ expect(onHide.mock.calls).toEqual([['manual']]);
+ expect(
+ await screen.findByText('Shown by the fallback'),
+ ).toBeInTheDocument();
+ expect(screen.queryByText('Dismissed while waiting')).toBeNull();
+ expect(onHide).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/src/Layer/toastHost.tsx b/packages/core/src/Layer/toastHost.tsx
new file mode 100644
index 0000000000..010aabb006
--- /dev/null
+++ b/packages/core/src/Layer/toastHost.tsx
@@ -0,0 +1,212 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file toastHost.tsx
+ * @input The toast viewport that Toast registers, and LayerProvider's toast
+ * configuration
+ * @output ToastContext, registerToastHost, ToastHostOutlet, and the toast
+ * queue that the outlet and useToast's fallback root share
+ * @position Private layer infrastructure. LayerProvider renders the outlet,
+ * and Toast/ToastViewport.tsx registers itself and reads the context.
+ *
+ * SYNC: When modified, update /packages/core/src/Layer/toastHost.test.tsx and
+ * /docs/architecture/layer-runtime.md
+ */
+
+import {
+ createContext,
+ use,
+ useEffect,
+ useState,
+ useSyncExternalStore,
+ type ComponentType,
+ type ReactNode,
+} from 'react';
+import type {ToastDismissReason, ToastEntry} from '../Toast/types';
+import type {LayerInset, LayerToastConfig} from './LayerContext';
+
+/** Internal context value for toast state management. */
+export interface ToastContextValue {
+ /** Add a toast. */
+ addToast: (entry: ToastEntry) => void;
+ /** Remove a toast by ID with a reason. */
+ removeToast: (id: string, reason: ToastDismissReason) => void;
+ /** Find a toast by uniqueID. */
+ findByUniqueID: (uniqueID: string) => ToastEntry | undefined;
+}
+
+/**
+ * React context for toast state. It lives in Layer, so LayerProvider can
+ * provide it without importing Toast. With no provider it is null, and
+ * `useToast` mounts a viewport of its own.
+ */
+export const ToastContext = createContext<ToastContextValue | null>(null);
+ToastContext.displayName = 'ToastContext';
+
+/**
+ * Finds the toast a new one meets by uniqueID, and whether the new one is
+ * dropped. An empty uniqueID names no toast. With a namesake held, an ignored
+ * toast is dropped and an overwrite takes its place. The viewport and the
+ * waiting queue both decide through it, so the rule has one home.
+ */
+export function findToastNamesake<T extends ToastEntry>(
+ held: ReadonlyArray<T>,
+ entry: ToastEntry,
+): {namesake: T | undefined; isDropped: boolean} {
+ const {uniqueID, collisionBehavior = 'overwrite'} = entry.options;
+ const namesake = uniqueID
+ ? held.find(candidate => candidate.options.uniqueID === uniqueID)
+ : undefined;
+ return {
+ namesake,
+ isDropped: namesake != null && collisionBehavior === 'ignore',
+ };
+}
+
+/** The props an outlet gives the registered viewport. */
+export interface ToastHostProps {
+ position?: LayerToastConfig['position'];
+ maxVisible?: LayerToastConfig['maxVisible'];
+ inset?: LayerToastConfig['inset'];
+ layerInset?: LayerInset;
+ children?: ReactNode;
+}
+
+let registeredHost: ComponentType<ToastHostProps> | null = null;
+const hostListeners = new Set<() => void>();
+
+/**
+ * Registers the toast viewport, which every LayerProvider renders from then
+ * on. Toast's viewport module calls it as it loads, so an app that never
+ * imports Toast carries none of it.
+ */
+export function registerToastHost(host: ComponentType<ToastHostProps>): void {
+ if (registeredHost === host) {
+ return;
+ }
+ registeredHost = host;
+ for (const listener of hostListeners) {
+ listener();
+ }
+}
+
+function subscribeToHost(listener: () => void): () => void {
+ hostListeners.add(listener);
+ return () => {
+ hostListeners.delete(listener);
+ };
+}
+
+const readHost = () => registeredHost;
+// The server and the hydrating render show no viewport. The viewport has
+// nothing to show there, and it mounts right after hydration.
+const readNoHost = () => null;
+
+/**
+ * A toast context that holds toasts until a viewport's own context takes
+ * them. LayerProvider's outlet and useToast's fallback root each use one.
+ */
+export interface ToastQueue {
+ /** The context to provide. It forwards to the viewport once one connects. */
+ readonly context: ToastContextValue;
+ /** Connects the viewport's context, or disconnects it with null. */
+ connect: (viewport: ToastContextValue | null) => void;
+}
+
+export function createToastQueue(): ToastQueue {
+ let viewport: ToastContextValue | null = null;
+ let waiting: ToastEntry[] = [];
+ return {
+ context: {
+ addToast: entry => {
+ if (viewport != null) {
+ viewport.addToast(entry);
+ return;
+ }
+ // A waiting toast meets a namesake as the viewport's toasts do.
+ const {namesake, isDropped} = findToastNamesake(waiting, entry);
+ if (isDropped) {
+ return;
+ }
+ waiting =
+ namesake == null
+ ? [...waiting, entry]
+ : waiting.map(candidate =>
+ candidate === namesake ? entry : candidate,
+ );
+ },
+ removeToast: (id, reason) => {
+ if (viewport != null) {
+ viewport.removeToast(id, reason);
+ return;
+ }
+ const entry = waiting.find(candidate => candidate.id === id);
+ if (entry == null) {
+ return;
+ }
+ waiting = waiting.filter(candidate => candidate !== entry);
+ // A toast dismissed while it waits still reports its hide, as the
+ // viewport reports one for a toast that has not rendered yet. A
+ // replaced or ignored namesake is not waiting, so it reports none.
+ entry.options.onHide?.(reason);
+ },
+ findByUniqueID: uniqueID =>
+ viewport == null
+ ? waiting.find(entry => entry.options.uniqueID === uniqueID)
+ : viewport.findByUniqueID(uniqueID),
+ },
+ connect: next => {
+ viewport = next;
+ if (next == null) {
+ return;
+ }
+ const entries = waiting;
+ waiting = [];
+ for (const entry of entries) {
+ next.addToast(entry);
+ }
+ },
+ };
+}
+
+/** Connects a queue to the toast context of the viewport that renders it. */
+export function ToastQueueConnector({queue}: {queue: ToastQueue}) {
+ const viewport = use(ToastContext);
+ // Points the queue at the viewport's toast context once the viewport
+ // commits, so its addToast can set its state. The context changes with the
+ // viewport's props, and the queue stays connected across that change.
+ useEffect(() => {
+ queue.connect(viewport);
+ }, [queue, viewport]);
+ // Disconnects the queue when the viewport unmounts.
+ useEffect(
+ () => () => {
+ queue.connect(null);
+ },
+ [queue],
+ );
+ return null;
+}
+
+/**
+ * LayerProvider's toast outlet. It always provides the toast context, so the
+ * app keeps its place in the tree when the viewport arrives. A toast added
+ * before the viewport can take it waits in the queue, and the toasts that
+ * wait show in order.
+ */
+export function ToastHostOutlet({children, ...config}: ToastHostProps) {
+ const Host = useSyncExternalStore(subscribeToHost, readHost, readNoHost);
+ const [queue] = useState(createToastQueue);
+ return (
+ <ToastContext value={queue.context}>
+ {children}
+ {Host == null ? null : (
+ <Host {...config}>
+ <ToastQueueConnector queue={queue} />
+ </Host>
+ )}
+ </ToastContext>
+ );
+}
diff --git a/packages/core/src/Toast/ToastContext.ts b/packages/core/src/Toast/ToastContext.ts
index 1ecf9ebfd5..cb26f67460 100644
--- a/packages/core/src/Toast/ToastContext.ts
+++ b/packages/core/src/Toast/ToastContext.ts
@@ -2,22 +2,12 @@
'use client';
-import {createContext} from 'react';
-import type {ToastEntry, ToastDismissReason} from './types';
-
-/** Internal context value for toast state management. */
-export interface ToastContextValue {
- /** Add a toast. */
- addToast: (entry: ToastEntry) => void;
- /** Remove a toast by ID with a reason. */
- removeToast: (id: string, reason: ToastDismissReason) => void;
- /** Find a toast by uniqueID. */
- findByUniqueID: (uniqueID: string) => ToastEntry | undefined;
-}
-
/**
- * React context for toast state. Default is null — the hook
- * falls back to a self-mounting viewport when no provider exists.
+ * @file ToastContext.ts
+ * @input Layer's toast host
+ * @output ToastContext and ToastContextValue
+ * @position The context lives in Layer/toastHost.tsx, so LayerProvider can
+ * provide it without importing Toast.
*/
-export const ToastContext = createContext<ToastContextValue | null>(null);
-ToastContext.displayName = 'ToastContext';
+
+export {ToastContext, type ToastContextValue} from '../Layer/toastHost';
diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsx
index 4246baf32b..2c7af6918d 100644
--- a/packages/core/src/Toast/ToastViewport.tsx
+++ b/packages/core/src/Toast/ToastViewport.tsx
@@ -5,7 +5,8 @@
/**
* @file ToastViewport.tsx
* @input Uses React state/effects, ToastContext, content-provider boundary, useAnnounce, viewport tokens,
- * shared layer text reset, the active modal outlet, and placement-derived motion variables
+ * shared layer text reset, the active modal outlet, the layer toast host
+ * registry, and placement-derived motion variables
* @output Exports the ToastViewport provider, stack, live announcement dispatch,
* focus handoff, safe-area-aware edge gutters, modal rehosting, and motion context
* @position Core provider/imperative viewport for useToast()
@@ -49,6 +50,7 @@ import {ToastSurface} from './Toast';
import {ToastContext, type ToastContextValue} from './ToastContext';
import type {ToastEntry, ToastPosition, ToastDismissReason} from './types';
import {layerInsetProperties} from '../Layer/layerInset';
+import {findToastNamesake, registerToastHost} from '../Layer/toastHost';
import type {LayerInset} from '../Layer/LayerContext';
import {
registerEnglishFallback,
@@ -436,20 +438,19 @@ export function ToastViewport({
const addToast = useCallback(
(entry: ToastEntry) => {
- const {uniqueID, collisionBehavior = 'overwrite'} = entry.options;
+ const {uniqueID} = entry.options;
// A toast holds its uniqueID until it unmounts, leaving included
// (Toast.spec.md FR8): an overwrite replaces it in place, and an ignored
// namesake is dropped.
- const holdsUniqueID = (t: ToastEntry) => t.options.uniqueID === uniqueID;
+ const {namesake: overwritten, isDropped} = findToastNamesake(
+ toastsRef.current,
+ entry,
+ );
// Resolve an ignored collision synchronously against the committed list
// so a suppressed toast is neither shown nor announced. The remaining
// announce + setToasts run outside the setToasts updater, which React may
// invoke more than once — keeping the announcement exactly-once.
- if (
- uniqueID &&
- collisionBehavior === 'ignore' &&
- toastsRef.current.some(holdsUniqueID)
- ) {
+ if (isDropped) {
return;
}
// Only text is announced; interactive endContent is reachable via F6.
@@ -464,7 +465,6 @@ export function ToastViewport({
// already reported onHide); otherwise its row would come back collapsed
// when the window reached it again, holding a slot and the landmark.
const committed = toastsRef.current;
- const overwritten = uniqueID ? committed.find(holdsUniqueID) : undefined;
if (overwritten && renderedToastsRef.current.includes(overwritten)) {
replacedRef.current.set(overwritten.id, overwritten);
}
@@ -945,3 +945,7 @@ export function ToastViewport({
);
}
ToastViewport.displayName = 'ToastViewport';
+
+// LayerProvider renders the viewport once this module loads. So an app that
+// never imports Toast carries none of its code.
+registerToastHost(ToastViewport);
diff --git a/packages/core/src/Toast/useToast.test.tsx b/packages/core/src/Toast/useToast.test.tsx
index 5fae53c906..00d5ec3154 100644
--- a/packages/core/src/Toast/useToast.test.tsx
+++ b/packages/core/src/Toast/useToast.test.tsx
@@ -142,11 +142,9 @@ describe('useToast fallback viewport theme mode', () => {
await waitFor(() => {
expect(document.documentElement).toHaveAttribute('data-theme', 'light');
});
- // Whichever test clicks first in this file finds the fallback proxy still
- // pending: addToast queues the entry and kicks off the ctxReady.then(...)
- // microtask that later delivers it to the real context. Awaiting an async
- // act() flushes that chain instead of letting it resolve outside any act
- // scope.
+ // Whichever test clicks first in this file finds the fallback viewport
+ // not yet connected, so its toast waits in the queue. The queue hands it
+ // over in the viewport's effect, and an async act() flushes that effect.
await act(async () => {
fireEvent.click(screen.getByText('Trigger branded'));
});
diff --git a/packages/core/src/Toast/useToast.tsx b/packages/core/src/Toast/useToast.tsx
index 084fadbcb3..cb523c8db0 100644
--- a/packages/core/src/Toast/useToast.tsx
+++ b/packages/core/src/Toast/useToast.tsx
@@ -2,11 +2,12 @@
'use client';
-import {useCallback, use, useEffect, useRef} from 'react';
+import {useCallback, use} from 'react';
import {createRoot} from 'react-dom/client';
import {dataAttr} from '../naming';
import {ToastContext, type ToastContextValue} from './ToastContext';
import {ToastViewport} from './ToastViewport';
+import {createToastQueue, ToastQueueConnector} from '../Layer/toastHost';
import {ThemeNestingContext} from '../theme/Theme';
import {warnOnce} from '../utils/devWarning';
import type {
@@ -83,67 +84,21 @@ function getFallbackContext(): ToastContextValue {
document.body.appendChild(container);
syncRootThemeAttrs(container);
- let resolveCtx: ((ctx: ToastContextValue) => void) | undefined;
- const ctxReady = new Promise<ToastContextValue>(r => {
- resolveCtx = r;
- });
-
- const FallbackCapture = () => {
- const ctx = use(ToastContext);
- const doneRef = useRef(false);
- // Syncs the module-level fallback with the first toast context that mounts.
- useEffect(() => {
- if (ctx && !doneRef.current) {
- doneRef.current = true;
- fallbackContext = ctx;
- resolveCtx?.(ctx);
- }
- }, [ctx]);
- return null;
- };
-
+ // Toasts wait in the queue until the fallback viewport's context connects.
+ const queue = createToastQueue();
fallbackRoot = createRoot(container);
// This root sits inside the app, so a <Theme> in toast content is nested:
// it themes its own subtree and leaves the app's <html> sync alone.
fallbackRoot.render(
<ThemeNestingContext value={true}>
<ToastViewport>
- <FallbackCapture />
+ <ToastQueueConnector queue={queue} />
</ToastViewport>
</ThemeNestingContext>,
);
- // Proxy that queues calls until real context is captured
- const pending: ToastEntry[] = [];
- const proxy: ToastContextValue = {
- addToast: entry => {
- if (fallbackContext && fallbackContext !== proxy) {
- fallbackContext.addToast(entry);
- } else {
- pending.push(entry);
- void ctxReady.then(ctx => {
- for (const e of pending) {
- ctx.addToast(e);
- }
- pending.length = 0;
- });
- }
- },
- removeToast: (id, reason) => {
- if (fallbackContext && fallbackContext !== proxy) {
- fallbackContext.removeToast(id, reason);
- }
- },
- findByUniqueID: uid => {
- if (fallbackContext && fallbackContext !== proxy) {
- return fallbackContext.findByUniqueID(uid);
- }
- return undefined;
- },
- };
-
- fallbackContext = proxy;
- return proxy;
+ fallbackContext = queue.context;
+ return queue.context;
}
let toastIdCounter = 0;
diff --git a/scripts/layer-toast-bundle.test.mjs b/scripts/layer-toast-bundle.test.mjs
new file mode 100644
index 0000000000..749e45b728
--- /dev/null
+++ b/scripts/layer-toast-bundle.test.mjs
@@ -0,0 +1,141 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file layer-toast-bundle.test.mjs
+ * @input Core's source, bundled with the PR size report's esbuild options
+ * (.github/scripts/lib/component-size.js)
+ * @output Proves an import of Layer loads none of Toast's modules. An import
+ * of useToast loads the viewport it registers with LayerProvider, and the
+ * swipe code with no import() in between
+ * @position Node test over source, so it needs no build. Its build files live
+ * under the repository's `node_modules/.cache`, never the system temp
+ * directory, whose listing esbuild would read for every build
+ */
+
+import fs from 'node:fs';
+import {createRequire} from 'node:module';
+import path from 'node:path';
+import {afterAll, beforeAll, describe, expect, it} from 'vitest';
+
+const REPO = path.resolve(import.meta.dirname, '..');
+const CORE_SRC = path.join(REPO, 'packages/core/src');
+const require = createRequire(path.join(REPO, 'package.json'));
+const esbuild = require('esbuild');
+
+const TOAST_MODULE = /^packages\/core\/src\/Toast\//;
+
+const CACHE = path.join(REPO, 'node_modules/.cache/astryx-layer-toast-bundle');
+let scratch = '';
+beforeAll(() => {
+ fs.mkdirSync(CACHE, {recursive: true});
+ scratch = fs.mkdtempSync(path.join(CACHE, 'run-'));
+});
+afterAll(() => {
+ fs.rmSync(scratch, {recursive: true, force: true});
+});
+
+/**
+ * The size report's build of a component import (minified ESM for the
+ * browser). React and StyleX stay external.
+ */
+const BUILD_OPTIONS = {
+ absWorkingDir: REPO,
+ // Never written (`write: false`): it only names the outputs.
+ outdir: path.join(CACHE, 'out'),
+ bundle: true,
+ minify: true,
+ format: 'esm',
+ platform: 'browser',
+ define: {'process.env.NODE_ENV': '"production"'},
+ loader: {'.css': 'empty'},
+ external: [
+ 'react',
+ 'react/*',
+ 'react-dom',
+ 'react-dom/*',
+ '@stylexjs/stylex',
+ ],
+ metafile: true,
+ write: false,
+ logLevel: 'silent',
+ splitting: true,
+};
+
+/**
+ * The source modules that load with an import of `source`: its output and
+ * every chunk that output imports statically, not those behind an `import()`.
+ */
+function modulesLoadedBy(name, source) {
+ const file = path.join(scratch, `${name}.ts`);
+ fs.writeFileSync(file, source);
+ const {outputs} = esbuild.buildSync({
+ ...BUILD_OPTIONS,
+ entryPoints: [file],
+ }).metafile;
+ const loaded = new Set();
+ const load = output => {
+ if (loaded.has(output)) {
+ return;
+ }
+ loaded.add(output);
+ for (const {path: chunk, kind} of outputs[output].imports) {
+ if (kind === 'import-statement' && chunk in outputs) {
+ load(chunk);
+ }
+ }
+ };
+ load(
+ Object.keys(outputs).find(
+ output => outputs[output].entryPoint === path.relative(REPO, file),
+ ),
+ );
+ const modules = new Set();
+ for (const output of loaded) {
+ for (const [input, {bytesInOutput}] of Object.entries(
+ outputs[output].inputs,
+ )) {
+ if (bytesInOutput > 0) {
+ modules.add(input);
+ }
+ }
+ }
+ return modules;
+}
+
+const LAYER = JSON.stringify(path.join(CORE_SRC, 'Layer/index.ts'));
+const CORE = JSON.stringify(path.join(CORE_SRC, 'index.ts'));
+
+describe('Layer and Toast in bundles', () => {
+ it('loads no Toast module with LayerProvider', () => {
+ const modules = modulesLoadedBy(
+ 'layer-provider',
+ `export {LayerProvider} from ${LAYER};\n`,
+ );
+ expect(modules.has('packages/core/src/Layer/toastHost.tsx')).toBe(true);
+ expect([...modules].filter(input => TOAST_MODULE.test(input))).toEqual([]);
+ });
+
+ it('loads no Toast module with the whole Layer entry', () => {
+ const modules = modulesLoadedBy('layer', `export * from ${LAYER};\n`);
+ expect([...modules].filter(input => TOAST_MODULE.test(input))).toEqual([]);
+ });
+
+ it('loads the viewport that useToast registers with LayerProvider', () => {
+ const modules = modulesLoadedBy(
+ 'layer-provider-and-use-toast',
+ `export {LayerProvider, useToast} from ${CORE};\n`,
+ );
+ expect(modules.has('packages/core/src/Toast/ToastViewport.tsx')).toBe(true);
+ expect(modules.has('packages/core/src/Layer/toastHost.tsx')).toBe(true);
+ });
+
+ it('loads the swipe code with useToast, not behind an import()', () => {
+ const modules = modulesLoadedBy(
+ 'use-toast-swipe',
+ `export {useToast} from ${CORE};\n`,
+ );
+ expect(modules.has('packages/core/src/Toast/useToastGesture.ts')).toBe(
+ true,
+ );
+ });
+});