An open source design system that's fully customizable and agent ready
TypeScript
feat(Toast): renderContent — custom toast layout, with a DismissButton that cannot be lost (#5428)
freddymeta9aaa6f40016a
diff --git a/.changeset/toast-render-content.md b/.changeset/toast-render-content.mdnew file mode 100644index 0000000000..f83daba259--- /dev/null+++ b/.changeset/toast-render-content.md@@ -0,0 +1,32 @@+---+'@astryxdesign/core': patch+---++[feat] Toast: `renderContent` on the `showToast` options replaces the content of that toast's card with your own layout.++```tsx+showToast({+ body: 'Your changes have been saved.',+ renderContent: ({body, endContent, DismissButton}) => (+ <MyRow>+ <MyTitle>{body}</MyTitle>+ {endContent}+ <DismissButton />+ </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.++`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.++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.++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.++@freddymetadiff --git a/apps/storybook/stories/Toast.stories.tsx b/apps/storybook/stories/Toast.stories.tsxindex 71383798b8..0a0be09c21 100644--- a/apps/storybook/stories/Toast.stories.tsx+++ b/apps/storybook/stories/Toast.stories.tsx@@ -4,7 +4,11 @@ import type {Meta, StoryObj} from '@storybook/react';import {useState, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {Toast, useToast, ToastViewport} from '@astryxdesign/core/Toast';-import type {ToastOptions, ToastType} from '@astryxdesign/core/Toast';+import type {+ ToastContentRenderProps,+ ToastOptions,+ ToastType,+} from '@astryxdesign/core/Toast';import {Theme, defineTheme, useTheme} from '@astryxdesign/core/theme';import {Button} from '@astryxdesign/core/Button';import {Link} from '@astryxdesign/core/Link';@@ -13,6 +17,11 @@ import {Stack} from '@astryxdesign/core/Stack';import {Heading} from '@astryxdesign/core/Text';import {Dialog} from '@astryxdesign/core/Dialog';import {Text} from '@astryxdesign/core/Text';+import {+ colorVars,+ radiusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';const styles = stylex.create({narrowLayoutReference: {@@ -832,3 +841,140 @@ function ThemedToastTriggers() {}function noop() {}++// =============================================================================+// Custom content (renderContent)+// =============================================================================++const customContentStyles = stylex.create({+ row: {+ display: 'flex',+ alignItems: 'flex-start',+ gap: spacingVars['--spacing-3'],+ width: '100%',+ },+ stripe: {+ alignSelf: 'stretch',+ width: 4,+ borderRadius: radiusVars['--radius-full'],+ flexShrink: 0,+ },+ stripeInfo: {backgroundColor: colorVars['--color-accent']},+ stripeError: {backgroundColor: colorVars['--color-text-red']},+ text: {flex: 1, minWidth: 0},+});++function ProductToastContent({+ type,+ body,+ endContent,+ DismissButton,+}: ToastContentRenderProps) {+ return (+ <div {...stylex.props(customContentStyles.row)}>+ <div+ {...stylex.props(+ customContentStyles.stripe,+ type === 'error'+ ? customContentStyles.stripeError+ : customContentStyles.stripeInfo,+ )}+ />+ <div {...stylex.props(customContentStyles.text)}>{body}</div>+ {endContent}+ <DismissButton />+ </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) {+ return (+ <div {...stylex.props(customContentStyles.row)}>+ <div+ {...stylex.props(+ customContentStyles.stripe,+ type === 'error'+ ? customContentStyles.stripeError+ : customContentStyles.stripeInfo,+ )}+ />+ <div {...stylex.props(customContentStyles.text)}>{body}</div>+ </div>+ );+}++const renderProductContent = (toast: ToastContentRenderProps) => (+ <ProductToastContent {...toast} />+);++export const CustomContent: StoryObj = {+ name: 'Custom content (renderContent)',+ render: function CustomContentStory() {+ const toast = useToast();+ return (+ <Stack direction="horizontal" gap={2} wrap="wrap">+ <Button+ label="Show"+ onClick={() => {+ toast({+ body: 'Your changes have been saved.',+ renderContent: renderProductContent,+ });+ }}+ />+ <Button+ label="With an action"+ variant="secondary"+ onClick={() => {+ toast({+ body: 'Row deleted.',+ endContent: <Button variant="ghost" size="sm" label="Undo" />,+ renderContent: renderProductContent,+ });+ }}+ />+ <Button+ label="Error"+ variant="destructive"+ onClick={() => {+ toast({+ body: 'Could not reach the server.',+ type: 'error',+ renderContent: renderProductContent,+ });+ }}+ />+ <Button+ label="Layout without the close"+ variant="ghost"+ onClick={() => {+ toast({+ body: 'This layout never renders DismissButton.',+ type: 'error',+ renderContent: toastProps => (+ <ForgetfulToastContent {...toastProps} />+ ),+ });+ }}+ />+ <Button+ label="Without renderContent"+ variant="ghost"+ onClick={() => {+ toast({body: 'A toast from code that knows nothing about it.'});+ }}+ />+ </Stack>+ );+ },+ parameters: {+ 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.",+ },+ },+ },+};diff --git a/packages/core/src/Toast/Toast.doc.mjs b/packages/core/src/Toast/Toast.doc.mjsindex bdd0aa5d60..a79c8c4c6a 100644--- a/packages/core/src/Toast/Toast.doc.mjs+++ b/packages/core/src/Toast/Toast.doc.mjs@@ -66,6 +66,12 @@ export const docs = {description: 'Callback fired when the toast is dismissed.',required: true,},+ {+ 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'.",+ },], theming: {targets: [{className: 'astryx-toast', visualProps: ['type']},@@ -117,6 +123,8 @@ export const docsZh = {uniqueID: '用于去重的唯一标识符。',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'。",},usage: {description:diff --git a/packages/core/src/Toast/Toast.tsx b/packages/core/src/Toast/Toast.tsxindex d8d1267ea3..836b112b11 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, useRef} from 'react';+import {useCallback, useEffect, useMemo, useRef, useState} from 'react';import type {ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {Button} from '../Button';@@ -35,13 +35,21 @@ import {import {mergeProps} from '../utils';import {useTheme} from '../theme';import {MediaTheme} from '../theme/MediaTheme';-import type {ToastType, ToastDismissReason} from './types';+import type {+ ToastType,+ ToastDismissReason,+ ToastContentRenderFn,+} 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'],@@ -100,6 +108,14 @@ 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 {@@ -110,6 +126,67 @@ export interface ToastProps {autoHideDuration: number;isExiting?: boolean;onDismiss: (reason: ToastDismissReason) => void;+ /**+ * Replaces the content of this toast's card with your own layout. Direct+ * `Toast` renders use the same contract as `ToastOptions.renderContent`;+ * apps normally set it per toast in the options passed to `useToast()`.+ */+ 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>+ );}/**@@ -140,6 +217,7 @@ export function Toast({autoHideDuration,isExiting = false,onDismiss,+ renderContent,}: ToastProps) {const t = useTranslator();const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -220,6 +298,24 @@ 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@@ -245,21 +341,28 @@ export function Toast({),)}><MediaTheme mode="auto" fallback={fallbackMediaMode}>- <div {...stylex.props(styles.inner)}>- <div {...stylex.props(styles.content)}>{body}</div>+ {renderContent ? (+ <ToastCustomContent dismissButton={dismissButton}>+ {renderContent({+ body,+ endContent,+ DismissButton,+ type,+ isAutoHide,+ autoHideDuration,+ dismiss: handleDismiss,+ })}+ </ToastCustomContent>+ ) : (+ <div {...stylex.props(styles.inner)}>+ <div {...stylex.props(styles.content)}>{body}</div>- <div {...stylex.props(styles.endContent)}>- {endContent}- <Button- variant="ghost"- size="sm"- icon={<Icon icon="close" size="sm" color="inherit" />}- label={t('@astryx.toast.dismiss')}- onClick={handleDismiss}- isIconOnly- />+ <div {...stylex.props(styles.endContent)}>+ {endContent}+ {dismissButton}+ </div></div>- </div>+ )}</MediaTheme></div>);diff --git a/packages/core/src/Toast/ToastDismissSlot.tsx b/packages/core/src/Toast/ToastDismissSlot.tsxnew file mode 100644index 0000000000..0bd80e8cfb--- /dev/null+++ b/packages/core/src/Toast/ToastDismissSlot.tsx@@ -0,0 +1,89 @@+// 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.tsxindex cb9e4d1bfb..b5c48c82d4 100644--- a/packages/core/src/Toast/ToastViewport.test.tsx+++ b/packages/core/src/Toast/ToastViewport.test.tsx@@ -30,7 +30,9 @@ import {waitFor,within,} from '@testing-library/react';-import React from 'react';+import React, {useState} from 'react';+import {hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';import {readFileSync} from 'node:fs';import {type AnnounceFn, __resetLiveRegionsForTest} from '../hooks/useAnnounce';import {Button} from '../Button';@@ -720,6 +722,43 @@ 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@@ -1013,4 +1052,327 @@ describe('toast timer lifecycle (#3589)', () => {vi.useRealTimers();}});++ // `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 = {+ body: 'Toast A',+ renderContent: toast => (+ <div data-testid="custom-content">+ {toast.body}+ {toast.endContent}+ <toast.DismissButton />+ </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" />);+ 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.+ renderViewport(+ <>+ <ShowToastButton options={STRIPED} triggerLabel="Custom" />+ <ShowToastButton options={INFO_B} triggerLabel="Plain" />+ </>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Custom'));+ });+ act(() => {+ fireEvent.click(screen.getByText('Plain'));+ });+ 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();+ });++ 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" />);+ act(() => {+ fireEvent.click(screen.getByText('Show'));+ });+ expect(+ within(screen.getByTestId('custom-content')).getByRole('button', {+ name: 'Dismiss notification',+ }),+ ).toBeInTheDocument();+ });++ it('dismisses the toast from the handed-over button', () => {+ const onHide = vi.fn();+ renderViewport(+ <ShowToastButton options={{...STRIPED, onHide}} triggerLabel="Show" />,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show'));+ });+ act(() => {+ fireEvent.click(+ screen.getByRole('button', {name: 'Dismiss notification'}),+ );+ });+ 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" />);+ act(() => {+ fireEvent.click(screen.getByText('Show'));+ });+ expect(+ screen.getAllByRole('button', {name: 'Dismiss notification'}),+ ).toHaveLength(1);+ });++ it('hands endContent to the layout rather than dropping it', () => {+ renderViewport(+ <ShowToastButton+ options={{+ ...STRIPED,+ endContent: <button type="button">Undo</button>,+ }}+ triggerLabel="Show"+ />,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show'));+ });+ expect(+ within(screen.getByTestId('custom-content')).getByRole('button', {+ name: 'Undo',+ }),+ ).toBeInTheDocument();+ });++ it('still auto-dismisses, and says so before it happens', () => {+ vi.useFakeTimers();+ try {+ const seen: {isAutoHide: boolean; autoHideDuration: number}[] = [];+ const onHide = vi.fn();+ renderViewport(+ <ShowToastButton+ options={{+ body: 'Fleeting',+ autoHideDuration: 3000,+ onHide,+ renderContent: toast => {+ seen.push({+ isAutoHide: toast.isAutoHide,+ autoHideDuration: toast.autoHideDuration,+ });+ return <div>{toast.body}</div>;+ },+ }}+ triggerLabel="Show"+ />,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show'));+ });+ expect(seen[0]).toEqual({isAutoHide: true, autoHideDuration: 3000});+ act(() => {+ vi.advanceTimersByTime(3000);+ });+ expect(onHide).toHaveBeenCalledWith('auto');+ } finally {+ vi.useRealTimers();+ }+ });++ 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" />);+ 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/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsxindex ee934f911f..471513a620 100644--- a/packages/core/src/Toast/ToastViewport.tsx+++ b/packages/core/src/Toast/ToastViewport.tsx@@ -533,6 +533,7 @@ export function ToastViewport({autoHideDuration={dur}isExiting={isExiting}onDismiss={reason => removeToast(entry.id, reason)}+ renderContent={o.renderContent}/></div></div>diff --git a/packages/core/src/Toast/index.ts b/packages/core/src/Toast/index.tsindex 6fb0414eb8..444526c90c 100644--- a/packages/core/src/Toast/index.ts+++ b/packages/core/src/Toast/index.ts@@ -12,6 +12,8 @@ export type {ToastOptions,ToastDismissFn,ShowToastFn,+ ToastContentRenderProps,+ ToastContentRenderFn,} from './types';// Exported for LayerProvider integrationdiff --git a/packages/core/src/Toast/types.ts b/packages/core/src/Toast/types.tsindex 6339b06eab..3b77cb9b47 100644--- a/packages/core/src/Toast/types.ts+++ b/packages/core/src/Toast/types.ts@@ -1,16 +1,12 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import type {ReactNode} from 'react';+import type {ComponentType, ReactNode} from 'react';/** Toast status type. Controls color scheme. */export type ToastType = 'info' | 'error';/** Position for the toast stack relative to the viewport. */-export type ToastPosition =- | 'topEnd'- | 'topStart'- | 'bottomEnd'- | 'bottomStart';+export type ToastPosition = 'topEnd' | 'topStart' | 'bottomEnd' | 'bottomStart';/** Behavior when a toast with the same uniqueID already exists. */export type ToastCollisionBehavior = 'overwrite' | 'ignore';@@ -39,6 +35,23 @@ export interface ToastOptions {autoHideDuration?: number;/** Content rendered at the end of the toast (trailing slot). */endContent?: ReactNode;+ /**+ * 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.+ *+ * 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.+ */+ renderContent?: ToastContentRenderFn;/** Unique identifier for deduplication. */uniqueID?: string;@@ -54,6 +67,56 @@ 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.+ */+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. */+ isAutoHide: boolean;+ /** 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.+ */+ dismiss: ToastDismissFn;+}++/**+ * Renders the content of one toast inside Astryx's card — see+ * `ToastOptions.renderContent`.+ */+export type ToastContentRenderFn = (+ toast: ToastContentRenderProps,+) => ReactNode;+/** Function returned by useToast to show toasts. */export type ShowToastFn = (options: ToastOptions) => ToastDismissFn;diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 224cf8909a..22c2956f62 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -135,6 +135,8 @@ export type {ToastOptions,ToastDismissFn,ShowToastFn,+ ToastContentRenderProps,+ ToastContentRenderFn,} from './Toast';// Popover component and hook