Skip to content

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

TypeScript

fix(Layer): a swizzled LayerProvider shows the package's toasts (#10800)

Cindy Zhang49bc221f586c
diff --git a/.changeset/layer-toast-host-swizzle.md b/.changeset/layer-toast-host-swizzle.md
new file mode 100644
index 0000000000..88fc912c21
--- /dev/null
+++ b/.changeset/layer-toast-host-swizzle.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A swizzled `LayerProvider` now shows the package's toasts: the viewport the package's `Toast` registers renders in a copied provider's outlet, and the package's provider renders a copy's. Before, each copy kept its own registry, so toasts added under a swizzled provider never showed. The registry lives under a registered, versioned key. No API changes.
+
+@cixzhang
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 6b215ab979..16f6ff3593 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -803,7 +803,9 @@ it on the surface inside the layer and run no layout while it plays.
shared dismissal stack owns Escape and platform close routing.
- `Layer/toastHost.tsx` owns `ToastContext`, Toast's viewport registration, and
the toast queue that LayerProvider's outlet and `useToast`'s fallback root
- both use. `LayerProvider`, `useToast`, and `ToastViewport` own current
+ both use. The viewport registration lives under a versioned key, one per
+ React, so every copy of Core on one React renders the same registered
+ viewport (`spec:AST-110` FR3). `LayerProvider`, `useToast`, and `ToastViewport` own current
notification state, dispatch, and viewport rendering; the viewport sits at
the provider's inset on each edge unless its own `toast.inset` overrides that
edge.
diff --git a/packages/core/src/Layer/toastHost.lateRegistration.test.tsx b/packages/core/src/Layer/toastHost.lateRegistration.test.tsx
index b1254496f1..19b2126fd3 100644
--- a/packages/core/src/Layer/toastHost.lateRegistration.test.tsx
+++ b/packages/core/src/Layer/toastHost.lateRegistration.test.tsx
@@ -8,8 +8,9 @@
* 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.
+ * @position Unit tests for Layer/toastHost.tsx. Each test forgets the
+ * registered viewport and reloads the modules, so Toast's registration is
+ * fresh in each one.
*/
import {act, render, screen} from '@testing-library/react';
@@ -33,7 +34,11 @@ async function loadViewport() {
await viewportLoad;
}
-beforeEach(() => {
+beforeEach(async () => {
+ // The registered viewport is shared across module loads (spec:AST-110
+ // FR3), so each test forgets it before it reloads the modules.
+ const {__resetToastHostForTest} = await import('./toastHost');
+ __resetToastHostForTest();
vi.resetModules();
});
diff --git a/packages/core/src/Layer/toastHost.shared.test.tsx b/packages/core/src/Layer/toastHost.shared.test.tsx
new file mode 100644
index 0000000000..1c8cd8c855
--- /dev/null
+++ b/packages/core/src/Layer/toastHost.shared.test.tsx
@@ -0,0 +1,88 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file toastHost.shared.test.tsx
+ * @input Two loads of the toast host module, as the package and a swizzled
+ * copy of LayerProvider each carry one
+ * @output Proves a viewport the package's Toast registers renders in a copied
+ * LayerProvider's outlet, before and after the outlet mounts, and that a
+ * viewport registered on another React does not
+ * @position Unit tests for Layer/toastHost.tsx (spec:AST-110 FR3)
+ */
+
+import {createRequire} from 'node:module';
+import {act, render, screen} from '@testing-library/react';
+import type {ReactNode} from 'react';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+
+/**
+ * A second instance of React, as a page that loads two React copies has.
+ * Node keeps one instance per resolved file, so drop React's files from the
+ * require cache, load it again, then put the first instance back.
+ */
+function secondReact(): typeof import('react') {
+ const require = createRequire(import.meta.url);
+ const isReactFile = (file: string) =>
+ /[\\/]node_modules[\\/]react[\\/]/.test(file);
+ const saved = Object.keys(require.cache)
+ .filter(isReactFile)
+ .map(file => [file, require.cache[file]] as const);
+ for (const [file] of saved) {
+ Reflect.deleteProperty(require.cache, file);
+ }
+ try {
+ return require('react') as typeof import('react');
+ } finally {
+ for (const [file, module] of saved) {
+ require.cache[file] = module;
+ }
+ }
+}
+
+function Host({children}: {children?: ReactNode}) {
+ return <div data-testid="toast-host">{children}</div>;
+}
+
+afterEach(async () => {
+ const toastHost = await import('./toastHost');
+ toastHost.__resetToastHostForTest();
+ vi.resetModules();
+});
+
+describe('the toast host a swizzled LayerProvider shares', () => {
+ it("renders the viewport the package registered in a copy's outlet", async () => {
+ const pkg = await import('./toastHost');
+ vi.resetModules();
+ const copy = await import('./toastHost');
+ expect(copy).not.toBe(pkg);
+ pkg.registerToastHost(Host);
+ render(<copy.ToastHostOutlet>app</copy.ToastHostOutlet>);
+ expect(screen.getByTestId('toast-host')).toBeInTheDocument();
+ });
+
+ it("keeps a viewport registered on another React out of this React's outlet", async () => {
+ const otherReact = secondReact();
+ vi.resetModules();
+ vi.doMock('react', () => ({...otherReact, default: otherReact}));
+ const onOtherReact = await import('./toastHost');
+ vi.doUnmock('react');
+ onOtherReact.registerToastHost(Host);
+ vi.resetModules();
+ const onThisReact = await import('./toastHost');
+ render(<onThisReact.ToastHostOutlet>app</onThisReact.ToastHostOutlet>);
+ expect(screen.queryByTestId('toast-host')).toBeNull();
+ onOtherReact.__resetToastHostForTest();
+ });
+
+ it("renders a viewport registered after a copy's outlet mounted", async () => {
+ const pkg = await import('./toastHost');
+ vi.resetModules();
+ const copy = await import('./toastHost');
+ render(<copy.ToastHostOutlet>app</copy.ToastHostOutlet>);
+ expect(screen.queryByTestId('toast-host')).toBeNull();
+ act(() => {
+ pkg.registerToastHost(Host);
+ });
+ expect(screen.getByTestId('toast-host')).toBeInTheDocument();
+ });
+});
diff --git a/packages/core/src/Layer/toastHost.tsx b/packages/core/src/Layer/toastHost.tsx
index c0e913a6e9..111d140b6b 100644
--- a/packages/core/src/Layer/toastHost.tsx
+++ b/packages/core/src/Layer/toastHost.tsx
@@ -16,6 +16,7 @@
*/
import {
+ createContext,
use,
useEffect,
useState,
@@ -26,6 +27,7 @@ import {
import type {ToastDismissReason, ToastEntry} from '../Toast/types';
import type {LayerInset, LayerToastConfig} from './LayerContext';
import {createSharedContext} from '../utils/sharedContext';
+import {realmValue, sharedKey} from '../utils/sharedRealm';
/** Internal context value for toast state management. */
export interface ToastContextValue {
@@ -78,8 +80,27 @@ export interface ToastHostProps {
children?: ReactNode;
}
-let registeredHost: ComponentType<ToastHostProps> | null = null;
-const hostListeners = new Set<() => void>();
+interface ToastHostRegistry {
+ host: ComponentType<ToastHostProps> | null;
+ readonly listeners: Set<() => void>;
+}
+
+// Every copy of Core on this React uses one registry, so a swizzled
+// LayerProvider renders the viewport the package's Toast registers. The
+// registry holds a component, so a copy on another React keeps its own.
+const hostRegistry = (() => {
+ const byReact = realmValue(
+ sharedKey('layer/toast-host', 1),
+ () => new WeakMap<typeof createContext, ToastHostRegistry>(),
+ value => value instanceof WeakMap,
+ );
+ let registry = byReact.get(createContext);
+ if (registry == null) {
+ registry = {host: null, listeners: new Set()};
+ byReact.set(createContext, registry);
+ }
+ return registry;
+})();
/**
* Registers the toast viewport, which every LayerProvider renders from then
@@ -87,23 +108,28 @@ const hostListeners = new Set<() => void>();
* imports Toast carries none of it.
*/
export function registerToastHost(host: ComponentType<ToastHostProps>): void {
- if (registeredHost === host) {
+ if (hostRegistry.host === host) {
return;
}
- registeredHost = host;
- for (const listener of hostListeners) {
+ hostRegistry.host = host;
+ for (const listener of hostRegistry.listeners) {
listener();
}
}
+/** Test-only: forget the registered viewport, as on a fresh page. */
+export function __resetToastHostForTest(): void {
+ hostRegistry.host = null;
+}
+
function subscribeToHost(listener: () => void): () => void {
- hostListeners.add(listener);
+ hostRegistry.listeners.add(listener);
return () => {
- hostListeners.delete(listener);
+ hostRegistry.listeners.delete(listener);
};
}
-const readHost = () => registeredHost;
+const readHost = () => hostRegistry.host;
// 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;