Skip to content

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

TypeScript

fix(Toast): improve responsive layout and motion (#5353)

rubyycheungcddf57e5d474
diff --git a/.changeset/toast-responsive-interaction.md b/.changeset/toast-responsive-interaction.md
new file mode 100644
index 0000000000..aa7b9bd2f7
--- /dev/null
+++ b/.changeset/toast-responsive-interaction.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Toast now stays within viewport and safe-area gutters; wraps long messages without clipping; keeps actions and dismissal aligned to the first text line when the message wraps; tightens inter-Toast spacing from 12px to 8px while preserving the viewport-edge gutter; collapses dismissed Toasts smoothly; enters and exits toward its configured top or bottom edge; and exposes the Notifications landmark only while Toasts are present. Placement, visible-stack limits, auto-hide defaults, announcement semantics, dismissal reasons, and browser-chrome behavior remain unchanged.
+
+@rubyycheung
diff --git a/apps/storybook/stories/Toast.stories.tsx b/apps/storybook/stories/Toast.stories.tsx
index ee87f6f57a..cbb464dac6 100644
--- a/apps/storybook/stories/Toast.stories.tsx
+++ b/apps/storybook/stories/Toast.stories.tsx
@@ -1,14 +1,141 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import type {Meta, StoryObj} from '@storybook/react';
-import {useState, useRef} from 'react';
-import {useToast, ToastViewport} from '@astryxdesign/core/Toast';
-import type {ToastType} from '@astryxdesign/core/Toast';
+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 {Button} from '@astryxdesign/core/Button';
import {Link} from '@astryxdesign/core/Link';
import {Card} from '@astryxdesign/core/Card';
import {Stack} from '@astryxdesign/core/Stack';
import {Dialog} from '@astryxdesign/core/Dialog';
+import {Text} from '@astryxdesign/core/Text';
+
+const styles = stylex.create({
+ narrowLayoutReference: {
+ width: 280,
+ maxWidth: '100%',
+ },
+ mobileCanvas: {
+ position: 'relative',
+ boxSizing: 'border-box',
+ inlineSize: 360,
+ maxInlineSize: '100%',
+ minBlockSize: 640,
+ overflow: 'hidden',
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: 'var(--color-border)',
+ borderRadius: 'var(--radius-container)',
+ backgroundColor: 'var(--color-background-body)',
+ boxShadow: 'var(--shadow-low)',
+ transform: 'translateZ(0)',
+ },
+ mobileHeader: {
+ paddingBlock: 'var(--spacing-4)',
+ paddingInline: 'var(--spacing-4)',
+ backgroundColor: 'var(--color-background-surface)',
+ borderBlockEndWidth: 1,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: 'var(--color-border)',
+ },
+ mobileContent: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 'var(--spacing-3)',
+ padding: 'var(--spacing-4)',
+ },
+ mobileCard: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 'var(--spacing-2)',
+ padding: 'var(--spacing-3)',
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: 'var(--color-border)',
+ borderRadius: 'var(--radius-container)',
+ backgroundColor: 'var(--color-background-surface)',
+ },
+ rtlCanvas: {
+ direction: 'rtl',
+ },
+ stackControls: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: 'var(--spacing-2)',
+ },
+});
+
+const mobileStoryParameters = {
+ docs: {
+ story: {inline: false, height: '720px'},
+ },
+};
+
+function MobileCanvas({
+ title,
+ description,
+ isRtl = false,
+ children,
+}: {
+ title: string;
+ description: string;
+ isRtl?: boolean;
+ children: ReactNode;
+}) {
+ return (
+ <div
+ dir={isRtl ? 'rtl' : undefined}
+ {...stylex.props(styles.mobileCanvas, isRtl && styles.rtlCanvas)}>
+ <div {...stylex.props(styles.mobileHeader)}>
+ <Text type="label">{title}</Text>
+ <Text type="supporting" color="secondary">
+ {description}
+ </Text>
+ </div>
+ <div {...stylex.props(styles.mobileContent)}>{children}</div>
+ </div>
+ );
+}
+
+function MockCard({children}: {children: ReactNode}) {
+ return <div {...stylex.props(styles.mobileCard)}>{children}</div>;
+}
+
+interface ReplayToastSpec extends ToastOptions {
+ key: string;
+}
+
+function ToastReplayControls({
+ items,
+ label = 'Show toast',
+}: {
+ items: ReadonlyArray<ReplayToastSpec>;
+ label?: string;
+}) {
+ const toast = useToast();
+ const dismissers = useRef<Array<() => void>>([]);
+ const reset = (): void => {
+ for (const dismiss of dismissers.current) {
+ dismiss();
+ }
+ dismissers.current = [];
+ };
+ const replay = (): void => {
+ reset();
+ for (const item of items) {
+ const {key, ...options} = item;
+ dismissers.current.push(toast({uniqueID: key, ...options}));
+ }
+ };
+ return (
+ <div {...stylex.props(styles.stackControls)}>
+ <Button label={label} onClick={replay} />
+ <Button label="Reset" variant="secondary" onClick={reset} />
+ </div>
+ );
+}
const meta: Meta = {
title: 'Core/Toast',
@@ -17,7 +144,7 @@ const meta: Meta = {
docs: {
description: {
component:
- 'Imperative toast notification system. Use `useToast()` to show transient feedback messages. Works with or without `LayerProvider`.',
+ 'Imperative toast notification system. Use `useToast()` for brief, non-critical feedback. Works with or without `LayerProvider`.',
},
},
},
@@ -39,6 +166,14 @@ export const Default: StoryObj = {
/>
);
},
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Plain info toasts are transient by default. Use them for brief, non-critical feedback that is also reflected elsewhere in the UI.',
+ },
+ },
+ },
};
// =============================================================================
@@ -71,7 +206,7 @@ export const Types: StoryObj = {
docs: {
description: {
story:
- 'Two toast types: info (default) and error. Error toasts persist until dismissed.',
+ 'Two toast types: info (default) and error. Plain info toasts are transient by default; error toasts persist until dismissed.',
},
},
},
@@ -125,7 +260,7 @@ export const WithAction: StoryObj = {
docs: {
description: {
story:
- 'Use `endContent` for trailing actions: buttons, links, or any content.',
+ 'Use `endContent` for short trailing actions. Set `isAutoHide: false` when the action must remain available; timed content still needs to satisfy WCAG 2.2.1.',
},
},
},
@@ -279,9 +414,180 @@ export const Stacking: StoryObj = {
};
// =============================================================================
-// No Provider (fallback)
+// Layout references
// =============================================================================
+export const NarrowLayoutReference: StoryObj = {
+ name: 'Narrow layout reference',
+ render: () => (
+ <div {...stylex.props(styles.narrowLayoutReference)}>
+ <Toast
+ type="info"
+ body="Arbeitsbereichsbenachrichtigungseinstellungen gespeichert"
+ isAutoHide={false}
+ autoHideDuration={5000}
+ endContent={<Button label="Undo" variant="secondary" size="sm" />}
+ onDismiss={() => {}}
+ />
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Static visual reference for narrow viewport/content-fit behavior: realistic translated copy wraps while Undo and dismiss stay aligned with its first line. This example opts out of auto-hide and does not emulate touch, pointer, or hover capabilities.',
+ },
+ },
+ },
+};
+
+// =============================================================================
+// Mobile situations
+// =============================================================================
+
+export const MobileRtlSafeAreaPlacement: StoryObj = {
+ name: 'Mobile situations / RTL logical placement',
+ render: () => (
+ <MobileCanvas
+ title="إعدادات الفريق"
+ description="bottomStart follows the document direction; safe-area insets are device behavior and are not pixel-emulated here."
+ isRtl>
+ <ToastViewport position="bottomStart" isTopLayer={false} maxVisible={2}>
+ <MockCard>
+ <Text type="supporting" color="secondary">
+ The toast uses a logical start placement. On an RTL page, start is
+ the right edge; device safe-area padding is handled by the viewport
+ styles.
+ </Text>
+ <ToastReplayControls
+ label="إظهار التنبيه"
+ items={[
+ {key: 'mobile-rtl-safe-area', body: 'تم حفظ إعدادات الفريق'},
+ ]}
+ />
+ </MockCard>
+ </ToastViewport>
+ </MobileCanvas>
+ ),
+ parameters: {
+ ...mobileStoryParameters,
+ docs: {
+ story: {
+ ...mobileStoryParameters.docs.story,
+ description:
+ 'RTL story for logical start/end placement. Safe-area behavior depends on real device insets; this story does not fake pixel evidence.',
+ },
+ },
+ },
+};
+
+export const MobileMotionEdgeAwareEntrance: StoryObj = {
+ name: 'Mobile situations / Motion edge-aware entrance',
+ render: () => (
+ <MobileCanvas
+ title="Motion replay"
+ description="Replay top and bottom stacks to compare the 8px edge-directed slide, fade, and tighter stack spacing.">
+ <Stack gap={3}>
+ <ToastViewport position="topEnd" isTopLayer={false} maxVisible={3}>
+ <MockCard>
+ <Text type="supporting" color="secondary">
+ Top placement travels 8px down from the top edge; exits return
+ upward. Existing toasts make room through the wrapper grid-row
+ transition.
+ </Text>
+ <ToastReplayControls
+ label="Replay top stack"
+ items={[
+ {key: 'motion-top-1', body: 'Top first', isAutoHide: false},
+ {key: 'motion-top-2', body: 'Top second', isAutoHide: false},
+ {key: 'motion-top-3', body: 'Top third', isAutoHide: false},
+ ]}
+ />
+ </MockCard>
+ </ToastViewport>
+ <ToastViewport position="bottomEnd" isTopLayer={false} maxVisible={3}>
+ <MockCard>
+ <Text type="supporting" color="secondary">
+ Bottom placement travels 8px up from the bottom edge and returns
+ downward on exit, with the same transform/opacity contract and
+ tighter stack spacing.
+ </Text>
+ <ToastReplayControls
+ label="Replay bottom stack"
+ items={[
+ {
+ key: 'motion-bottom-1',
+ body: 'Bottom first',
+ isAutoHide: false,
+ },
+ {
+ key: 'motion-bottom-2',
+ body: 'Bottom second',
+ isAutoHide: false,
+ },
+ {
+ key: 'motion-bottom-3',
+ body: 'Bottom third',
+ isAutoHide: false,
+ },
+ ]}
+ />
+ </MockCard>
+ </ToastViewport>
+ </Stack>
+ </MobileCanvas>
+ ),
+ parameters: {
+ ...mobileStoryParameters,
+ docs: {
+ story: {
+ ...mobileStoryParameters.docs.story,
+ description:
+ 'Replayable visual check for the focused motion change: an 8px top/bottom translate with the existing opacity and timing, plus the wrapper grid-row spacing transition.',
+ },
+ },
+ },
+};
+
+export const NestedViewportLandmark: StoryObj = {
+ name: 'Accessibility / Nested viewport landmark',
+ render: () => (
+ <MobileCanvas
+ title="Nested providers"
+ description="Only the viewport that receives a toast becomes a Notifications landmark.">
+ <ToastViewport isTopLayer={false}>
+ <ToastViewport isTopLayer={false}>
+ <MockCard>
+ <Text type="supporting" color="secondary">
+ Show a toast, then inspect the accessibility tree: the empty outer
+ viewport remains unnamed and only the inner viewport is a region.
+ </Text>
+ <ToastReplayControls
+ items={[
+ {
+ key: 'nested-viewport-landmark',
+ body: 'Notification settings saved',
+ isAutoHide: false,
+ },
+ ]}
+ />
+ </MockCard>
+ </ToastViewport>
+ </ToastViewport>
+ </MobileCanvas>
+ ),
+ parameters: {
+ ...mobileStoryParameters,
+ docs: {
+ story: {
+ ...mobileStoryParameters.docs.story,
+ description:
+ 'Accessibility check for nested ToastViewport composition. With a toast visible, exactly one named Notifications region should appear; with none visible, there should be zero.',
+ },
+ },
+ },
+};
+
export const NoProvider: StoryObj = {
render: function NoProviderStory() {
const toast = useToast();
diff --git a/packages/core/src/Toast/Toast.doc.mjs b/packages/core/src/Toast/Toast.doc.mjs
index 818ba41745..bdd0aa5d60 100644
--- a/packages/core/src/Toast/Toast.doc.mjs
+++ b/packages/core/src/Toast/Toast.doc.mjs
@@ -32,13 +32,13 @@ export const docs = {
{
name: 'autoHideDuration',
type: 'number',
- description: 'Duration in ms before auto-dismiss.',
+ description: 'Duration in ms before auto-dismiss. Timed content must satisfy WCAG 2.2.1.',
default: '5000',
},
{
name: 'endContent',
type: 'ReactNode',
- description: 'Content rendered at the trailing end (e.g. Undo button, link).',
+ description: 'Content rendered at the trailing end (e.g. Undo button, link). Keep action labels short.',
slotElements: [
{__element: 'Icon', props: {icon: 'chevronDown', size: 'sm'}},
{__element: 'Badge', props: {label: '3'}},
@@ -70,14 +70,22 @@ export const docs = {
targets: [
{className: 'astryx-toast', visualProps: ['type']},
],
+ vars: [
+ {
+ name: '--_toast-slide-y',
+ description: 'Private block-axis offset inherited from ToastViewport for entry and exit motion',
+ default: 'var(--spacing-2)',
+ private: true,
+ },
+ ],
},
usage: {
description:
- 'Toast shows a brief, non-blocking notification to confirm an action or present temporary information. Use it for scenarios where the user needs feedback but not a decision, such as saving, deleting, or changing a status.\n\nFor production use, prefer the `useToast()` hook; it handles positioning, stacking, auto-dismiss, and deduplication via `ToastViewport`. The `Toast` component renders the visual toast element inline and is useful for previews, documentation, and static showcases where the viewport lifecycle is not needed.',
+ 'Toast shows a brief, non-blocking notification to confirm an action or present temporary information. Use it for scenarios where the user needs feedback but not a decision, such as saving, deleting, or changing a status.\n\nFor production use, prefer the `useToast()` hook; it handles positioning, stacking, auto-dismiss, and deduplication via `ToastViewport`. Toasts stay within viewport and safe-area gutters, wrap long message content, and enter or exit toward their configured top or bottom edge. Set `isAutoHide: false` explicitly when an action or message must remain available. The `Toast` component renders the visual toast element inline and is useful for previews, documentation, and static showcases where the viewport lifecycle is not needed.',
bestPractices: [
{guidance: true, description: 'Keep messages short: only a few words that tell the user what happened, like "Changes saved" or "Message sent".'},
- {guidance: true, description: 'Add an undo action in the endContent slot for reversible operations like deleting an item, so the user can recover without navigating away.'},
+ {guidance: true, description: 'Add a short undo action in the endContent slot for reversible operations. Set isAutoHide to false when the action must remain available.'},
{guidance: true, description: 'Use uniqueID to deduplicate toasts that fire from repeated actions, like clicking a save button multiple times.'},
{guidance: true, description: 'Use error type for failures that need attention but not immediate action; it persists until dismissed so the user won\'t miss it.'},
{guidance: false, description: 'Don\'t use a toast for critical errors that block the user. Use Banner for persistent, in-context messaging that requires acknowledgment.'},
@@ -104,18 +112,18 @@ export const docsZh = {
body: '主要消息内容。',
type: 'Toast 类型,控制背景颜色。error toast 持续显示直到关闭。',
isAutoHide: '是否自动关闭。info 默认为 true,error 默认为 false。',
- autoHideDuration: '自动关闭前的持续时间(毫秒)。',
- endContent: '尾部渲染的内容(如撤销按钮、链接)。',
+ autoHideDuration: '自动关闭前的持续时间(毫秒)。定时内容必须符合 WCAG 2.2.1。',
+ endContent: '尾部渲染的内容(如撤销按钮、链接)。操作标签应保持简短。',
uniqueID: '用于去重的唯一标识符。',
collisionBehavior: '当已存在相同 uniqueID 的 toast 时的行为。',
onHide: '当 toast 被移除时触发的回调。',
},
usage: {
description:
- 'Toast 显示简短的非阻塞通知,用于确认操作或呈现临时信息。适用于用户需要反馈但不需要做决定的场景,如保存、删除或状态变更。\n\n生产环境中推荐使用 `useToast()` hook,它通过 `ToastViewport` 处理定位、堆叠、自动关闭和去重。`Toast` 组件以内联方式渲染 toast 视觉元素,适用于预览、文档和静态展示。',
+ 'Toast 显示简短的非阻塞通知,用于确认操作或呈现临时信息。适用于用户需要反馈但不需要做决定的场景,如保存、删除或状态变更。\n\n生产环境中推荐使用 `useToast()` hook,它通过 `ToastViewport` 处理定位、堆叠、自动关闭和去重。Toast 会保持在视口和安全区域边距内,较长的消息会换行,并根据配置的顶部或底部边缘进入或退出。当操作或消息必须持续可用时,请显式设置 `isAutoHide: false`。`Toast` 组件以内联方式渲染 toast 视觉元素,适用于不需要视口生命周期的预览、文档和静态展示。',
bestPractices: [
{guidance: true, description: '保持消息简短,只需几个词告诉用户发生了什么,如"更改已保存"或"消息已发送"。'},
- {guidance: true, description: '在 endContent 插槽中添加撤销操作,用于可逆操作如删除项目,让用户无需导航即可恢复。'},
+ {guidance: true, description: '在 endContent 插槽中添加简短的撤销操作,用于可逆操作。当操作必须持续可用时,将 isAutoHide 设置为 false。'},
{guidance: true, description: '使用 uniqueID 去重重复操作触发的 toast,如多次点击保存按钮。'},
{guidance: true, description: '对需要关注但不需要立即操作的错误使用 error 类型,它会持续显示直到关闭。'},
{guidance: false, description: '不要对阻塞用户的严重错误使用 toast,使用 Banner 进行持久的上下文消息传递。'},
@@ -136,10 +144,10 @@ export const docsDense = {
'toast notification w/ auto-dismiss, stacking, dedup, smooth animations; MediaTheme inverted surface',
usage: {
description:
- 'Brief non-blocking notification for action confirmations and temporary info. Use where user needs feedback not decisions: saves, deletes, status changes. useToast() hook for production (positioning, stacking, auto-dismiss, dedup via ToastViewport). Toast renders inline for previews/docs/static showcases.',
+ 'Brief non-blocking notification for action confirmations and temporary info. Use where user needs feedback not decisions: saves, deletes, status changes. useToast() hook for production (safe-area positioning, responsive message wrapping, stacking, auto-dismiss, dedup via ToastViewport). Set isAutoHide false explicitly for must-remain actions/messages. Toast renders inline for previews/docs/static showcases.',
bestPractices: [
{guidance: true, description: 'Short messages, a few words: "Changes saved", "Message sent".'},
- {guidance: true, description: 'Undo action in endContent for reversible ops like deletes.'},
+ {guidance: true, description: 'Short Undo action in endContent for reversible ops; set isAutoHide false when it must remain available.'},
{guidance: true, description: 'uniqueID to dedup repeated action toasts.'},
{guidance: true, description: 'Error type for failures needing attention; persists until dismissed.'},
{guidance: false, description: 'Don\'t use for critical blocking errors. Use Banner for persistent in-context messaging.'},
@@ -151,8 +159,8 @@ export const docsDense = {
body: 'primary message content',
type: 'toast type; controls bg color; error persists until dismissed',
isAutoHide: 'auto-dismiss; true for info, false for error',
- autoHideDuration: 'ms before auto-dismiss',
- endContent: 'trailing end content (undo btn, link)',
+ autoHideDuration: 'ms before auto-dismiss; timed content must satisfy WCAG 2.2.1',
+ endContent: 'trailing end content (undo btn, link); keep action labels short',
uniqueID: 'unique id for dedup',
collisionBehavior: 'behavior when matching uniqueID exists',
onHide: 'callback when toast removed',
diff --git a/packages/core/src/Toast/Toast.tsx b/packages/core/src/Toast/Toast.tsx
index 8afd21c1e1..d8d1267ea3 100644
--- a/packages/core/src/Toast/Toast.tsx
+++ b/packages/core/src/Toast/Toast.tsx
@@ -2,6 +2,21 @@
'use client';
+/**
+ * @file Toast.tsx
+ * @input Uses React timers, Toast options, Button/Icon, MediaTheme, tokens, and
+ * placement-derived motion variables inherited from ToastViewport
+ * @output Exports the rendered Toast surface and its pause/dismiss behavior
+ * @position Core implementation; rendered by ToastViewport and documented by Toast.doc.mjs
+ *
+ * SYNC: When Toast layout, timer pause, media theme, or dismissal behavior changes,
+ * update these files to stay in sync:
+ * - /packages/core/src/Toast/ToastViewport.test.tsx
+ * - /packages/core/src/Toast/Toast.doc.mjs
+ * - /apps/storybook/stories/Toast.stories.tsx
+ * - /packages/cli/assets/templates/blocks/components/Toast/ (showcase blocks)
+ */
+
import {useCallback, useEffect, useRef} from 'react';
import type {ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
@@ -24,13 +39,15 @@ import type {ToastType, ToastDismissReason} from './types';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
+const TOAST_EDGE_DRIFT = spacingVars['--spacing-2'];
const styles = stylex.create({
root: {
paddingBlock: spacingVars['--spacing-4'],
paddingInline: spacingVars['--spacing-4'],
borderRadius: radiusVars['--radius-container'],
+ boxSizing: 'border-box',
width: 400,
- maxWidth: 'min(100%, calc(100vw - 32px))',
+ maxWidth: '100%',
boxShadow: shadowVars['--shadow-med'],
opacity: 1,
fontFamily: typographyVars['--font-family-body'],
@@ -45,15 +62,17 @@ const styles = stylex.create({
transitionTimingFunction: easeVars['--ease-standard'],
'@starting-style': {
opacity: 0,
- transform: 'translateY(8px)',
+ transform: `translateY(var(--_toast-slide-y, ${TOAST_EDGE_DRIFT}))`,
},
},
variantDefault: {
backgroundColor: colorVars['--color-background-inverted'],
},
+
inner: {
display: 'flex',
alignItems: 'flex-start',
+ flexWrap: 'nowrap',
gap: spacingVars['--spacing-3'],
width: '100%',
},
@@ -63,17 +82,22 @@ const styles = stylex.create({
content: {
flex: 1,
minWidth: 0,
+ overflowWrap: 'anywhere',
},
exiting: {
opacity: 0,
- transform: 'translateY(-8px)',
+ transform: `translateY(var(--_toast-slide-y, ${TOAST_EDGE_DRIFT}))`,
},
endContent: {
flexShrink: 0,
display: 'flex',
alignItems: 'center',
gap: spacingVars['--spacing-2'],
- marginBlock: `calc(${spacingVars['--spacing-1']} * -1)`,
+ // Keep every trailing control centered on the first 20px body line, even
+ // when the body wraps or a consumer supplies a control taller than the
+ // built-in 28px dismiss button. The action label should still stay short;
+ // the wrappers above let it break rather than widen the Toast.
+ blockSize: `calc(${typeScaleDefaults['--text-body-size']} * ${typeScaleDefaults['--text-body-leading']})`,
marginInlineEnd: `calc(${spacingVars['--spacing-1']} * -1)`,
},
});
diff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsx
index c9ddbefc01..cb9e4d1bfb 100644
--- a/packages/core/src/Toast/ToastViewport.test.tsx
+++ b/packages/core/src/Toast/ToastViewport.test.tsx
@@ -12,8 +12,17 @@
* announcement flow changes, update these tests
*/
-import {describe, it, expect, vi, beforeAll, afterEach} from 'vitest';
import {
+ describe,
+ it,
+ expect,
+ expectTypeOf,
+ vi,
+ beforeAll,
+ afterEach,
+} from 'vitest';
+import {
+ cleanup,
render,
screen,
fireEvent,
@@ -22,7 +31,10 @@ import {
within,
} from '@testing-library/react';
import React from 'react';
+import {readFileSync} from 'node:fs';
import {type AnnounceFn, __resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import {Button} from '../Button';
+import {Toast, type ToastProps} from './Toast';
import {ToastViewport} from './ToastViewport';
import {useToast} from './useToast';
import type {ToastOptions} from './types';
@@ -66,6 +78,7 @@ beforeAll(() => {
afterEach(() => {
__resetLiveRegionsForTest();
announceSpy.mockClear();
+ vi.unstubAllGlobals();
});
// Module-level constant default props (avoids unstable-default-props lint).
@@ -89,11 +102,33 @@ function ShowToastButton({
const INFO_A: ToastOptions = {body: 'Toast A'};
const INFO_B: ToastOptions = {body: 'Toast B'};
const AUTO_TOAST: ToastOptions = {body: 'Auto toast', autoHideDuration: 3000};
+const LONG_TOAST_BODY =
+ 'Arbeitsbereichsbenachrichtigungseinstellungen gespeichert';
function renderViewport(children: React.ReactNode) {
return render(<ToastViewport isTopLayer={false}>{children}</ToastViewport>);
}
+function getToastWrapperByText(text: string): HTMLElement {
+ const visualToast = screen.getByText(text).closest('[data-type]');
+ if (!(visualToast instanceof HTMLElement)) {
+ throw new Error(`Toast visual for ${text} not found`);
+ }
+ const wrapper = visualToast.closest('[data-toast-id]');
+ if (!(wrapper instanceof HTMLElement)) {
+ throw new Error(`Toast wrapper for ${text} not found`);
+ }
+ return wrapper;
+}
+
+function getVisualToastByText(text: string): HTMLElement {
+ const visualToast = screen.getByText(text).closest('[data-type]');
+ if (!(visualToast instanceof HTMLElement)) {
+ throw new Error(`Toast visual for ${text} not found`);
+ }
+ return visualToast;
+}
+
// Fire the transition-end that ToastViewport listens for to unmount an
// exiting toast (jsdom does not run CSS transitions).
function completeExit(toastId: string) {
@@ -105,6 +140,274 @@ function completeExit(toastId: string) {
}
}
+describe('Toast responsive layout', () => {
+ it('keeps placement on ToastViewport rather than exposing a non-positioning Toast prop', () => {
+ expectTypeOf<ToastProps>().not.toHaveProperty('position');
+ expectTypeOf<React.ComponentProps<typeof ToastViewport>>().toHaveProperty(
+ 'position',
+ );
+ });
+
+ it('keeps real trailing controls on the first line while long body text wraps', () => {
+ renderViewport(
+ <ShowToastButton
+ options={{
+ body: LONG_TOAST_BODY,
+ isAutoHide: false,
+ endContent: (
+ <Button
+ label="Änderungen wiederherstellen"
+ variant="secondary"
+ size="lg"
+ />
+ ),
+ }}
+ />,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger'));
+ });
+
+ const viewport = screen.getByRole('region', {name: 'Notifications'});
+ const body = within(viewport).getByText(LONG_TOAST_BODY);
+ const toast = body.closest('[data-type]') as HTMLElement;
+ const mediaWrapper = toast.firstElementChild as HTMLElement;
+ const layoutRow = mediaWrapper.firstElementChild as HTMLElement;
+ const endArea = body.nextElementSibling as HTMLElement;
+ const actionControl = endArea.firstElementChild as HTMLElement;
+ const dismissControl = within(endArea).getByRole('button', {
+ name: 'Dismiss notification',
+ });
+
+ expect(getComputedStyle(layoutRow).flexWrap).toBe('nowrap');
+ expect(getComputedStyle(layoutRow).alignItems).toBe('flex-start');
+ expect(getComputedStyle(body).minWidth).toBe('0');
+ expect(getComputedStyle(body).overflowWrap).toBe('anywhere');
+ expect(getComputedStyle(endArea).alignItems).toBe('center');
+ expect(getComputedStyle(endArea).height).toBe(
+ 'calc(var(--text-body-size) * var(--text-body-leading))',
+ );
+ expect(getComputedStyle(actionControl).height).toBe(
+ 'var(--size-element-lg)',
+ );
+ expect(getComputedStyle(dismissControl).height).toBe(
+ 'var(--size-element-sm)',
+ );
+ });
+
+ it('uses the viewport as the inline constraint for edge placements', () => {
+ renderViewport(<ShowToastButton options={INFO_A} />);
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger'));
+ });
+
+ const viewport = screen.getByRole('region', {name: 'Notifications'});
+
+ const style = getComputedStyle(viewport);
+ const viewportSource = readFileSync(
+ 'packages/core/src/Toast/ToastViewport.tsx',
+ 'utf8',
+ );
+ expect(viewportSource).not.toContain('100lvh - 100dvh');
+ expect(style.boxSizing).toBe('border-box');
+ expect(style.width).not.toBe('100%');
+ expect(style.paddingInlineEnd).not.toBe('0px');
+ expect(style.insetInlineStart).toBe('0');
+ expect(style.insetInlineEnd).toBe('0');
+ });
+
+ it('preserves custom start and end insets in LTR and RTL without forcing full width', () => {
+ const renderWithDirection = (direction: 'ltr' | 'rtl') =>
+ render(
+ <div dir={direction}>
+ <ToastViewport
+ isTopLayer={false}
+ inset={{bottom: 24, start: 24, end: 40}}>
+ <ShowToastButton options={INFO_A} />
+ </ToastViewport>
+ </div>,
+ );
+
+ renderWithDirection('ltr');
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger'));
+ });
+ let viewport = screen.getByRole('region', {name: 'Notifications'});
+ expect(viewport.style.bottom).toBe('24px');
+ expect(viewport.style.insetInlineStart).toBe('24px');
+ expect(viewport.style.insetInlineEnd).toBe('40px');
+ expect(getComputedStyle(viewport).width).not.toBe('100%');
+
+ cleanup();
+ renderWithDirection('rtl');
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger'));
+ });
+ viewport = screen.getByRole('region', {name: 'Notifications'});
+ expect(viewport.style.bottom).toBe('24px');
+ expect(viewport.style.insetInlineStart).toBe('24px');
+ expect(viewport.style.insetInlineEnd).toBe('40px');
+ expect(getComputedStyle(viewport).width).not.toBe('100%');
+ });
+});
+
+describe('ToastViewport placement', () => {
+ function renderPlacement({
+ position,
+ triggerLabel = 'Trigger',
+ body = 'Placed',
+ }: {
+ position?: React.ComponentProps<typeof ToastViewport>['position'];
+ triggerLabel?: string;
+ body?: string;
+ } = {}) {
+ const result = render(
+ <ToastViewport isTopLayer={false} position={position}>
+ <ShowToastButton
+ options={{body, isAutoHide: false}}
+ triggerLabel={triggerLabel}
+ />
+ </ToastViewport>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText(triggerLabel));
+ });
+ return {
+ ...result,
+ viewport: screen.getByRole('region', {name: 'Notifications'}),
+ };
+ }
+
+ it('defaults to bottomEnd with an end-aligned full-inline viewport', () => {
+ const {viewport} = renderPlacement();
+
+ expect(getComputedStyle(viewport).bottom).toBe('0px');
+ expect(getComputedStyle(viewport).alignItems).toBe('flex-end');
+ expect(getComputedStyle(viewport).width).not.toBe('100%');
+ });
+
+ it('maps explicit top and bottom placements to their configured edge', () => {
+ const top = renderPlacement({position: 'topEnd'});
+ expect(getComputedStyle(top.viewport).top).toBe('0px');
+ expect(getComputedStyle(top.viewport).alignItems).toBe('flex-end');
+ expect(getComputedStyle(top.viewport).flexDirection).toBe('column-reverse');
+ top.unmount();
+
+ const bottom = renderPlacement({
+ position: 'bottomStart',
+ triggerLabel: 'Bottom trigger',
+ body: 'Bottom start',
+ });
+ expect(getComputedStyle(bottom.viewport).bottom).toBe('0px');
+ expect(getComputedStyle(bottom.viewport).alignItems).toBe('flex-start');
+ bottom.unmount();
+ });
+});
+
+it('keeps newest toasts nearest the configured edge in wide stacks', () => {
+ render(
+ <>
+ <ToastViewport isTopLayer={false} position="bottomEnd" maxVisible={3}>
+ <ShowToastButton
+ options={{body: 'Bottom first', isAutoHide: false}}
+ triggerLabel="Bottom first"
+ />
+ <ShowToastButton
+ options={{body: 'Bottom second', isAutoHide: false}}
+ triggerLabel="Bottom second"
+ />
+ <ShowToastButton
+ options={{body: 'Bottom third', isAutoHide: false}}
+ triggerLabel="Bottom third"
+ />
+ </ToastViewport>
+ <ToastViewport isTopLayer={false} position="topEnd" maxVisible={3}>
+ <ShowToastButton
+ options={{body: 'Top first', isAutoHide: false}}
+ triggerLabel="Top first"
+ />
+ <ShowToastButton
+ options={{body: 'Top second', isAutoHide: false}}
+ triggerLabel="Top second"
+ />
+ <ShowToastButton
+ options={{body: 'Top third', isAutoHide: false}}
+ triggerLabel="Top third"
+ />
+ </ToastViewport>
+ </>,
+ );
+ for (const label of [
+ 'Bottom first',
+ 'Bottom second',
+ 'Bottom third',
+ 'Top first',
+ 'Top second',
+ 'Top third',
+ ]) {
+ act(() => {
+ fireEvent.click(screen.getByText(label));
+ });
+ }
+
+ const [bottom, top] = screen.getAllByRole('region', {
+ name: 'Notifications',
+ });
+ expect(getComputedStyle(bottom).flexDirection).toBe('column');
+ expect(
+ within(bottom)
+ .getAllByText(/Bottom/)
+ .map(el => el.textContent),
+ ).toEqual(['Bottom first', 'Bottom second', 'Bottom third']);
+ expect(getComputedStyle(top).flexDirection).toBe('column-reverse');
+ expect(
+ within(top)
+ .getAllByText(/Top/)
+ .map(el => el.textContent),
+ ).toEqual(['Top first', 'Top second', 'Top third']);
+});
+
+describe('ToastViewport visible limit', () => {
+ function renderMany(maxVisible?: number) {
+ render(
+ <ToastViewport isTopLayer={false} maxVisible={maxVisible}>
+ <ShowToastButton
+ options={{body: 'One', isAutoHide: false}}
+ triggerLabel="One"
+ />
+ <ShowToastButton
+ options={{body: 'Two', isAutoHide: false}}
+ triggerLabel="Two"
+ />
+ <ShowToastButton
+ options={{body: 'Three', isAutoHide: false}}
+ triggerLabel="Three"
+ />
+ </ToastViewport>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText('One'));
+ fireEvent.click(screen.getByText('Two'));
+ fireEvent.click(screen.getByText('Three'));
+ });
+ return screen.getByRole('region', {name: 'Notifications'});
+ }
+
+ it('keeps the five-toast default and supports an explicit one-visible cap', () => {
+ let viewport = renderMany();
+ expect(
+ within(viewport).getAllByRole('button', {name: 'Dismiss notification'}),
+ ).toHaveLength(3);
+
+ cleanup();
+ viewport = renderMany(1);
+ expect(
+ within(viewport).getAllByRole('button', {name: 'Dismiss notification'}),
+ ).toHaveLength(1);
+ expect(within(viewport).getByText('Three')).toBeInTheDocument();
+ });
+});
+
describe('ToastViewport keyboard reach + focus', () => {
it('F6 moves focus into the newest toast', () => {
renderViewport(
@@ -252,14 +555,240 @@ describe('Toast blur timer pause', () => {
});
});
+describe('Toast native motion contract', () => {
+ function renderMotionToast(
+ position: React.ComponentProps<typeof ToastViewport>['position'],
+ body = `Motion ${position}`,
+ wrapper: (children: React.ReactNode) => React.ReactElement = children => (
+ <>{children}</>
+ ),
+ ) {
+ const result = render(
+ wrapper(
+ <ToastViewport isTopLayer={false} position={position} maxVisible={3}>
+ <ShowToastButton
+ options={{body, isAutoHide: false}}
+ triggerLabel={`Show ${position}`}
+ />
+ </ToastViewport>,
+ ),
+ );
+ act(() => {
+ fireEvent.click(screen.getByText(`Show ${position}`));
+ });
+ return {
+ ...result,
+ visualToast: getVisualToastByText(body),
+ wrapper: getToastWrapperByText(body),
+ };
+ }
+
+ const normalizeCssList = (value: string): string =>
+ value
+ .split(',')
+ .map(part => part.trim())
+ .join(', ');
+
+ const normalizeCssFunction = (value: string): string =>
+ value.replace(/,\s*/g, ', ');
+
+ it('uses tokenized transform and wrapper timing, with reduced motion kept eventful', () => {
+ const {visualToast, wrapper} = renderMotionToast('bottomEnd');
+ const toastStyle = getComputedStyle(visualToast);
+ const wrapperStyle = getComputedStyle(wrapper);
+
+ expect(normalizeCssFunction(toastStyle.transform)).toBe('translateY(0)');
+ expect(normalizeCssList(toastStyle.transitionProperty)).toBe(
+ 'opacity, transform',
+ );
+ expect(toastStyle.transitionDuration).toBe('var(--duration-fast)');
+ expect(toastStyle.transitionTimingFunction).toBe('var(--ease-standard)');
+ expect(normalizeCssList(wrapperStyle.transitionProperty)).toBe(
+ 'grid-template-rows, padding',
+ );
+ expect(wrapperStyle.transitionDuration).toBe('var(--duration-fast)');
+ expect(wrapperStyle.transitionTimingFunction).toBe('var(--ease-standard)');
+ expect(wrapperStyle.width).toBe('100%');
+ expect(wrapperStyle.maxWidth).toBe('400px');
+ expect(wrapperStyle.minWidth).toBe('0');
+ expect(
+ getComputedStyle(wrapper.firstElementChild as HTMLElement).minHeight,
+ ).toBe('0');
+ expect(
+ getComputedStyle(wrapper.firstElementChild as HTMLElement).overflow,
+ ).toBe('hidden');
+ });
+
+ it('keeps reduced motion transitions eventful for exit cleanup', () => {
+ const toastSource = readFileSync(
+ 'packages/core/src/Toast/Toast.tsx',
+ 'utf8',
+ );
+ const viewportSource = readFileSync(
+ 'packages/core/src/Toast/ToastViewport.tsx',
+ 'utf8',
+ );
+
+ expect(toastSource).toContain(
+ "'@media (prefers-reduced-motion: reduce)': '0.01ms'",
+ );
+ expect(viewportSource).toContain(
+ "'@media (prefers-reduced-motion: reduce)': '0.01ms'",
+ );
+ });
+
+ it('slides from the top or bottom edge without adding corner or scale motion', () => {
+ const bottom = renderMotionToast('bottomEnd');
+ expect(
+ getComputedStyle(bottom.wrapper).getPropertyValue('--_toast-slide-y'),
+ ).toBe('var(--spacing-2)');
+ bottom.unmount();
+
+ const top = renderMotionToast('topStart');
+ expect(
+ getComputedStyle(top.wrapper).getPropertyValue('--_toast-slide-y'),
+ ).toBe('calc(-1 * var(--spacing-2))');
+ top.unmount();
+
+ const toastSource = readFileSync(
+ 'packages/core/src/Toast/Toast.tsx',
+ 'utf8',
+ );
+ expect(toastSource).not.toContain('scale(0.98)');
+ expect(toastSource).not.toContain('transformOrigin');
+ });
+
+ it('uses an 8px inter-Toast gap without adding space at the viewport edge', () => {
+ renderViewport(
+ <>
+ <ShowToastButton options={INFO_A} triggerLabel="Show A" />
+ <ShowToastButton options={INFO_B} triggerLabel="Show B" />
+ </>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText('Show A'));
+ fireEvent.click(screen.getByText('Show B'));
+ });
+ const viewport = screen.getByRole('region', {name: 'Notifications'});
+ const wrappers = viewport.querySelectorAll<HTMLElement>('[data-toast-id]');
+
+ expect(getComputedStyle(wrappers[0]).paddingBottom).toBe(
+ 'var(--spacing-2)',
+ );
+ expect(getComputedStyle(wrappers[1]).paddingBottom).toBe('0px');
+ expect(
+ normalizeCssFunction(getComputedStyle(viewport).paddingInlineEnd),
+ ).toBe('max(var(--spacing-4), env(safe-area-inset-right, 0px))');
+
+ cleanup();
+ render(
+ <ToastViewport isTopLayer={false} position="topEnd">
+ <ShowToastButton options={INFO_A} triggerLabel="Top A" />
+ <ShowToastButton options={INFO_B} triggerLabel="Top B" />
+ </ToastViewport>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText('Top A'));
+ fireEvent.click(screen.getByText('Top B'));
+ });
+ const topWrappers = screen
+ .getByRole('region', {name: 'Notifications'})
+ .querySelectorAll<HTMLElement>('[data-toast-id]');
+ expect(getComputedStyle(topWrappers[0]).paddingBottom).toBe('0px');
+ expect(getComputedStyle(topWrappers[1]).paddingBottom).toBe(
+ 'var(--spacing-2)',
+ );
+ });
+
+ it('collapses a dismissed Toast before unmounting it', () => {
+ const {wrapper} = renderMotionToast('bottomEnd');
+ const id = wrapper.getAttribute('data-toast-id')!;
+ act(() => {
+ fireEvent.click(
+ within(wrapper).getByRole('button', {name: 'Dismiss notification'}),
+ );
+ });
+
+ expect(wrapper).toBeInTheDocument();
+ expect(getComputedStyle(wrapper).gridTemplateRows).toBe('0fr');
+ expect(getComputedStyle(wrapper).paddingBottom).toBe('0px');
+ act(() => {
+ completeExit(id);
+ });
+ expect(document.querySelector(`[data-toast-id="${id}"]`)).toBeNull();
+ });
+});
+
+describe('Toast live-region fallback semantics', () => {
+ it('keeps standalone info Toast content in a polite status region', () => {
+ render(
+ <Toast
+ type="info"
+ body="Saved"
+ isAutoHide={false}
+ autoHideDuration={5000}
+ onDismiss={() => {}}
+ />,
+ );
+
+ const visualToast = screen.getByText('Saved').closest('[data-type]');
+ expect(visualToast).toHaveAttribute('role', 'status');
+ expect(visualToast).toHaveAttribute('aria-live', 'polite');
+ expect(visualToast).toHaveAttribute('aria-atomic', 'true');
+ });
+
+ it('keeps standalone error Toast content in an assertive alert region', () => {
+ render(
+ <Toast
+ type="error"
+ body="Upload failed"
+ isAutoHide={false}
+ autoHideDuration={5000}
+ onDismiss={() => {}}
+ />,
+ );
+
+ const visualToast = screen
+ .getByText('Upload failed')
+ .closest('[data-type]');
+ expect(visualToast).toHaveAttribute('role', 'alert');
+ expect(visualToast).toHaveAttribute('aria-live', 'assertive');
+ expect(visualToast).toHaveAttribute('aria-atomic', 'true');
+ });
+});
+
describe('ToastViewport region ARIA', () => {
- it('exposes the notifications region without a prohibited aria-modal', () => {
+ it('does not expose an empty notifications landmark', () => {
renderViewport(<ShowToastButton />);
+ expect(
+ screen.queryByRole('region', {name: 'Notifications'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('exposes the notifications region without a prohibited aria-modal when a toast is visible', () => {
+ renderViewport(<ShowToastButton />);
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger'));
+ });
const region = screen.getByRole('region', {name: 'Notifications'});
- // aria-modal is only valid on role="dialog"/"alertdialog"; a region must
- // not declare it (axe: aria-allowed-attr).
expect(region).not.toHaveAttribute('aria-modal');
});
+
+ it('does not duplicate the landmark for nested viewports', () => {
+ render(
+ <ToastViewport isTopLayer={false}>
+ <ToastViewport isTopLayer={false}>
+ <ShowToastButton options={INFO_A} />
+ </ToastViewport>
+ </ToastViewport>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger'));
+ });
+ expect(screen.getAllByRole('region', {name: 'Notifications'})).toHaveLength(
+ 1,
+ );
+ });
});
describe('toast announcements via singleton live regions', () => {
@@ -297,7 +826,7 @@ describe('toast announcements via singleton live regions', () => {
act(() => {
fireEvent.click(screen.getByText('Show'));
});
- // Announced synchronously at dispatch, exactly once.
+ // Announced once when the toast is dispatched.
expect(announceSpy).toHaveBeenCalledTimes(1);
expect(announceSpy).toHaveBeenCalledWith(
'Update ready Restart to apply',
@@ -337,9 +866,8 @@ describe('toast announcements via singleton live regions', () => {
act(() => {
fireEvent.click(screen.getByText('Show'));
});
- // The announcement lives in the imperative dispatch path (addToast), not a
- // render effect, so StrictMode's double render and double-invoked state
- // updater cannot announce the same toast twice.
+ // Announcement happens in the event-driven dispatch path, so StrictMode's
+ // double render cannot announce the same toast twice.
expect(announceSpy).toHaveBeenCalledTimes(1);
expect(announceSpy).toHaveBeenCalledWith('Toast A', 'polite');
});
diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsx
index 4789e43cc6..ee934f911f 100644
--- a/packages/core/src/Toast/ToastViewport.tsx
+++ b/packages/core/src/Toast/ToastViewport.tsx
@@ -2,6 +2,18 @@
'use client';
+/**
+ * @file ToastViewport.tsx
+ * @input Uses React state/effects, ToastContext, useAnnounce, viewport tokens,
+ * and placement-derived motion variables
+ * @output Exports the ToastViewport provider, stack, live announcement dispatch,
+ * focus handoff, safe-area-aware edge gutters, and motion context
+ * @position Core provider/imperative viewport for useToast()
+ *
+ * SYNC: When placement, stacking, focus, announcement, or safe-area behavior
+ * changes, update ToastViewport.test.tsx, Toast.doc.mjs, and Toast.stories.tsx.
+ */
+
import {
isValidElement,
useCallback,
@@ -22,13 +34,30 @@ import {ToastContext, type ToastContextValue} from './ToastContext';
import type {ToastEntry, ToastPosition, ToastDismissReason} from './types';
import {useTranslator} from '../i18n';
+const SAFE_AREA_INLINE_START = `max(${spacingVars['--spacing-4']}, env(safe-area-inset-left, 0px))`;
+const SAFE_AREA_INLINE_END = `max(${spacingVars['--spacing-4']}, env(safe-area-inset-right, 0px))`;
+const SAFE_AREA_BLOCK_START = `max(${spacingVars['--spacing-4']}, env(safe-area-inset-top, 0px))`;
+const SAFE_AREA_BLOCK_END = `max(${spacingVars['--spacing-4']}, env(safe-area-inset-bottom, 0px))`;
+const TOAST_EDGE_DRIFT = spacingVars['--spacing-2'];
+const TOAST_EDGE_DRIFT_NEGATIVE = `calc(-1 * ${TOAST_EDGE_DRIFT})`;
+
const styles = stylex.create({
viewport: {
position: 'fixed',
zIndex: 500,
display: 'flex',
+ boxSizing: 'border-box',
flexDirection: 'column',
- padding: spacingVars['--spacing-4'],
+ paddingBlockStart: SAFE_AREA_BLOCK_START,
+ paddingBlockEnd: SAFE_AREA_BLOCK_END,
+ paddingInlineStart: {
+ default: SAFE_AREA_INLINE_START,
+ ':is([dir="rtl"] *)': SAFE_AREA_INLINE_END,
+ },
+ paddingInlineEnd: {
+ default: SAFE_AREA_INLINE_END,
+ ':is([dir="rtl"] *)': SAFE_AREA_INLINE_START,
+ },
pointerEvents: 'none',
// Reset popover styles — the popover attribute puts us in the top
// layer (above dialogs), but we don't want its default styles.
@@ -40,23 +69,28 @@ const styles = stylex.create({
backgroundColor: 'transparent',
overflow: 'visible',
},
- bottomEnd: {bottom: 0, insetInlineEnd: 0, alignItems: 'flex-end'},
- bottomStart: {bottom: 0, insetInlineStart: 0, alignItems: 'flex-start'},
+ viewportInlineSpan: {
+ insetInlineStart: 0,
+ insetInlineEnd: 0,
+ },
+ bottomEnd: {bottom: 0, alignItems: 'flex-end'},
+ bottomStart: {bottom: 0, alignItems: 'flex-start'},
topEnd: {
top: 0,
- insetInlineEnd: 0,
alignItems: 'flex-end',
flexDirection: 'column-reverse',
},
topStart: {
top: 0,
- insetInlineStart: 0,
alignItems: 'flex-start',
flexDirection: 'column-reverse',
},
toastWrapper: {
pointerEvents: 'auto',
display: 'grid',
+ width: '100%',
+ maxWidth: 400,
+ minWidth: 0,
gridTemplateRows: '1fr',
transitionProperty: 'grid-template-rows, padding',
transitionDuration: {
@@ -69,23 +103,33 @@ const styles = stylex.create({
paddingBlockEnd: 0,
},
},
- // The inter-toast gap is padding on each toast rather than `gap` on the
- // viewport so it can animate alongside gridTemplateRows on entry and exit.
- // That makes it the toast's own trailing space, so the toast at the visual
- // bottom of the stack has to give it up — otherwise it stacks on top of the
- // viewport's own padding. Which child that is flips with the flex direction
- // the position sets.
+ toastWrapperFromBottom: {
+ '--_toast-slide-y': TOAST_EDGE_DRIFT,
+ },
+ toastWrapperFromTop: {
+ '--_toast-slide-y': TOAST_EDGE_DRIFT_NEGATIVE,
+ },
+ // The inter-toast gap is padding on each wrapper so it collapses with the
+ // grid track. The wrapper nearest the viewport edge drops that padding; the
+ // child flips because top stacks use column-reverse.
toastWrapperGap: {
- paddingBlockEnd: {default: spacingVars['--spacing-3'], ':last-child': 0},
+ paddingBlockEnd: {default: spacingVars['--spacing-2'], ':last-child': 0},
},
toastWrapperGapReversed: {
- paddingBlockEnd: {default: spacingVars['--spacing-3'], ':first-child': 0},
+ paddingBlockEnd: {default: spacingVars['--spacing-2'], ':first-child': 0},
},
toastWrapperExiting: {
gridTemplateRows: '0fr',
paddingBlockEnd: 0,
},
toastWrapperInner: {
+ width: '100%',
+ maxWidth: '100%',
+ minWidth: 0,
+ minHeight: 0,
+ // Required for the 1fr -> 0fr exit collapse to hide the shrinking Toast.
+ // This preserves main's paint containment; browser-chrome behavior is not
+ // changed or claimed by this responsive-layout fix.
overflow: 'hidden',
},
});
@@ -115,6 +159,7 @@ function getNodeText(node: ReactNode): string {
export interface ToastViewportProps {
position?: ToastPosition;
+ /** Maximum number of visible toasts. @default 5 */
maxVisible?: number;
inset?: {top?: number; bottom?: number; start?: number; end?: number};
/**
@@ -352,6 +397,7 @@ export function ToastViewport({
);
const visibleToasts = toasts.slice(-maxVisible);
+
const insetStyle: React.CSSProperties = {};
if (inset?.top) {
insetStyle.top = inset.top;
@@ -429,6 +475,9 @@ export function ToastViewport({
? styles.bottomStart
: styles.bottomEnd;
const isReversed = position === 'topEnd' || position === 'topStart';
+ const toastWrapperPositionStyle = isReversed
+ ? styles.toastWrapperFromTop
+ : styles.toastWrapperFromBottom;
const gapStyle = isReversed
? styles.toastWrapperGapReversed
: styles.toastWrapperGap;
@@ -438,15 +487,18 @@ export function ToastViewport({
{children}
<div
ref={viewportRef}
- role="region"
- aria-label={t('@astryx.toast.viewport')}
- tabIndex={-1}
+ role={hasToasts ? 'region' : undefined}
+ aria-label={hasToasts ? t('@astryx.toast.viewport') : undefined}
+ tabIndex={hasToasts ? -1 : undefined}
// popover="manual" promotes to the top layer (above dialogs).
// Omitted inside dialogs where the viewport is already in a top layer.
popover={isTopLayer ? 'manual' : undefined}
- {...mergeProps(stylex.props(styles.viewport, posStyle), {
- style: Object.keys(insetStyle).length > 0 ? insetStyle : undefined,
- })}>
+ {...mergeProps(
+ stylex.props(styles.viewport, styles.viewportInlineSpan, posStyle),
+ {
+ style: Object.keys(insetStyle).length > 0 ? insetStyle : undefined,
+ },
+ )}>
{visibleToasts.map(entry => {
const o = entry.options;
const type = o.type ?? 'info';
@@ -459,6 +511,7 @@ export function ToastViewport({
data-toast-id={entry.id}
{...stylex.props(
styles.toastWrapper,
+ toastWrapperPositionStyle,
gapStyle,
isExiting && styles.toastWrapperExiting,
)}
diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.ts
index ea5b0967ff..1bbe9681a2 100644
--- a/packages/core/src/theme/derivedVarRegistry.test.ts
+++ b/packages/core/src/theme/derivedVarRegistry.test.ts
@@ -280,6 +280,9 @@ const VARS_WITHOUT_DERIVED_MAPPING = new Set([
'--_thumbnail-hit-inset',
'--_input-clear-hit-inset',
'--_input-clear-hit-content',
+ // Placement-driven motion is private Toast behavior. A theme author controls
+ // the surface transform as a whole, not this one offset within it.
+ '--_toast-slide-y',
// Indentation and row-spacing metrics: --tree-list-indent is the authorable
// step, --_tree-indent the per-row distance TreeListItem computes from it.
// --tree-list-row-gap is applied as half a padding-block on each row wrapper,