Skip to content

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

TypeScript

feat(Toast): rebase scroll-safe swipe dismissal (#5375)

rubyycheungc6a8b21aeedf
diff --git a/.changeset/toast-swipe-dismissal.md b/.changeset/toast-swipe-dismissal.md
new file mode 100644
index 0000000000..00d00012ec
--- /dev/null
+++ b/.changeset/toast-swipe-dismissal.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Toast now supports touch and pen swipe dismissal toward its configured viewport edge. The vertical axis matches each Toast's top/bottom placement and entrance/exit motion, so the dismissal follows the same spatial model instead of introducing a separate side exit. Native touch scrolling is preserved until movement resolves to the dismiss direction, interactive controls do not start a swipe, and swipe continues to report the existing manual dismissal reason. Pen is included as direct-contact input; mouse drag is excluded because desktop users already have the visible close control and dragging can conflict with text selection.
+
+@rubyycheung
diff --git a/apps/storybook/stories/Toast.stories.tsx b/apps/storybook/stories/Toast.stories.tsx
index 0b0981dfff..89de943e70 100644
--- a/apps/storybook/stories/Toast.stories.tsx
+++ b/apps/storybook/stories/Toast.stories.tsx
@@ -492,6 +492,50 @@ export const MobileRtlSafeAreaPlacement: StoryObj = {
},
};
+export const MobileSwipeToDismiss: StoryObj = {
+ name: 'Mobile situations / Swipe to dismiss',
+ render: () => (
+ <MobileCanvas
+ title="Swipe dismissal"
+ description="Swipe is an enhancement only; the surface fades as it approaches the edge, and the visible close button remains the simple alternative.">
+ <ToastViewport position="topEnd" isTopLayer={false} maxVisible={2}>
+ <MockCard>
+ <Text type="supporting" color="secondary">
+ Use touch or pen input, or browser touch emulation, to swipe the
+ toast toward its configured block edge: up for top placement, down
+ for bottom placement. This matches the direction each Toast enters
+ and exits, keeping one spatial model for the whole interaction. The
+ gesture claims the touch only after dominant travel matches the
+ dismiss edge, so opposite-direction and horizontal page scrolling
+ remain available. Pen is supported as direct-contact input; mouse
+ dragging is ignored to avoid conflicting with desktop text
+ selection, where the close button remains available.
+ </Text>
+ <ToastReplayControls
+ items={[
+ {
+ key: 'mobile-swipe-dismiss',
+ body: 'Swipe or close me',
+ isAutoHide: false,
+ },
+ ]}
+ />
+ </MockCard>
+ </ToastViewport>
+ </MobileCanvas>
+ ),
+ parameters: {
+ ...mobileStoryParameters,
+ docs: {
+ story: {
+ ...mobileStoryParameters.docs.story,
+ description:
+ 'Interactive vertical edge swipe-to-dismiss example using real ToastViewport behavior. The vertical axis intentionally matches the Toast placement and motion model: top Toasts leave upward and bottom Toasts leave downward. A non-passive touchmove handoff claims only dominant travel toward that edge; opposite-direction and horizontal page scrolling remain available. Pen is supported as direct-contact input, while mouse drag is excluded to avoid conflicting with desktop selection; the close button and F6 keyboard access remain available.',
+ },
+ },
+ },
+};
+
export const MobileMotionEdgeAwareEntrance: StoryObj = {
name: 'Mobile situations / Motion edge-aware entrance',
render: () => (
diff --git a/packages/core/src/Toast/Toast.doc.mjs b/packages/core/src/Toast/Toast.doc.mjs
index e59f8652a8..89b87c58e0 100644
--- a/packages/core/src/Toast/Toast.doc.mjs
+++ b/packages/core/src/Toast/Toast.doc.mjs
@@ -8,7 +8,15 @@ export const docs = {
group: 'Toast',
category: 'Overlay',
hiddenComponents: ['ToastViewport'],
- keywords: ["toast","notification","snackbar","alert","message","feedback","status"],
+ keywords: [
+ 'toast',
+ 'notification',
+ 'snackbar',
+ 'alert',
+ 'message',
+ 'feedback',
+ 'status',
+ ],
props: [
{
@@ -16,29 +24,35 @@ export const docs = {
type: 'ReactNode',
description: 'Primary message content.',
required: true,
- slotElements: [{__element: 'Text', props: {type: 'body'}, children: 'Toast message'}],
+ slotElements: [
+ {__element: 'Text', props: {type: 'body'}, children: 'Toast message'},
+ ],
},
{
name: 'type',
type: "'info' | 'error'",
- description: 'Toast type controlling background color. Error toasts persist until dismissed.',
+ description:
+ 'Toast type controlling background color. Error toasts persist until dismissed.',
default: "'info'",
},
{
name: 'isAutoHide',
type: 'boolean',
- description: 'Whether the toast auto-dismisses. Defaults to true for info, false for error.',
+ description:
+ 'Whether the toast auto-dismisses. Defaults to true for info, false for error.',
},
{
name: 'autoHideDuration',
type: 'number',
- description: 'Duration in ms before auto-dismiss. Timed content must satisfy WCAG 2.2.1.',
+ 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). Keep action labels short.',
+ 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'}},
@@ -52,7 +66,8 @@ export const docs = {
{
name: 'collisionBehavior',
type: "'overwrite' | 'ignore'",
- description: 'Behavior when a toast with matching uniqueID already exists.',
+ description:
+ 'Behavior when a toast with matching uniqueID already exists.',
default: "'overwrite'",
},
{
@@ -72,36 +87,103 @@ export const docs = {
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 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: [
- {className: 'astryx-toast', visualProps: ['type']},
- ],
+ ],
+ theming: {
+ targets: [{className: 'astryx-toast', visualProps: ['type']}],
vars: [
{
name: '--_toast-slide-y',
- description: 'Private block-axis offset inherited from ToastViewport for entry and exit motion',
+ description:
+ 'Private block-axis offset inherited from ToastViewport for entry and exit motion',
default: 'var(--spacing-2)',
private: true,
},
+ {
+ name: '--_toast-swipe-y',
+ description: 'Private active swipe offset along the block axis',
+ default: '0px',
+ private: true,
+ },
+ {
+ name: '--_toast-swipe-exit-y',
+ description: 'Private completed-swipe exit offset',
+ default: 'var(--_toast-swipe-y)',
+ private: true,
+ },
+ {
+ name: '--_toast-swipe-opacity',
+ description: 'Private opacity feedback during an accepted swipe',
+ default: '1',
+ private: true,
+ },
+ {
+ name: '--_toast-swipe-scale',
+ description: 'Private scale feedback during an accepted swipe',
+ default: '1',
+ 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`. 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.',
+ '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, exit, or swipe-dismiss toward their configured top or bottom edge. The vertical swipe uses the same spatial model as placement motion: top Toasts leave upward and bottom Toasts leave downward. Swipe waits for dominant edge-directed intent before cancelling native touch movement and reports the existing manual dismissal reason. Pen is supported as direct-contact input; mouse drag is excluded to avoid conflicting with desktop text selection, where the visible close control remains available. 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 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.'},
- {guidance: false, description: 'Don\'t put long or multi-line content in a toast; it disappears after 5 seconds and the user may not finish reading.'},
- {guidance: false, description: 'Don\'t show form validation errors as toasts. Use inline field validation so the user can see exactly which field needs fixing.'},
+ {
+ 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 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.",
+ },
+ {
+ guidance: false,
+ description:
+ "Don't put long or multi-line content in a toast; it disappears after 5 seconds and the user may not finish reading.",
+ },
+ {
+ guidance: false,
+ description:
+ "Don't show form validation errors as toasts. Use inline field validation so the user can see exactly which field needs fixing.",
+ },
],
anatomy: [
- {name: 'Body', required: true, description: 'The primary message text describing what happened or what the user should know.'},
- {name: 'End content', required: false, description: 'A trailing action like an Undo button or a link, placed after the body text.'},
- {name: 'Dismiss button', required: true, description: 'A close button that lets the user manually dismiss the toast before auto-hide.'},
+ {
+ name: 'Body',
+ required: true,
+ description:
+ 'The primary message text describing what happened or what the user should know.',
+ },
+ {
+ name: 'End content',
+ required: false,
+ description:
+ 'A trailing action like an Undo button or a link, placed after the body text.',
+ },
+ {
+ name: 'Dismiss button',
+ required: true,
+ description:
+ 'A close button that lets the user manually dismiss the toast before auto-hide.',
+ },
],
},
};
@@ -118,7 +200,8 @@ export const docsZh = {
body: '主要消息内容。',
type: 'Toast 类型,控制背景颜色。error toast 持续显示直到关闭。',
isAutoHide: '是否自动关闭。info 默认为 true,error 默认为 false。',
- autoHideDuration: '自动关闭前的持续时间(毫秒)。定时内容必须符合 WCAG 2.2.1。',
+ autoHideDuration:
+ '自动关闭前的持续时间(毫秒)。定时内容必须符合 WCAG 2.2.1。',
endContent: '尾部渲染的内容(如撤销按钮、链接)。操作标签应保持简短。',
uniqueID: '用于去重的唯一标识符。',
collisionBehavior: '当已存在相同 uniqueID 的 toast 时的行为。',
@@ -128,20 +211,60 @@ export const docsZh = {
},
usage: {
description:
- 'Toast 显示简短的非阻塞通知,用于确认操作或呈现临时信息。适用于用户需要反馈但不需要做决定的场景,如保存、删除或状态变更。\n\n生产环境中推荐使用 `useToast()` hook,它通过 `ToastViewport` 处理定位、堆叠、自动关闭和去重。Toast 会保持在视口和安全区域边距内,较长的消息会换行,并根据配置的顶部或底部边缘进入或退出。当操作或消息必须持续可用时,请显式设置 `isAutoHide: false`。`Toast` 组件以内联方式渲染 toast 视觉元素,适用于不需要视口生命周期的预览、文档和静态展示。',
+ 'Toast 显示简短的非阻塞通知,用于确认操作或呈现临时信息。适用于用户需要反馈但不需要做决定的场景,如保存、删除或状态变更。\n\n生产环境中推荐使用 `useToast()` hook,它通过 `ToastViewport` 处理定位、堆叠、自动关闭和去重。Toast 会保持在视口和安全区域边距内,较长的消息会换行,并根据配置的顶部或底部边缘进入、退出或滑动关闭。垂直滑动与位置动效使用同一空间模型:顶部 Toast 向上离开,底部 Toast 向下离开。只有在动作明确朝向关闭边缘时才会接管原生触摸移动,滑动关闭继续报告现有的 manual 原因。触控笔属于直接接触输入,因此支持相同手势;鼠标拖动会与桌面文本选择冲突,所以不启用,关闭按钮始终可用。当操作或消息必须持续可用时,请显式设置 `isAutoHide: false`。`Toast` 组件以内联方式渲染 toast 视觉元素,适用于不需要视口生命周期的预览、文档和静态展示。',
bestPractices: [
- {guidance: true, description: '保持消息简短,只需几个词告诉用户发生了什么,如"更改已保存"或"消息已发送"。'},
- {guidance: true, description: '在 endContent 插槽中添加简短的撤销操作,用于可逆操作。当操作必须持续可用时,将 isAutoHide 设置为 false。'},
- {guidance: true, description: '使用 uniqueID 去重重复操作触发的 toast,如多次点击保存按钮。'},
- {guidance: true, description: '对需要关注但不需要立即操作的错误使用 error 类型,它会持续显示直到关闭。'},
- {guidance: false, description: '不要对阻塞用户的严重错误使用 toast,使用 Banner 进行持久的上下文消息传递。'},
- {guidance: false, description: '不要在 toast 中放置长内容或多行内容,它会在5秒后消失,用户可能来不及阅读。'},
- {guidance: false, description: '不要将表单验证错误显示为 toast,使用内联字段验证让用户看到具体哪个字段需要修复。'},
+ {
+ guidance: true,
+ description:
+ '保持消息简短,只需几个词告诉用户发生了什么,如"更改已保存"或"消息已发送"。',
+ },
+ {
+ guidance: true,
+ description:
+ '在 endContent 插槽中添加简短的撤销操作,用于可逆操作。当操作必须持续可用时,将 isAutoHide 设置为 false。',
+ },
+ {
+ guidance: true,
+ description:
+ '使用 uniqueID 去重重复操作触发的 toast,如多次点击保存按钮。',
+ },
+ {
+ guidance: true,
+ description:
+ '对需要关注但不需要立即操作的错误使用 error 类型,它会持续显示直到关闭。',
+ },
+ {
+ guidance: false,
+ description:
+ '不要对阻塞用户的严重错误使用 toast,使用 Banner 进行持久的上下文消息传递。',
+ },
+ {
+ guidance: false,
+ description:
+ '不要在 toast 中放置长内容或多行内容,它会在5秒后消失,用户可能来不及阅读。',
+ },
+ {
+ guidance: false,
+ description:
+ '不要将表单验证错误显示为 toast,使用内联字段验证让用户看到具体哪个字段需要修复。',
+ },
],
anatomy: [
- {name: '正文', required: true, description: '描述发生了什么或用户应该知道什么的主要消息文本。'},
- {name: '尾部内容', required: false, description: '正文后的尾随操作,如撤销按钮或链接。'},
- {name: '关闭按钮', required: true, description: '让用户在自动隐藏前手动关闭 toast 的关闭按钮。'},
+ {
+ name: '正文',
+ required: true,
+ description: '描述发生了什么或用户应该知道什么的主要消息文本。',
+ },
+ {
+ name: '尾部内容',
+ required: false,
+ description: '正文后的尾随操作,如撤销按钮或链接。',
+ },
+ {
+ name: '关闭按钮',
+ required: true,
+ description: '让用户在自动隐藏前手动关闭 toast 的关闭按钮。',
+ },
],
},
};
@@ -152,23 +275,52 @@ 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 (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.',
+ '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). Enters, exits, or swipe-dismisses toward configured edge; touch is claimed only after dominant edge-directed intent; swipe reports manual. Pen uses the direct-contact gesture; mouse drag stays off to preserve text selection and the close control remains available. 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: '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.'},
- {guidance: false, description: 'Don\'t put long/multi-line content; disappears in 5s, user may not finish reading.'},
- {guidance: false, description: 'Don\'t show form validation errors. Use inline field validation instead.'},
+ {
+ guidance: true,
+ description:
+ 'Short messages, a few words: "Changes saved", "Message sent".',
+ },
+ {
+ 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.",
+ },
+ {
+ guidance: false,
+ description:
+ "Don't put long/multi-line content; disappears in 5s, user may not finish reading.",
+ },
+ {
+ guidance: false,
+ description:
+ "Don't show form validation errors. Use inline field validation instead.",
+ },
],
},
propDescriptions: {
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; timed content must satisfy WCAG 2.2.1',
- endContent: 'trailing end content (undo btn, link); keep action labels short',
+ 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 901fcbb680..6a6774df10 100644
--- a/packages/core/src/Toast/Toast.tsx
+++ b/packages/core/src/Toast/Toast.tsx
@@ -4,9 +4,9 @@
/**
* @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
+ * @input Uses React timers, touch/pen gesture events, Toast options, Button/Icon,
+ * MediaTheme, tokens, and placement motion inherited from ToastViewport
+ * @output Exports the rendered Toast surface and its pause/swipe/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,
@@ -33,6 +33,7 @@ import {
typeScaleDefaults,
} from '../theme/tokens.stylex';
import {mergeProps} from '../utils';
+import {INTERACTIVE_SELECTORS} from '../hooks/useClickableContainer';
import {useTheme} from '../theme';
import {MediaTheme} from '../theme/MediaTheme';
import type {
@@ -42,6 +43,26 @@ import type {
} from './types';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
+import {useToastGesture, type ToastGestureDirection} from './useToastGesture';
+
+const SWIPE_INTERACTIVE_TARGET_SELECTOR = `${INTERACTIVE_SELECTORS},[tabindex],[contenteditable]:not([contenteditable="false"])`;
+
+function isInteractiveTarget(
+ target: EventTarget | null,
+ root: HTMLElement,
+): boolean {
+ if (!(target instanceof Element)) {
+ return false;
+ }
+ let current: Element | null = target;
+ while (current != null && current !== root && current !== document.body) {
+ if (current.matches(SWIPE_INTERACTIVE_TARGET_SELECTOR)) {
+ return true;
+ }
+ current = current.parentElement;
+ }
+ return false;
+}
const TOAST_EDGE_DRIFT = spacingVars['--spacing-2'];
const styles = stylex.create({
@@ -53,11 +74,12 @@ const styles = stylex.create({
width: 400,
maxWidth: '100%',
boxShadow: shadowVars['--shadow-med'],
- opacity: 1,
+ opacity: 'var(--_toast-swipe-opacity, 1)',
fontFamily: typographyVars['--font-family-body'],
fontSize: typeScaleDefaults['--text-body-size'],
lineHeight: typeScaleDefaults['--text-body-leading'],
- transform: 'translateY(0)',
+ transform:
+ 'translateY(var(--_toast-swipe-y, 0px)) scale(var(--_toast-swipe-scale, 1))',
transitionProperty: 'opacity, transform',
transitionDuration: {
default: durationVars['--duration-fast'],
@@ -90,7 +112,7 @@ const styles = stylex.create({
},
exiting: {
opacity: 0,
- transform: `translateY(var(--_toast-slide-y, ${TOAST_EDGE_DRIFT}))`,
+ transform: `translateY(var(--_toast-swipe-exit-y, var(--_toast-swipe-y, var(--_toast-slide-y, ${TOAST_EDGE_DRIFT})))) scale(var(--_toast-swipe-scale, 1))`,
},
endContent: {
flexShrink: 0,
@@ -122,6 +144,10 @@ export interface ToastProps {
renderContent?: ToastContentRenderFn;
}
+interface ToastSurfaceProps extends ToastProps {
+ gestureDirection: ToastGestureDirection;
+}
+
/**
* Individual toast notification.
*
@@ -142,7 +168,11 @@ export interface ToastProps {
* />
* ```
*/
-export function Toast({
+export function Toast(props: ToastProps) {
+ return <ToastSurface {...props} gestureDirection={1} />;
+}
+
+export function ToastSurface({
type,
body,
endContent,
@@ -151,7 +181,8 @@ export function Toast({
isExiting = false,
onDismiss,
renderContent,
-}: ToastProps) {
+ gestureDirection,
+}: ToastSurfaceProps) {
const t = useTranslator();
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const isPausedRef = useRef(false);
@@ -227,6 +258,21 @@ export function Toast({
};
}, [isAutoHide, pauseTimer, resumeTimer]);
+ const isTimerPaused = useCallback(() => isPausedRef.current, []);
+ const dismissFromGesture = useCallback(() => {
+ onDismissRef.current('manual');
+ }, []);
+ const {rootRef, bindings: gestureBindings} = useToastGesture({
+ direction: gestureDirection,
+ enabled: !isExiting,
+ canPauseTimer: isAutoHide,
+ isTimerPaused,
+ pauseTimer,
+ resumeTimer,
+ dismiss: dismissFromGesture,
+ shouldIgnoreTarget: isInteractiveTarget,
+ });
+
const handleDismiss = useCallback(() => {
onDismiss('manual');
}, [onDismiss]);
@@ -240,6 +286,7 @@ export function Toast({
return (
<div
+ ref={rootRef}
role={isError ? 'alert' : 'status'}
aria-live={isError ? 'assertive' : 'polite'}
aria-atomic="true"
@@ -247,6 +294,7 @@ export function Toast({
onMouseLeave={resumeTimer}
onFocusCapture={pauseTimer}
onBlurCapture={resumeTimer}
+ {...gestureBindings}
{...mergeProps(
themeProps('toast', {type}),
stylex.props(
@@ -288,3 +336,4 @@ export function Toast({
}
Toast.displayName = 'Toast';
+ToastSurface.displayName = 'ToastSurface';
diff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsx
index 8640dca16a..5a1df6ed6f 100644
--- a/packages/core/src/Toast/ToastViewport.test.tsx
+++ b/packages/core/src/Toast/ToastViewport.test.tsx
@@ -71,6 +71,10 @@ beforeAll(() => {
HTMLElement.prototype.showPopover = vi.fn();
HTMLElement.prototype.hidePopover = vi.fn();
}
+ if (typeof HTMLElement.prototype.setPointerCapture === 'undefined') {
+ HTMLElement.prototype.setPointerCapture = vi.fn();
+ HTMLElement.prototype.releasePointerCapture = vi.fn();
+ }
});
// Toast text is mirrored into the singleton live regions, which outlive each
@@ -102,6 +106,7 @@ 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 SWIPE_TOAST: ToastOptions = {body: 'Swipe toast', isAutoHide: false};
const LONG_TOAST_BODY =
'Arbeitsbereichsbenachrichtigungseinstellungen gespeichert';
@@ -597,7 +602,9 @@ describe('Toast native motion contract', () => {
const toastStyle = getComputedStyle(visualToast);
const wrapperStyle = getComputedStyle(wrapper);
- expect(normalizeCssFunction(toastStyle.transform)).toBe('translateY(0)');
+ expect(normalizeCssFunction(toastStyle.transform)).toBe(
+ 'translateY(var(--_toast-swipe-y, 0px)) scale(var(--_toast-swipe-scale, 1))',
+ );
expect(normalizeCssList(toastStyle.transitionProperty)).toBe(
'opacity, transform',
);
@@ -719,6 +726,692 @@ describe('Toast native motion contract', () => {
});
});
+describe('Toast swipe dismissal', () => {
+ function renderSwipeToast(
+ options: ToastOptions = SWIPE_TOAST,
+ position: React.ComponentProps<
+ typeof ToastViewport
+ >['position'] = 'bottomEnd',
+ bodyText = 'Swipe toast',
+ surfaceHeight = 80,
+ ) {
+ const onHide = vi.fn();
+ const result = render(
+ <ToastViewport isTopLayer={false} position={position}>
+ <ShowToastButton options={{...options, onHide}} />
+ </ToastViewport>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger'));
+ });
+ const visualToast = screen
+ .getByText(bodyText)
+ .closest('[data-type]') as HTMLElement;
+ vi.spyOn(visualToast, 'getBoundingClientRect').mockReturnValue({
+ x: 0,
+ y: 0,
+ width: 400,
+ height: surfaceHeight,
+ top: 0,
+ right: 400,
+ bottom: surfaceHeight,
+ left: 0,
+ toJSON: () => ({}),
+ });
+ return {...result, visualToast, onHide};
+ }
+
+ it('dismisses on a pen swipe toward the configured block edge past the threshold', () => {
+ const {visualToast, onHide} = renderSwipeToast();
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 60,
+ });
+ fireEvent.pointerUp(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 60,
+ });
+ });
+
+ expect(visualToast.setPointerCapture).toHaveBeenCalledWith(7);
+ expect(visualToast.releasePointerCapture).toHaveBeenCalledWith(7);
+ expect(onHide).toHaveBeenCalledWith('manual');
+ expect(onHide).toHaveBeenCalledTimes(1);
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-exit-y')).toBe(
+ '120%',
+ );
+ expect(getComputedStyle(visualToast).transform).not.toContain('translateX');
+ });
+
+ it('dismisses a fast flick below the distance threshold', () => {
+ const now = vi
+ .spyOn(Date, 'now')
+ .mockReturnValueOnce(1_000)
+ .mockReturnValueOnce(1_020);
+ try {
+ const {visualToast, onHide} = renderSwipeToast(
+ SWIPE_TOAST,
+ 'bottomEnd',
+ 'Swipe toast',
+ 400,
+ );
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 8,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 8,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 60,
+ });
+ fireEvent.pointerUp(visualToast, {
+ pointerId: 8,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 60,
+ });
+ });
+
+ expect(onHide).toHaveBeenCalledWith('manual');
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-exit-y')).toBe(
+ '120%',
+ );
+ } finally {
+ now.mockRestore();
+ }
+ });
+
+ it('snaps back without dismissing after a short drag', () => {
+ const {visualToast, onHide} = renderSwipeToast();
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 24,
+ });
+ fireEvent.pointerUp(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 24,
+ });
+ });
+
+ expect(onHide).not.toHaveBeenCalled();
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-y')).toBe('');
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-opacity')).toBe(
+ '',
+ );
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-scale')).toBe('');
+ });
+
+ it('fades and subtly scales only after accepted vertical edge swipe intent', () => {
+ const {visualToast} = renderSwipeToast();
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: -40,
+ });
+ });
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-y')).toBe('');
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-opacity')).toBe(
+ '',
+ );
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-scale')).toBe('');
+ act(() => {
+ fireEvent.pointerCancel(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: -40,
+ });
+ });
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 8,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 8,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 40,
+ });
+ });
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-y')).toBe('40px');
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-opacity')).toBe(
+ '0.800',
+ );
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-scale')).toBe(
+ '0.990',
+ );
+ });
+
+ it('does not fade for horizontal intent and resets swipe vars on pointercancel', () => {
+ const {visualToast, onHide} = renderSwipeToast();
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 80,
+ clientY: 20,
+ });
+ });
+ expect(onHide).not.toHaveBeenCalled();
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-opacity')).toBe(
+ '',
+ );
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-scale')).toBe('');
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 8,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 8,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 40,
+ });
+ });
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-opacity')).toBe(
+ '0.800',
+ );
+ act(() => {
+ fireEvent.pointerCancel(visualToast, {
+ pointerId: 8,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 40,
+ });
+ });
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-y')).toBe('');
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-opacity')).toBe(
+ '',
+ );
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-scale')).toBe('');
+ });
+
+ it('hands the opposite vertical direction back without moving the toast', () => {
+ const {visualToast, onHide} = renderSwipeToast(SWIPE_TOAST, 'bottomEnd');
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 100,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 40,
+ });
+ fireEvent.pointerUp(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 40,
+ });
+ });
+
+ expect(onHide).not.toHaveBeenCalled();
+ });
+
+ it('keeps bottom placement dismissing downward under RTL', () => {
+ const onHide = vi.fn();
+ render(
+ <div dir="rtl">
+ <ToastViewport isTopLayer={false} position="bottomStart">
+ <ShowToastButton options={{...SWIPE_TOAST, onHide}} />
+ </ToastViewport>
+ </div>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger'));
+ });
+ const visualToast = screen
+ .getByText('Swipe toast')
+ .closest('[data-type]') as HTMLElement;
+ vi.spyOn(visualToast, 'getBoundingClientRect').mockReturnValue({
+ x: 0,
+ y: 0,
+ width: 400,
+ height: 80,
+ top: 0,
+ right: 400,
+ bottom: 80,
+ left: 0,
+ toJSON: () => ({}),
+ });
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 60,
+ });
+ fireEvent.pointerUp(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 60,
+ });
+ });
+
+ expect(onHide).toHaveBeenCalledWith('manual');
+ });
+
+ it('keeps top placement dismissing upward under RTL', () => {
+ const onHide = vi.fn();
+ render(
+ <div dir="rtl">
+ <ToastViewport isTopLayer={false} position="topEnd">
+ <ShowToastButton options={{...SWIPE_TOAST, onHide}} />
+ </ToastViewport>
+ </div>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger'));
+ });
+ const visualToast = getVisualToastByText('Swipe toast');
+ vi.spyOn(visualToast, 'getBoundingClientRect').mockReturnValue({
+ x: 0,
+ y: 0,
+ width: 400,
+ height: 80,
+ top: 0,
+ right: 400,
+ bottom: 80,
+ left: 0,
+ toJSON: () => ({}),
+ });
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 100,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 40,
+ });
+ fireEvent.pointerUp(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 40,
+ });
+ });
+
+ expect(onHide).toHaveBeenCalledWith('manual');
+ });
+
+ it('sets swipe exit to a vertical throw with no horizontal drift', () => {
+ const {visualToast, onHide} = renderSwipeToast(
+ SWIPE_TOAST,
+ 'topEnd',
+ 'Swipe toast',
+ );
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 100,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 40,
+ });
+ fireEvent.pointerUp(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 40,
+ });
+ });
+
+ expect(onHide).toHaveBeenCalledWith('manual');
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-opacity')).toBe(
+ '0.700',
+ );
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-scale')).toBe(
+ '0.985',
+ );
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-exit-y')).toBe(
+ 'calc(-1 * 120%)',
+ );
+ expect(getComputedStyle(visualToast).transform).not.toContain('translateX');
+ });
+
+ it('allows native page scrolling until touch intent matches the dismiss edge', () => {
+ const {visualToast, onHide} = renderSwipeToast(
+ SWIPE_TOAST,
+ 'topEnd',
+ 'Swipe toast',
+ );
+ const touchEvent = (
+ type: 'touchstart' | 'touchmove' | 'touchend',
+ clientY: number,
+ ) => {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const touch = {identifier: 31, clientX: 10, clientY};
+ Object.defineProperty(event, 'touches', {
+ value: type === 'touchend' ? [] : [touch],
+ });
+ Object.defineProperty(event, 'changedTouches', {value: [touch]});
+ visualToast.dispatchEvent(event);
+ return event;
+ };
+
+ act(() => {
+ touchEvent('touchstart', 100);
+ });
+ let move: Event;
+ act(() => {
+ move = touchEvent('touchmove', 140);
+ });
+ expect(move!.defaultPrevented).toBe(false);
+ expect(onHide).not.toHaveBeenCalled();
+
+ act(() => {
+ touchEvent('touchstart', 100);
+ });
+ Object.defineProperty(
+ (move = new Event('touchmove', {bubbles: true, cancelable: true})),
+ 'changedTouches',
+ {value: [{identifier: 31, clientX: 80, clientY: 104}]},
+ );
+ act(() => {
+ visualToast.dispatchEvent(move);
+ });
+ expect(move.defaultPrevented).toBe(false);
+
+ act(() => {
+ touchEvent('touchstart', 100);
+ });
+ act(() => {
+ move = touchEvent('touchmove', 40);
+ });
+ expect(move!.defaultPrevented).toBe(true);
+ act(() => {
+ touchEvent('touchend', 40);
+ });
+ expect(onHide).toHaveBeenCalledWith('manual');
+ });
+
+ it('resets an accepted touch gesture on native touchcancel', () => {
+ const {visualToast, onHide} = renderSwipeToast();
+ const touch = (type: 'touchstart' | 'touchmove', clientY: number) => {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const point = {identifier: 44, clientX: 10, clientY};
+ Object.defineProperty(event, 'touches', {value: [point]});
+ Object.defineProperty(event, 'changedTouches', {value: [point]});
+ visualToast.dispatchEvent(event);
+ return event;
+ };
+
+ act(() => {
+ touch('touchstart', 0);
+ });
+ let move: Event;
+ act(() => {
+ move = touch('touchmove', 40);
+ });
+ expect(move!.defaultPrevented).toBe(true);
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-y')).toBe('40px');
+
+ act(() => {
+ visualToast.dispatchEvent(
+ new Event('touchcancel', {bubbles: true, cancelable: true}),
+ );
+ });
+
+ expect(onHide).not.toHaveBeenCalled();
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-y')).toBe('');
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-opacity')).toBe(
+ '',
+ );
+ });
+
+ it('removes native touch listeners when a Toast unmounts', () => {
+ const {visualToast, unmount} = renderSwipeToast();
+ const removeListener = vi.spyOn(visualToast, 'removeEventListener');
+
+ unmount();
+
+ for (const type of ['touchstart', 'touchmove', 'touchend', 'touchcancel']) {
+ expect(removeListener).toHaveBeenCalledWith(type, expect.any(Function));
+ }
+ });
+
+ it('resets safely on pointercancel and resumes the auto-hide timer', () => {
+ vi.useFakeTimers();
+ try {
+ const {visualToast, onHide} = renderSwipeToast({
+ body: 'Swipe toast',
+ autoHideDuration: 3000,
+ });
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 40,
+ });
+ vi.advanceTimersByTime(10_000);
+ });
+ expect(onHide).not.toHaveBeenCalled();
+
+ act(() => {
+ fireEvent.pointerCancel(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 40,
+ });
+ vi.advanceTimersByTime(3_000);
+ });
+
+ expect(onHide).toHaveBeenCalledWith('auto');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps horizontal pan intent and mouse drag from dismissing', () => {
+ const {visualToast, onHide} = renderSwipeToast();
+
+ act(() => {
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 80,
+ clientY: 20,
+ });
+ fireEvent.pointerUp(visualToast, {
+ pointerId: 7,
+ pointerType: 'pen',
+ clientX: 220,
+ clientY: 80,
+ });
+ fireEvent.pointerDown(visualToast, {
+ pointerId: 8,
+ pointerType: 'mouse',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(visualToast, {
+ pointerId: 8,
+ pointerType: 'mouse',
+ clientX: 220,
+ clientY: 0,
+ });
+ fireEvent.pointerUp(visualToast, {
+ pointerId: 8,
+ pointerType: 'mouse',
+ clientX: 220,
+ clientY: 0,
+ });
+ });
+
+ expect(onHide).not.toHaveBeenCalled();
+ });
+
+ it('does not start a swipe from interactive descendants', () => {
+ const onAction = vi.fn();
+ const {visualToast, onHide} = renderSwipeToast({
+ ...SWIPE_TOAST,
+ endContent: (
+ <>
+ <Button label="Undo" size="sm" onClick={onAction} />
+ <span role="switch" tabIndex={-1}>
+ Mode
+ </span>
+ </>
+ ),
+ });
+
+ const targets = [
+ screen.getByRole('button', {name: 'Undo'}),
+ screen.getByRole('switch', {name: 'Mode'}),
+ ];
+ targets.forEach((target, index) => {
+ const pointerId = 20 + index;
+ act(() => {
+ fireEvent.pointerDown(target, {
+ pointerId,
+ pointerType: 'pen',
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ });
+ fireEvent.pointerMove(target, {
+ pointerId,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 80,
+ });
+ fireEvent.pointerUp(target, {
+ pointerId,
+ pointerType: 'pen',
+ clientX: 0,
+ clientY: 80,
+ });
+ });
+ });
+
+ expect(onHide).not.toHaveBeenCalled();
+ expect(visualToast.style.getPropertyValue('--_toast-swipe-y')).toBe('');
+ act(() => {
+ fireEvent.click(targets[0]);
+ });
+ expect(onAction).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the visible dismiss button as a non-gesture alternative', () => {
+ const {onHide} = renderSwipeToast();
+
+ act(() => {
+ fireEvent.click(
+ screen.getByRole('button', {name: 'Dismiss notification'}),
+ );
+ });
+
+ expect(onHide).toHaveBeenCalledWith('manual');
+ });
+});
+
describe('Toast live-region fallback semantics', () => {
it('keeps standalone info Toast content in a polite status region', () => {
render(
diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsx
index 471513a620..8281d206cc 100644
--- a/packages/core/src/Toast/ToastViewport.tsx
+++ b/packages/core/src/Toast/ToastViewport.tsx
@@ -29,7 +29,7 @@ import {spacingVars, durationVars, easeVars} from '../theme/tokens.stylex';
import {mergeProps} from '../utils';
import {INTERACTIVE_SELECTORS} from '../hooks/useClickableContainer';
import {useAnnounce} from '../hooks/useAnnounce';
-import {Toast} from './Toast';
+import {ToastSurface} from './Toast';
import {ToastContext, type ToastContextValue} from './ToastContext';
import type {ToastEntry, ToastPosition, ToastDismissReason} from './types';
import {useTranslator} from '../i18n';
@@ -525,13 +525,14 @@ export function ToastViewport({
: undefined
}>
<div {...stylex.props(styles.toastWrapperInner)}>
- <Toast
+ <ToastSurface
type={type}
body={o.body}
endContent={o.endContent}
isAutoHide={isAutoHide}
autoHideDuration={dur}
isExiting={isExiting}
+ gestureDirection={isReversed ? -1 : 1}
onDismiss={reason => removeToast(entry.id, reason)}
renderContent={o.renderContent}
/>
diff --git a/packages/core/src/Toast/useToastGesture.ts b/packages/core/src/Toast/useToastGesture.ts
new file mode 100644
index 0000000000..1eb2c1f919
--- /dev/null
+++ b/packages/core/src/Toast/useToastGesture.ts
@@ -0,0 +1,361 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useToastGesture.ts
+ * @input Uses a resolved Toast edge direction, timer pause/resume hooks,
+ * dismissal callback, enabled state, and interactive-descendant policy
+ * @output Returns the Toast card root ref and touch/pen gesture bindings
+ * @position Internal Toast gesture unit; attached to the Toast card root
+ */
+
+import {useCallback, useEffect, useRef} from 'react';
+import type {PointerEvent as ReactPointerEvent, RefObject} from 'react';
+
+const DRAG_PROMOTION_SLOP = 8;
+const SWIPE_DISMISS_RATIO = 0.4;
+const FLICK_MIN_DISTANCE = 48;
+const FLICK_VELOCITY = 1.2;
+const VERTICAL_INTENT_RATIO = 1.2;
+const SWIPE_EXIT_DISTANCE = '120%';
+const SWIPE_ACTIVE_FADE_MAX = 0.4;
+const SWIPE_ACTIVE_SCALE_MAX = 0.02;
+
+export type ToastGestureDirection = 1 | -1;
+
+interface GesturePoint {
+ pointerId: number;
+ clientX: number;
+ clientY: number;
+}
+
+interface GestureState {
+ pointerId: number;
+ startX: number;
+ startY: number;
+ startTime: number;
+ direction: ToastGestureDirection;
+ intent: 'pending' | 'vertical' | 'opposite';
+ pausedTimer: boolean;
+ surfaceSize: number;
+ dismissThreshold: number;
+}
+
+interface UseToastGestureOptions {
+ direction: ToastGestureDirection;
+ enabled: boolean;
+ canPauseTimer: boolean;
+ isTimerPaused: () => boolean;
+ pauseTimer: () => void;
+ resumeTimer: () => void;
+ dismiss: () => void;
+ shouldIgnoreTarget: (
+ target: EventTarget | null,
+ root: HTMLElement,
+ ) => boolean;
+}
+
+interface ToastGestureBindings {
+ onPointerDown: (event: ReactPointerEvent<HTMLDivElement>) => void;
+ onPointerMove: (event: ReactPointerEvent<HTMLDivElement>) => void;
+ onPointerUp: (event: ReactPointerEvent<HTMLDivElement>) => void;
+ onPointerCancel: (event: ReactPointerEvent<HTMLDivElement>) => void;
+ onLostPointerCapture: (event: ReactPointerEvent<HTMLDivElement>) => void;
+}
+
+interface UseToastGestureResult {
+ rootRef: RefObject<HTMLDivElement | null>;
+ bindings: ToastGestureBindings;
+}
+
+function swipeProgressValue(travel: number, surfaceSize: number): number {
+ return Math.min(Math.max(travel / surfaceSize, 0), 1);
+}
+
+function clearTransientStyles(root: HTMLElement): void {
+ root.style.removeProperty('transition-duration');
+ root.style.removeProperty('--_toast-swipe-y');
+ root.style.removeProperty('--_toast-swipe-exit-y');
+ root.style.removeProperty('--_toast-swipe-opacity');
+ root.style.removeProperty('--_toast-swipe-scale');
+}
+
+export function useToastGesture({
+ direction,
+ enabled,
+ canPauseTimer,
+ isTimerPaused,
+ pauseTimer,
+ resumeTimer,
+ dismiss,
+ shouldIgnoreTarget,
+}: UseToastGestureOptions): UseToastGestureResult {
+ const rootRef = useRef<HTMLDivElement>(null);
+ const gestureRef = useRef<GestureState | null>(null);
+
+ const resetGesture = useCallback(
+ (shouldResume: boolean) => {
+ const root = rootRef.current;
+ const state = gestureRef.current;
+ gestureRef.current = null;
+ if (root) {
+ clearTransientStyles(root);
+ }
+ if (shouldResume && state?.pausedTimer) {
+ resumeTimer();
+ }
+ },
+ [resumeTimer],
+ );
+
+ const beginGesture = useCallback(
+ (point: GesturePoint, target: EventTarget | null): boolean => {
+ const root = rootRef.current;
+ if (
+ !root ||
+ !enabled ||
+ gestureRef.current != null ||
+ shouldIgnoreTarget(target, root)
+ ) {
+ return false;
+ }
+ const pausedTimer = canPauseTimer && !isTimerPaused();
+ if (pausedTimer) {
+ pauseTimer();
+ }
+ const surfaceSize = Math.max(root.getBoundingClientRect().height, 1);
+ gestureRef.current = {
+ pointerId: point.pointerId,
+ startX: point.clientX,
+ startY: point.clientY,
+ startTime: Date.now(),
+ direction,
+ intent: 'pending',
+ pausedTimer,
+ surfaceSize,
+ dismissThreshold: Math.max(
+ surfaceSize * SWIPE_DISMISS_RATIO,
+ FLICK_MIN_DISTANCE,
+ ),
+ };
+ return true;
+ },
+ [
+ canPauseTimer,
+ direction,
+ enabled,
+ isTimerPaused,
+ pauseTimer,
+ shouldIgnoreTarget,
+ ],
+ );
+
+ const moveGesture = useCallback(
+ (
+ point: GesturePoint,
+ preventDefault: () => void,
+ releaseCapture?: () => void,
+ ) => {
+ const state = gestureRef.current;
+ const root = rootRef.current;
+ if (!state || !root || point.pointerId !== state.pointerId) {
+ return;
+ }
+ const deltaX = point.clientX - state.startX;
+ const deltaY = point.clientY - state.startY;
+ const absX = Math.abs(deltaX);
+ const absY = Math.abs(deltaY);
+ if (state.intent === 'pending') {
+ if (absX > DRAG_PROMOTION_SLOP && absX > absY) {
+ releaseCapture?.();
+ resetGesture(true);
+ return;
+ }
+ if (
+ absY <= DRAG_PROMOTION_SLOP ||
+ absY <= absX * VERTICAL_INTENT_RATIO
+ ) {
+ return;
+ }
+ state.intent = deltaY * state.direction > 0 ? 'vertical' : 'opposite';
+ if (state.intent === 'opposite') {
+ releaseCapture?.();
+ resetGesture(true);
+ return;
+ }
+ root.style.setProperty('transition-duration', '0s');
+ }
+ preventDefault();
+ const travel = Math.max(0, deltaY * state.direction);
+ const progress = swipeProgressValue(travel, state.surfaceSize);
+ root.style.setProperty(
+ '--_toast-swipe-y',
+ `${travel * state.direction}px`,
+ );
+ root.style.setProperty(
+ '--_toast-swipe-opacity',
+ (1 - progress * SWIPE_ACTIVE_FADE_MAX).toFixed(3),
+ );
+ root.style.setProperty(
+ '--_toast-swipe-scale',
+ (1 - progress * SWIPE_ACTIVE_SCALE_MAX).toFixed(3),
+ );
+ },
+ [resetGesture],
+ );
+
+ const endGesture = useCallback(
+ (point: GesturePoint) => {
+ const state = gestureRef.current;
+ const root = rootRef.current;
+ if (!state || !root || point.pointerId !== state.pointerId) {
+ return;
+ }
+ const travel = Math.max(
+ 0,
+ (point.clientY - state.startY) * state.direction,
+ );
+ const elapsed = Math.max(1, Date.now() - state.startTime);
+ const isDismissed =
+ state.intent === 'vertical' &&
+ (travel >= state.dismissThreshold ||
+ (travel >= FLICK_MIN_DISTANCE && travel / elapsed > FLICK_VELOCITY));
+
+ gestureRef.current = null;
+ root.style.removeProperty('transition-duration');
+ if (isDismissed) {
+ root.style.setProperty(
+ '--_toast-swipe-exit-y',
+ state.direction === 1
+ ? SWIPE_EXIT_DISTANCE
+ : `calc(-1 * ${SWIPE_EXIT_DISTANCE})`,
+ );
+ dismiss();
+ return;
+ }
+ clearTransientStyles(root);
+ if (state.pausedTimer) {
+ resumeTimer();
+ }
+ },
+ [dismiss, resumeTimer],
+ );
+
+ const handlePointerDown = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (
+ event.pointerType === 'pen' &&
+ (event.button == null || event.button === 0) &&
+ beginGesture(event, event.target)
+ ) {
+ rootRef.current?.setPointerCapture?.(event.pointerId);
+ }
+ },
+ [beginGesture],
+ );
+
+ const handlePointerMove = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (event.pointerType !== 'pen') {
+ return;
+ }
+ moveGesture(
+ event,
+ () => event.preventDefault(),
+ () => rootRef.current?.releasePointerCapture?.(event.pointerId),
+ );
+ },
+ [moveGesture],
+ );
+
+ const handlePointerUp = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (event.pointerType !== 'pen') {
+ return;
+ }
+ rootRef.current?.releasePointerCapture?.(event.pointerId);
+ endGesture(event);
+ },
+ [endGesture],
+ );
+
+ const handlePointerCancel = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (
+ event.pointerType === 'pen' &&
+ gestureRef.current?.pointerId === event.pointerId
+ ) {
+ resetGesture(true);
+ }
+ },
+ [resetGesture],
+ );
+
+ useEffect(() => {
+ const root = rootRef.current;
+ if (!root || !enabled) {
+ return;
+ }
+ const point = (touch: Touch): GesturePoint => ({
+ pointerId: touch.identifier,
+ clientX: touch.clientX,
+ clientY: touch.clientY,
+ });
+ const changedTouch = (event: TouchEvent) => {
+ const pointerId = gestureRef.current?.pointerId;
+ return pointerId == null
+ ? undefined
+ : [...event.changedTouches].find(
+ touch => touch.identifier === pointerId,
+ );
+ };
+ const handleTouchStart = (event: TouchEvent) => {
+ const touch = event.touches.length === 1 ? event.changedTouches[0] : null;
+ if (touch) {
+ beginGesture(point(touch), event.target);
+ }
+ };
+ const handleTouchMove = (event: TouchEvent) => {
+ const touch = changedTouch(event);
+ if (touch) {
+ moveGesture(point(touch), () => {
+ if (event.cancelable) {
+ event.preventDefault();
+ }
+ });
+ }
+ };
+ const handleTouchEnd = (event: TouchEvent) => {
+ const touch = changedTouch(event);
+ if (touch) {
+ endGesture(point(touch));
+ } else if (event.touches.length === 0) {
+ resetGesture(true);
+ }
+ };
+ const handleTouchCancel = () => resetGesture(true);
+
+ root.addEventListener('touchstart', handleTouchStart, {passive: true});
+ root.addEventListener('touchmove', handleTouchMove, {passive: false});
+ root.addEventListener('touchend', handleTouchEnd, {passive: true});
+ root.addEventListener('touchcancel', handleTouchCancel, {passive: true});
+ return () => {
+ root.removeEventListener('touchstart', handleTouchStart);
+ root.removeEventListener('touchmove', handleTouchMove);
+ root.removeEventListener('touchend', handleTouchEnd);
+ root.removeEventListener('touchcancel', handleTouchCancel);
+ };
+ }, [beginGesture, enabled, endGesture, moveGesture, resetGesture]);
+
+ return {
+ rootRef,
+ bindings: {
+ onPointerDown: handlePointerDown,
+ onPointerMove: handlePointerMove,
+ onPointerUp: handlePointerUp,
+ onPointerCancel: handlePointerCancel,
+ onLostPointerCapture: handlePointerCancel,
+ },
+ };
+}
diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.ts
index d79926e69b..2ee0527746 100644
--- a/packages/core/src/theme/derivedVarRegistry.test.ts
+++ b/packages/core/src/theme/derivedVarRegistry.test.ts
@@ -280,9 +280,13 @@ 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.
+ // Placement and swipe lifecycle values are private Toast behavior. A theme
+ // author controls the surface transform/opacity as a whole, not these values.
'--_toast-slide-y',
+ '--_toast-swipe-y',
+ '--_toast-swipe-exit-y',
+ '--_toast-swipe-opacity',
+ '--_toast-swipe-scale',
// 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,