Skip to content

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

TypeScript

fix(Toast): pass dismiss to renderContent (#5655)

Cindy Zhangc84106ba2679
diff --git a/.changeset/toast-render-content.md b/.changeset/toast-render-content.md
index 04dd1812d9..8cbd0cdd3b 100644
--- a/.changeset/toast-render-content.md
+++ b/.changeset/toast-render-content.md
@@ -7,26 +7,22 @@
```tsx
showToast({
body: 'Your changes have been saved.',
- renderContent: ({body, endContent, DismissButton}) => (
+ renderContent: ({body, endContent, dismiss}) => (
<MyRow>
<MyTitle>{body}</MyTitle>
{endContent}
- <DismissButton />
+ <Button label="Dismiss notification" onClick={dismiss} />
</MyRow>
),
});
```
-Astryx keeps the card — its surface, its `astryx-toast` theme target, the live-region role and the auto-hide timer with its pause on hover, focus and window blur — and hands the renderer the message, the `endContent`, and a **`DismissButton`** to place.
+Astryx keeps the card, its `astryx-toast` theme target, live-region role and auto-hide behavior. The renderer receives the message, `endContent`, resolved toast settings and a `dismiss` callback.
-`DismissButton` renders Astryx's own close: the ghost icon `Button` with the translated `@astryx.toast.dismiss` label and the `astryx-button` theme target. A layout positions the close rather than rebuilding it, so it cannot be mislabelled — and **a layout that never renders it does not produce a toast with no way out**. The close then appears in the card's default corner instead. Registration follows the button's own mount and unmount, so if a deeply nested layout removes it from its own state later, the corner fallback returns in that same commit. On the server and during hydration's first render, the fallback is the one close in the markup; the placed button claims its position before the first client paint, so there is exactly one throughout SSR and hydration. Rendering it twice renders two closes and warns in development.
+Custom content owns its complete layout and every control in it. Call `dismiss` from the control that should close the toast; it may be passed through nested components. Astryx does not register an injected component or add a fallback close behind a custom layout.
-Absence is a default, not a hole: nothing suppresses anything, and a toast always has an exit.
-
-It is per-toast rather than app-wide on purpose. An app that wants one layout across its own toasts wraps `useToast()` once and passes `renderContent` on every call; a toast raised by library code that knows nothing about that wrapper then renders as an ordinary Astryx toast — intact and dismissible — rather than inheriting a layout written for someone else's payload.
+The API is per-toast. An app can share one layout by wrapping `useToast()` and passing `renderContent` on each call, while other toasts continue to use the ordinary Astryx layout and its translated, themeable dismiss `Button`.
New exported types: `ToastContentRenderProps`, `ToastContentRenderFn`.
-No change to any existing toast: omit `renderContent` and the rendered output, the timers and the DOM are exactly as before.
-
@freddymeta
diff --git a/apps/storybook/stories/Toast.stories.tsx b/apps/storybook/stories/Toast.stories.tsx
index 0a0be09c21..0b0981dfff 100644
--- a/apps/storybook/stories/Toast.stories.tsx
+++ b/apps/storybook/stories/Toast.stories.tsx
@@ -868,7 +868,7 @@ function ProductToastContent({
type,
body,
endContent,
- DismissButton,
+ dismiss,
}: ToastContentRenderProps) {
return (
<div {...stylex.props(customContentStyles.row)}>
@@ -882,14 +882,17 @@ function ProductToastContent({
/>
<div {...stylex.props(customContentStyles.text)}>{body}</div>
{endContent}
- <DismissButton />
+ <Button
+ label="Dismiss custom toast"
+ variant="ghost"
+ size="sm"
+ onClick={dismiss}
+ />
</div>
);
}
-// The same layout with the close left out. Astryx keeps it dismissible by
-// putting the close in the card's corner.
-function ForgetfulToastContent({type, body}: ToastContentRenderProps) {
+function ContentWithoutDismiss({type, body}: ToastContentRenderProps) {
return (
<div {...stylex.props(customContentStyles.row)}>
<div
@@ -947,14 +950,13 @@ export const CustomContent: StoryObj = {
}}
/>
<Button
- label="Layout without the close"
+ label="Layout without a close"
variant="ghost"
onClick={() => {
toast({
- body: 'This layout never renders DismissButton.',
- type: 'error',
+ body: 'This layout relies on auto-hide.',
renderContent: toastProps => (
- <ForgetfulToastContent {...toastProps} />
+ <ContentWithoutDismiss {...toastProps} />
),
});
}}
@@ -973,7 +975,7 @@ export const CustomContent: StoryObj = {
docs: {
description: {
story:
- "`renderContent` replaces the content of one toast's card. Astryx keeps the transport and hands over the message, `endContent` and a `DismissButton` to place. If a nested layout removes that button later, Astryx immediately restores its corner close. The last button omits `renderContent`, showing that a library-raised toast keeps the ordinary Astryx layout.",
+ "`renderContent` replaces the content of one toast's card and receives a `dismiss` callback. The custom layout composes its own Astryx `Button`; a layout without a close is left as-is and can rely on auto-hide. The last button omits `renderContent`, showing the ordinary Astryx layout and dismiss control.",
},
},
},
diff --git a/packages/core/src/Toast/Toast.doc.mjs b/packages/core/src/Toast/Toast.doc.mjs
index a79c8c4c6a..e59f8652a8 100644
--- a/packages/core/src/Toast/Toast.doc.mjs
+++ b/packages/core/src/Toast/Toast.doc.mjs
@@ -70,7 +70,7 @@ export const docs = {
name: 'renderContent',
type: '(toast: ToastContentRenderProps) => ReactNode',
description:
- "Replaces the content of this toast's card with your own layout. Astryx keeps the card, its astryx-toast theme target, the live-region role and the auto-hide timer, and hands the renderer the message, the endContent and a DismissButton component to place — so the close stays themeable, translated and correctly named rather than something a custom layout has to rebuild. A layout that never renders DismissButton does not produce a toast with no way out: Astryx renders the close in the card's default corner instead. Per-toast: an app shares one layout by wrapping useToast and passing it on every call, while a toast raised by library code that never passes it renders as an ordinary Astryx toast. The argument is {body, endContent, DismissButton, type, isAutoHide, autoHideDuration, dismiss}, where type is 'info' | 'error'.",
+ "Replaces the content of this toast's card with your own layout. Astryx keeps the card, its astryx-toast theme target, the live-region role and auto-hide behavior, then hands the renderer the message, endContent, resolved toast settings and a dismiss callback. The custom renderer owns every control in its layout: compose the control you want and call dismiss from it. Astryx does not inject a fallback close into custom content. Per-toast: an app shares one layout by wrapping useToast and passing it on every call, while a toast raised by library code that never passes it renders as an ordinary Astryx toast. The argument is {body, endContent, type, isAutoHide, autoHideDuration, dismiss}, where type is 'info' | 'error'.",
},
], theming: {
targets: [
@@ -124,7 +124,7 @@ export const docsZh = {
collisionBehavior: '当已存在相同 uniqueID 的 toast 时的行为。',
onHide: '当 toast 被移除时触发的回调。',
renderContent:
- "用你自己的布局替换该 toast 卡片内部的内容。Astryx 保留卡片本身、astryx-toast 主题目标、实时区域角色以及自动关闭计时器,并把消息、endContent 和一个 DismissButton 组件交给渲染函数放置——因此关闭控件仍然可主题化、已翻译且具备正确的无障碍名称,无需自行重建。若布局始终不渲染 DismissButton,也不会得到无法关闭的 toast:Astryx 会改为在卡片默认的角落位置渲染关闭按钮。按 toast 单独设置:应用可通过封装 useToast 并在每次调用时传入来共享同一套布局;而由库代码发起、从不传入该参数的 toast 会渲染为普通的 Astryx toast。传入参数为 {body, endContent, DismissButton, type, isAutoHide, autoHideDuration, dismiss},其中 type 为 'info' | 'error'。",
+ "用你自己的布局替换该 toast 卡片内部的内容。Astryx 保留卡片本身、astryx-toast 主题目标、实时区域角色和自动关闭行为,并把消息、endContent、解析后的 toast 设置和 dismiss 回调交给渲染函数。自定义渲染函数完全拥有布局中的控件:请组合所需的控件并通过它调用 dismiss。Astryx 不会向自定义内容注入后备关闭按钮。按 toast 单独设置:应用可通过封装 useToast 并在每次调用时传入来共享同一套布局;而由库代码发起、从不传入该参数的 toast 会渲染为普通的 Astryx toast。传入参数为 {body, endContent, type, isAutoHide, autoHideDuration, dismiss},其中 type 为 'info' | 'error'。",
},
usage: {
description:
@@ -172,5 +172,6 @@ export const docsDense = {
uniqueID: 'unique id for dedup',
collisionBehavior: 'behavior when matching uniqueID exists',
onHide: 'callback when toast removed',
+ renderContent: 'custom inner layout; receives content, resolved settings + dismiss callback; no injected fallback control',
},
};
diff --git a/packages/core/src/Toast/Toast.tsx b/packages/core/src/Toast/Toast.tsx
index 836b112b11..901fcbb680 100644
--- a/packages/core/src/Toast/Toast.tsx
+++ b/packages/core/src/Toast/Toast.tsx
@@ -17,7 +17,7 @@
* - /packages/cli/assets/templates/blocks/components/Toast/ (showcase blocks)
*/
-import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import {useCallback, useEffect, useRef} from 'react';
import type {ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Button} from '../Button';
@@ -42,14 +42,10 @@ import type {
} from './types';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
-import {devWarn} from '../utils/devWarning';
-import {DismissButton, ToastDismissSlotProvider} from './ToastDismissSlot';
const TOAST_EDGE_DRIFT = spacingVars['--spacing-2'];
const styles = stylex.create({
root: {
- // Containing block for the fallback close below.
- position: 'relative',
paddingBlock: spacingVars['--spacing-4'],
paddingInline: spacingVars['--spacing-4'],
borderRadius: radiusVars['--radius-container'],
@@ -108,14 +104,6 @@ const styles = stylex.create({
blockSize: `calc(${typeScaleDefaults['--text-body-size']} * ${typeScaleDefaults['--text-body-leading']})`,
marginInlineEnd: `calc(${spacingVars['--spacing-1']} * -1)`,
},
- // Where the close goes when a `renderContent` layout did not place it: the
- // same corner the default layout puts it in. Positioned rather than
- // appended so it cannot reflow a layout that was not expecting it.
- fallbackDismiss: {
- position: 'absolute',
- insetBlockStart: spacingVars['--spacing-3'],
- insetInlineEnd: spacingVars['--spacing-3'],
- },
});
export interface ToastProps {
@@ -134,61 +122,6 @@ export interface ToastProps {
renderContent?: ToastContentRenderFn;
}
-interface ToastCustomContentProps {
- children: ReactNode;
- dismissButton: ReactNode;
-}
-
-/**
- * Owns the dismiss slot only for a custom layout. Keeping this state outside
- * `Toast` matters twice: an ordinary toast pays no registration render at all,
- * and a nested custom component can mount/unmount `DismissButton` from its own
- * state without needing `Toast` itself to rerender.
- */
-function ToastCustomContent({
- children,
- dismissButton,
-}: ToastCustomContentProps) {
- const [dismissCount, setDismissCount] = useState(0);
- const registerDismiss = useCallback(() => {
- let isRegistered = true;
- setDismissCount(count => count + 1);
- return () => {
- if (!isRegistered) {
- return;
- }
- isRegistered = false;
- setDismissCount(count => Math.max(0, count - 1));
- };
- }, []);
- const slot = useMemo(
- () => ({button: dismissButton, register: registerDismiss}),
- [dismissButton, registerDismiss],
- );
-
- useEffect(() => {
- if (dismissCount > 1) {
- devWarn(
- 'Toast',
- `renderContent rendered DismissButton ${dismissCount} times — this ` +
- 'toast has that many close buttons. Render it once.',
- );
- }
- }, [dismissCount]);
-
- return (
- <ToastDismissSlotProvider value={slot}>
- {children}
- {/* Start with the safe default. A placed DismissButton registers in a
- layout effect and removes this before paint; if a nested layout later
- unmounts it, cleanup restores this in the same commit. */}
- {dismissCount === 0 && (
- <div {...stylex.props(styles.fallbackDismiss)}>{dismissButton}</div>
- )}
- </ToastDismissSlotProvider>
- );
-}
-
/**
* Individual toast notification.
*
@@ -298,24 +231,6 @@ export function Toast({
onDismiss('manual');
}, [onDismiss]);
- // Built here rather than inside the default layout so a `renderContent`
- // layout places the very same control: Astryx's close, with its translated
- // label and its `astryx-button` theming, instead of one the layout has to
- // rebuild and get those right itself.
- const dismissButton = useMemo(
- () => (
- <Button
- variant="ghost"
- size="sm"
- icon={<Icon icon="close" size="sm" color="inherit" />}
- label={t('@astryx.toast.dismiss')}
- onClick={handleDismiss}
- isIconOnly
- />
- ),
- [t, handleDismiss],
- );
-
const isError = type === 'error';
// The surface is *usually* dark in light mode and light in dark mode, but a
// theme can define --color-background-inverted as anything — so the mode is
@@ -342,24 +257,28 @@ export function Toast({
)}>
<MediaTheme mode="auto" fallback={fallbackMediaMode}>
{renderContent ? (
- <ToastCustomContent dismissButton={dismissButton}>
- {renderContent({
- body,
- endContent,
- DismissButton,
- type,
- isAutoHide,
- autoHideDuration,
- dismiss: handleDismiss,
- })}
- </ToastCustomContent>
+ renderContent({
+ body,
+ endContent,
+ type,
+ isAutoHide,
+ autoHideDuration,
+ dismiss: handleDismiss,
+ })
) : (
<div {...stylex.props(styles.inner)}>
<div {...stylex.props(styles.content)}>{body}</div>
<div {...stylex.props(styles.endContent)}>
{endContent}
- {dismissButton}
+ <Button
+ variant="ghost"
+ size="sm"
+ icon={<Icon icon="close" size="sm" color="inherit" />}
+ label={t('@astryx.toast.dismiss')}
+ onClick={handleDismiss}
+ isIconOnly
+ />
</div>
</div>
)}
diff --git a/packages/core/src/Toast/ToastDismissSlot.tsx b/packages/core/src/Toast/ToastDismissSlot.tsx
deleted file mode 100644
index 0bd80e8cfb..0000000000
--- a/packages/core/src/Toast/ToastDismissSlot.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-'use client';
-
-/**
- * @file ToastDismissSlot.tsx
- * @input A toast's own dismiss control, provided by `Toast`
- * @output `DismissButton` for a `renderContent` layout, plus the claim
- * bookkeeping that lets `Toast` know whether the layout placed it
- * @position Internal to Toast; `DismissButton` is handed to `renderContent`
- * rather than imported by consumers.
- *
- * A custom layout places the close by rendering `<DismissButton />`. Mounting
- * it *claims* the toast's dismiss slot, and `Toast` renders its own close in
- * the card's corner when nothing claimed it — so a layout that forgets the
- * control produces a toast with a close in the default position rather than a
- * toast with no way out.
- *
- * Claiming is a mount-time registration rather than a DOM scan because the
- * layout may place the control anywhere: nested inside its own components,
- * behind a conditional, or passed on as someone else's prop. Rendering it is
- * the claim, wherever it ends up.
- *
- * SYNC: When modified, update:
- * - /packages/core/src/Toast/Toast.tsx (provides the slot, renders the fallback)
- * - /packages/core/src/Toast/types.ts (ToastContentRenderProps.DismissButton)
- */
-
-import {createContext, use, useSyncExternalStore} from 'react';
-import type {ReactNode} from 'react';
-import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
-import {devWarn} from '../utils/devWarning';
-
-interface ToastDismissSlot {
- /** The toast's own dismiss control, already built. */
- button: ReactNode;
- /** Register one mounted DismissButton; cleanup unregisters it. */
- register: () => () => void;
-}
-
-const ToastDismissSlotContext = createContext<ToastDismissSlot | null>(null);
-ToastDismissSlotContext.displayName = 'ToastDismissSlotContext';
-
-export const ToastDismissSlotProvider = ToastDismissSlotContext.Provider;
-
-// `useSyncExternalStore` gives this leaf a hydration-safe server/client split
-// without setting state in an effect: false in server output and hydration's
-// first render, true in ordinary client rendering and immediately afterwards.
-const subscribeToClient = () => () => {};
-const getClientSnapshot = () => true;
-const getServerSnapshot = () => false;
-
-/**
- * The toast's close, placed by a `renderContent` layout.
- *
- * Rendering it puts Astryx's own dismiss control at that spot — the same ghost
- * icon `Button`, with the translated `@astryx.toast.dismiss` label and the
- * `astryx-button` theme target. Omitting it is allowed: the toast then renders
- * its close in the card's default corner.
- */
-export function DismissButton(): ReactNode {
- const slot = use(ToastDismissSlotContext);
- // Start absent on the server and on hydration's first render, where the
- // provider's corner fallback is the one close in the markup. The external-
- // store snapshots switch this leaf to the placed control on the client
- // without a synchronous setState in an effect.
- const isClient = useSyncExternalStore(
- subscribeToClient,
- getClientSnapshot,
- getServerSnapshot,
- );
- useIsomorphicLayoutEffect(() => {
- if (slot == null) {
- return;
- }
- return slot.register();
- }, [slot]);
- if (slot == null) {
- devWarn(
- 'Toast',
- 'DismissButton was rendered outside a toast. It is the `DismissButton` ' +
- "passed to `renderContent`, not an import — render the one you're given.",
- );
- return null;
- }
- return isClient ? slot.button : null;
-}
-
-DismissButton.displayName = 'Toast.DismissButton';
diff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsx
index b5c48c82d4..8640dca16a 100644
--- a/packages/core/src/Toast/ToastViewport.test.tsx
+++ b/packages/core/src/Toast/ToastViewport.test.tsx
@@ -30,9 +30,7 @@ import {
waitFor,
within,
} from '@testing-library/react';
-import React, {useState} from 'react';
-import {hydrateRoot} from 'react-dom/client';
-import {renderToString} from 'react-dom/server';
+import React from 'react';
import {readFileSync} from 'node:fs';
import {type AnnounceFn, __resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {Button} from '../Button';
@@ -722,43 +720,6 @@ describe('Toast native motion contract', () => {
});
describe('Toast live-region fallback semantics', () => {
- it('server-renders and hydrates one dismiss control for custom content', async () => {
- const tree = (
- <Toast
- type="error"
- body="Upload failed"
- isAutoHide={false}
- autoHideDuration={5000}
- onDismiss={() => {}}
- renderContent={({body, DismissButton}) => (
- <div>
- {body}
- <DismissButton />
- </div>
- )}
- />
- );
- const serverHTML = renderToString(tree);
- expect(serverHTML.match(/Dismiss notification/g)).toHaveLength(1);
-
- const container = document.createElement('div');
- container.innerHTML = serverHTML;
- document.body.appendChild(container);
- let root: ReturnType<typeof hydrateRoot> | undefined;
- await act(async () => {
- root = hydrateRoot(container, tree);
- });
- expect(
- within(container).getAllByRole('button', {
- name: 'Dismiss notification',
- }),
- ).toHaveLength(1);
- await act(async () => {
- root?.unmount();
- });
- container.remove();
- });
-
it('keeps standalone info Toast content in a polite status region', () => {
render(
<Toast
@@ -1053,127 +1014,152 @@ describe('toast timer lifecycle (#3589)', () => {
}
});
- // `renderContent` rides the `showToast` options and replaces the content of
- // that toast's card. What matters to a consumer is the handover: the pieces
- // the layout needs must arrive rather than being dropped; the dismiss must
- // stay Astryx's own control so a layout cannot mislabel it or lose it; and
- // a toast that does NOT pass one must be untouched, because that is the
- // library-raised case the app cannot reach.
describe('renderContent', () => {
- const STRIPED: ToastOptions = {
+ const CUSTOM: ToastOptions = {
body: 'Toast A',
renderContent: toast => (
<div data-testid="custom-content">
{toast.body}
{toast.endContent}
- <toast.DismissButton />
+ <Button label="Dismiss custom toast" onClick={toast.dismiss} />
</div>
),
};
- it('keeps slot registration inactive for the default layout', () => {
- let commits = 0;
- render(
- <React.Profiler
- id="default-toast"
- onRender={() => {
- commits += 1;
- }}>
- <Toast
- type="info"
- body="Plain"
- isAutoHide={false}
- autoHideDuration={5000}
- onDismiss={() => {}}
- />
- </React.Profiler>,
- );
- expect(commits).toBe(1);
- });
-
it('replaces the default layout for that toast', () => {
- renderViewport(<ShowToastButton options={STRIPED} triggerLabel="Show" />);
+ renderViewport(<ShowToastButton options={CUSTOM} triggerLabel="Show" />);
act(() => {
fireEvent.click(screen.getByText('Show'));
});
expect(screen.getByTestId('custom-content')).toHaveTextContent('Toast A');
});
- it('leaves a toast that did not ask for one alone', () => {
- // The library-raised case: code that never passes `renderContent` keeps
- // Astryx's own layout, intact and dismissible, rather than inheriting a
- // layout written for someone else's payload.
+ it('keeps the default translated and themeable dismiss Button unchanged', () => {
+ const onHide = vi.fn();
renderViewport(
- <>
- <ShowToastButton options={STRIPED} triggerLabel="Custom" />
- <ShowToastButton options={INFO_B} triggerLabel="Plain" />
- </>,
+ <ShowToastButton
+ options={{body: 'Plain', isAutoHide: false, onHide}}
+ triggerLabel="Show"
+ />,
);
act(() => {
- fireEvent.click(screen.getByText('Custom'));
+ fireEvent.click(screen.getByText('Show'));
});
+ const toast = screen.getByText('Plain').closest('.astryx-toast');
+ expect(toast).not.toBeNull();
+ const dismissButton = within(toast as HTMLElement).getByRole('button', {
+ name: 'Dismiss notification',
+ });
+ expect(dismissButton).toHaveClass('astryx-button');
act(() => {
- fireEvent.click(screen.getByText('Plain'));
+ fireEvent.click(dismissButton);
});
- const plain = screen.getByText('Toast B').closest('.astryx-toast');
- expect(plain).not.toBeNull();
- expect(
- within(plain as HTMLElement).getByRole('button', {
- name: 'Dismiss notification',
- }),
- ).toBeInTheDocument();
- expect(
- within(plain as HTMLElement).queryByTestId('custom-content'),
- ).not.toBeInTheDocument();
+ expect(onHide).toHaveBeenCalledTimes(1);
+ expect(onHide).toHaveBeenCalledWith('manual');
});
- it("hands over Astryx's own dismiss button, correctly named", () => {
- // Why the control is passed rather than left to the layout: it keeps the
- // translated label and the accessible name, so a custom layout cannot
- // ship an unnamed or unlabelled close.
- renderViewport(<ShowToastButton options={STRIPED} triggerLabel="Show" />);
+ it('dismisses exactly once from a composed custom Button and reports manual', () => {
+ const onHide = vi.fn();
+ renderViewport(
+ <ShowToastButton options={{...CUSTOM, onHide}} triggerLabel="Show" />,
+ );
act(() => {
fireEvent.click(screen.getByText('Show'));
});
- expect(
- within(screen.getByTestId('custom-content')).getByRole('button', {
- name: 'Dismiss notification',
- }),
- ).toBeInTheDocument();
+ const dismissButton = within(
+ screen.getByTestId('custom-content'),
+ ).getByRole('button', {name: 'Dismiss custom toast'});
+ expect(dismissButton).toHaveClass('astryx-button');
+ act(() => {
+ fireEvent.click(dismissButton);
+ });
+ expect(onHide).toHaveBeenCalledTimes(1);
+ expect(onHide).toHaveBeenCalledWith('manual');
});
- it('dismisses the toast from the handed-over button', () => {
+ it('lets the dismiss callback travel through nested components', () => {
+ function NestedDismiss({dismiss}: {dismiss: () => void}) {
+ return <Button label="Nested dismiss" onClick={dismiss} />;
+ }
+
const onHide = vi.fn();
renderViewport(
- <ShowToastButton options={{...STRIPED, onHide}} triggerLabel="Show" />,
+ <ShowToastButton
+ options={{
+ body: 'Nested',
+ isAutoHide: false,
+ onHide,
+ renderContent: ({body, dismiss}) => (
+ <div>
+ {body}
+ <NestedDismiss dismiss={dismiss} />
+ </div>
+ ),
+ }}
+ triggerLabel="Show"
+ />,
);
act(() => {
fireEvent.click(screen.getByText('Show'));
});
act(() => {
- fireEvent.click(
- screen.getByRole('button', {name: 'Dismiss notification'}),
- );
+ fireEvent.click(screen.getByRole('button', {name: 'Nested dismiss'}));
});
+ expect(onHide).toHaveBeenCalledTimes(1);
expect(onHide).toHaveBeenCalledWith('manual');
});
- it('renders no dismiss button of its own beside the layout', () => {
- // Astryx must not draw a second close next to the one the layout placed.
- renderViewport(<ShowToastButton options={STRIPED} triggerLabel="Show" />);
+ it('does not inject a dismiss control into custom content', () => {
+ renderViewport(
+ <ShowToastButton
+ options={{
+ body: 'Control-free',
+ type: 'error',
+ renderContent: ({body}) => (
+ <div data-testid="control-free-content">{body}</div>
+ ),
+ }}
+ triggerLabel="Show"
+ />,
+ );
act(() => {
fireEvent.click(screen.getByText('Show'));
});
+ const content = screen.getByTestId('control-free-content');
+ expect(content).toHaveTextContent('Control-free');
+ const toast = content.closest('.astryx-toast');
+ expect(toast).not.toBeNull();
+ expect(within(toast as HTMLElement).queryByRole('button')).toBeNull();
+ });
+
+ it('leaves a toast that did not ask for custom content alone', () => {
+ renderViewport(
+ <>
+ <ShowToastButton options={CUSTOM} triggerLabel="Custom" />
+ <ShowToastButton options={INFO_B} triggerLabel="Plain" />
+ </>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText('Custom'));
+ fireEvent.click(screen.getByText('Plain'));
+ });
+ const plain = screen.getByText('Toast B').closest('.astryx-toast');
+ expect(plain).not.toBeNull();
expect(
- screen.getAllByRole('button', {name: 'Dismiss notification'}),
- ).toHaveLength(1);
+ within(plain as HTMLElement).getByRole('button', {
+ name: 'Dismiss notification',
+ }),
+ ).toBeInTheDocument();
+ expect(
+ within(plain as HTMLElement).queryByTestId('custom-content'),
+ ).not.toBeInTheDocument();
});
it('hands endContent to the layout rather than dropping it', () => {
renderViewport(
<ShowToastButton
options={{
- ...STRIPED,
+ ...CUSTOM,
endContent: <button type="button">Undo</button>,
}}
triggerLabel="Show"
@@ -1189,7 +1175,7 @@ describe('toast timer lifecycle (#3589)', () => {
).toBeInTheDocument();
});
- it('still auto-dismisses, and says so before it happens', () => {
+ it('still auto-dismisses and exposes its resolved timing', () => {
vi.useFakeTimers();
try {
const seen: {isAutoHide: boolean; autoHideDuration: number}[] = [];
@@ -1225,154 +1211,11 @@ describe('toast timer lifecycle (#3589)', () => {
});
it('keeps announcing through the live region', () => {
- // The announcement is the viewport's job, not the layout's — a custom
- // body must not cost a screen-reader user the notification.
- renderViewport(<ShowToastButton options={STRIPED} triggerLabel="Show" />);
+ renderViewport(<ShowToastButton options={CUSTOM} triggerLabel="Show" />);
act(() => {
fireEvent.click(screen.getByText('Show'));
});
expect(announceSpy).toHaveBeenCalledWith('Toast A', 'polite');
});
});
-
- // A layout is free to leave `DismissButton` out — the component renders
- // what it is given. What it must not produce is a toast with no way out, so
- // an unplaced close falls back to the card's own corner.
- describe('a layout that drops the dismiss', () => {
- const NO_CLOSE: ToastOptions = {
- body: 'Stuck',
- type: 'error', // errors do not auto-hide
- renderContent: toast => <div>{toast.body}</div>,
- };
-
- function closeButtons(): HTMLElement[] {
- return screen.queryAllByRole('button', {name: 'Dismiss notification'});
- }
-
- it('still renders a close, and it dismisses the toast', () => {
- const onHide = vi.fn();
- renderViewport(
- <ShowToastButton options={{...NO_CLOSE, onHide}} triggerLabel="Show" />,
- );
- act(() => {
- fireEvent.click(screen.getByText('Show'));
- });
- expect(closeButtons()).toHaveLength(1);
- act(() => {
- fireEvent.click(closeButtons()[0]);
- });
- expect(onHide).toHaveBeenCalledWith('manual');
- });
-
- it('does not add a second one when the layout places it', () => {
- renderViewport(
- <ShowToastButton
- options={{
- ...NO_CLOSE,
- renderContent: toast => (
- <div>
- {toast.body}
- <toast.DismissButton />
- </div>
- ),
- }}
- triggerLabel="Show"
- />,
- );
- act(() => {
- fireEvent.click(screen.getByText('Show'));
- });
- expect(closeButtons()).toHaveLength(1);
- });
-
- it('restores the fallback when a nested layout removes its close', () => {
- function NestedLayout({
- DismissButton,
- }: {
- DismissButton: React.ComponentType;
- }) {
- const [showsClose, setShowsClose] = useState(true);
- return (
- <div>
- <button
- type="button"
- onClick={() => setShowsClose(value => !value)}>
- Toggle nested close
- </button>
- {showsClose && (
- <div data-testid="nested-dismiss">
- <DismissButton />
- </div>
- )}
- </div>
- );
- }
-
- const onHide = vi.fn();
- renderViewport(
- <ShowToastButton
- options={{
- ...NO_CLOSE,
- onHide,
- renderContent: toast => (
- <NestedLayout DismissButton={toast.DismissButton} />
- ),
- }}
- triggerLabel="Show"
- />,
- );
- act(() => {
- fireEvent.click(screen.getByText('Show'));
- });
- expect(
- within(screen.getByTestId('nested-dismiss')).getByRole('button', {
- name: 'Dismiss notification',
- }),
- ).toBeInTheDocument();
- expect(closeButtons()).toHaveLength(1);
-
- // Only NestedLayout rerenders. Toast does not, so this specifically
- // proves registration cleanup — not a parent render recount — restores
- // the safe default.
- act(() => {
- fireEvent.click(screen.getByText('Toggle nested close'));
- });
- expect(screen.queryByTestId('nested-dismiss')).not.toBeInTheDocument();
- expect(closeButtons()).toHaveLength(1);
-
- act(() => {
- fireEvent.click(closeButtons()[0]);
- });
- expect(onHide).toHaveBeenCalledWith('manual');
- });
-
- it('warns when a layout renders the close more than once', () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- renderViewport(
- <ShowToastButton
- options={{
- ...NO_CLOSE,
- renderContent: toast => (
- <div>
- <toast.DismissButton />
- {toast.body}
- <toast.DismissButton />
- </div>
- ),
- }}
- triggerLabel="Show"
- />,
- );
- act(() => {
- fireEvent.click(screen.getByText('Show'));
- });
- expect(warn).toHaveBeenCalledWith(
- expect.stringContaining('Render it once'),
- );
- } finally {
- warn.mockRestore();
- }
- });
- });
});
diff --git a/packages/core/src/Toast/types.ts b/packages/core/src/Toast/types.ts
index 3b77cb9b47..ba12b8d507 100644
--- a/packages/core/src/Toast/types.ts
+++ b/packages/core/src/Toast/types.ts
@@ -1,6 +1,6 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import type {ComponentType, ReactNode} from 'react';
+import type {ReactNode} from 'react';
/** Toast status type. Controls color scheme. */
export type ToastType = 'info' | 'error';
@@ -38,18 +38,16 @@ export interface ToastOptions {
/**
* Replaces the content of this toast's card with your own layout.
*
- * Astryx keeps the card — its surface, its `astryx-toast` theme target, the
- * live-region role and the auto-hide timer — and hands the renderer this
- * toast's message, its `endContent`, and a `DismissButton` component to
- * place. Rendering it puts Astryx's own close at that spot; leaving it out
- * puts the close in the card's default corner, so a custom layout cannot
- * produce a toast with no way out.
+ * Astryx keeps the card, live-region role and auto-hide behavior, then hands
+ * the renderer this toast's content, resolved settings and `dismiss`
+ * callback. The renderer owns every control inside its layout; call
+ * `dismiss` from the control that should close the toast. Astryx does not
+ * inject a fallback control into custom content.
*
* Per-toast rather than app-wide on purpose. An app that wants every one of
* its toasts to share a layout wraps `useToast()` once and passes this on
* every call; a toast raised by library code that knows nothing about that
- * wrapper then renders as an ordinary Astryx toast — intact, dismissible —
- * rather than inheriting a layout written for someone else's payload.
+ * wrapper then renders as an ordinary Astryx toast.
*/
renderContent?: ToastContentRenderFn;
@@ -67,34 +65,12 @@ export interface ToastOptions {
/** Function to programmatically dismiss a toast. */
export type ToastDismissFn = () => void;
-/**
- * What a `renderContent` function receives: one toast's message and trailing
- * slot, plus the dismiss control Astryx has already built for it.
- *
- * `DismissButton` is the point of the whole thing. Astryx builds the close —
- * a ghost icon `Button` carrying the translated `@astryx.toast.dismiss` label
- * — and hands it over as a component the layout places. So it stays a real
- * Astryx `Button`: themeable through `astryx-button` like every other, named
- * in the user's language, impossible to mislabel — and, because an unplaced
- * close falls back to the card's corner, impossible to lose. The layout is
- * the consumer's; the control is not.
- */
+/** Values passed to a custom toast content renderer. */
export interface ToastContentRenderProps {
/** Primary message content, as passed to `showToast`. */
body: ReactNode;
/** Trailing content, as passed to `showToast`. Place it in your layout. */
endContent?: ReactNode;
- /**
- * The toast's close, for your layout to place. Render `<DismissButton />`
- * where you want it: it renders Astryx's own control — the ghost icon
- * `Button` with the translated `@astryx.toast.dismiss` label and the
- * `astryx-button` theme target — so a layout positions the close rather
- * than rebuilding it.
- *
- * Leaving it out is allowed, and safe: the toast then renders its close in
- * the card's default corner. A toast always has a way out.
- */
- DismissButton: ComponentType;
/** Resolved toast type — `'error'` also makes the live region assertive. */
type: ToastType;
/** Whether this toast will dismiss itself. */
@@ -102,9 +78,8 @@ export interface ToastContentRenderProps {
/** Milliseconds until auto-dismiss, when `isAutoHide`. */
autoHideDuration: number;
/**
- * Dismisses this toast, as a manual dismissal — the same thing
- * `DismissButton` does. For a layout whose own control dismisses too, e.g.
- * an Undo that closes the toast after undoing.
+ * Dismisses this toast with reason `'manual'`. Pass it through any nested
+ * components that need to close the toast.
*/
dismiss: ToastDismissFn;
}