An open source design system that's fully customizable and agent ready
TypeScript
feat(toast): add XDSToast system (#1194)
Cindy Zhang04065967995e
diff --git a/apps/storybook/.storybook/preview.tsx b/apps/storybook/.storybook/preview.tsxindex a35669fa01..4efa223775 100644--- a/apps/storybook/.storybook/preview.tsx+++ b/apps/storybook/.storybook/preview.tsx@@ -1,6 +1,6 @@import type {Preview, Decorator} from '@storybook/react';import * as React from 'react';-import {XDSTheme} from '@xds/core';+import {XDSTheme, XDSLayerProvider} from '@xds/core';import {defaultTheme} from '@xds/theme-default';import {neutralTheme} from '@xds/theme-neutral';import {brutalistTheme} from '@xds/theme-brutalist';@@ -54,13 +54,15 @@ const withXDSTheme: Decorator = (Story, context) => {return (<XDSTheme theme={theme} mode={mode}>- <div- style={{- backgroundColor: 'var(--color-background-surface)',- padding: 16,- }}>- <Story />- </div>+ <XDSLayerProvider>+ <div+ style={{+ backgroundColor: 'var(--color-background-surface)',+ padding: 16,+ }}>+ <Story />+ </div>+ </XDSLayerProvider></XDSTheme>);};diff --git a/apps/storybook/stories/Toast.stories.tsx b/apps/storybook/stories/Toast.stories.tsxnew file mode 100644index 0000000000..f2cdbd35fb--- /dev/null+++ b/apps/storybook/stories/Toast.stories.tsx@@ -0,0 +1,377 @@+import type {Meta, StoryObj} from '@storybook/react';+import {useState, useRef} from 'react';+import {useXDSToast, XDSToastViewport} from '@xds/core/Toast';+import type {XDSToastType} from '@xds/core/Toast';+import {XDSButton} from '@xds/core/Button';+import {XDSLink} from '@xds/core/Link';+import {XDSCard} from '@xds/core/Card';+import {XDSStack} from '@xds/core/Stack';+import {XDSDialog} from '@xds/core/Dialog';++const meta: Meta = {+ title: 'Core/XDSToast',+ tags: ['autodocs'],+ parameters: {+ docs: {+ description: {+ component:+ 'Imperative toast notification system. Use `useXDSToast()` to show transient feedback messages. Works with or without `XDSLayerProvider`.',+ },+ },+ },+};++export default meta;++// =============================================================================+// Default+// =============================================================================++export const Default: StoryObj = {+ render: function DefaultStory() {+ const toast = useXDSToast();+ return (+ <XDSButton+ label="Show toast"+ onClick={() => toast({body: 'This is an info toast'})}+ />+ );+ },+};++// =============================================================================+// Types+// =============================================================================++export const Types: StoryObj = {+ render: function TypesStory() {+ const toast = useXDSToast();+ const types: XDSToastType[] = ['info', 'error'];+ return (+ <XDSStack direction="row" gap={2}>+ {types.map(type => (+ <XDSButton+ key={type}+ label={type}+ variant={type === 'error' ? 'destructive' : 'secondary'}+ onClick={() =>+ toast({+ body: `This is a ${type} notification.`,+ type,+ })+ }+ />+ ))}+ </XDSStack>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'Two toast types: info (default) and error. Error toasts persist until dismissed.',+ },+ },+ },+};++// =============================================================================+// With Action (endContent)+// =============================================================================++export const WithAction: StoryObj = {+ render: function WithActionStory() {+ const toast = useXDSToast();+ return (+ <XDSStack direction="row" gap={2}>+ <XDSButton+ label="With button"+ onClick={() =>+ toast({+ body: 'Item deleted',+ isAutoHide: false,+ endContent: (+ <XDSButton+ label="Undo"+ variant="secondary"+ size="sm"+ onClick={() => console.log('Undo!')}+ />+ ),+ })+ }+ />+ <XDSButton+ label="With link"+ variant="secondary"+ onClick={() =>+ toast({+ body: 'Your report is ready.',+ isAutoHide: false,+ endContent: (+ <XDSLink href="#" hasUnderline>+ View report+ </XDSLink>+ ),+ })+ }+ />+ </XDSStack>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'Use `endContent` for trailing actions — buttons, links, or any content.',+ },+ },+ },+};++// =============================================================================+// Error Persists+// =============================================================================++export const ErrorPersists: StoryObj = {+ render: function ErrorPersistsStory() {+ const toast = useXDSToast();+ return (+ <XDSButton+ label="Trigger error"+ variant="destructive"+ onClick={() =>+ toast({+ body: 'Check your network connection and try again.',+ type: 'error',+ })+ }+ />+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'Error toasts default to `isAutoHide: false` — they persist until the user dismisses them.',+ },+ },+ },+};++// =============================================================================+// Programmatic Dismiss+// =============================================================================++export const ProgrammaticDismiss: StoryObj = {+ render: function ProgrammaticDismissStory() {+ const toast = useXDSToast();+ const dismissRef = useRef<(() => void) | null>(null);+ return (+ <XDSStack direction="row" gap={2}>+ <XDSButton+ label="Show persistent toast"+ onClick={() => {+ dismissRef.current = toast({+ body: 'Uploading...',+ isAutoHide: false,+ });+ }}+ />+ <XDSButton+ label="Dismiss"+ variant="secondary"+ onClick={() => {+ dismissRef.current?.();+ dismissRef.current = null;+ }}+ />+ </XDSStack>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ '`useXDSToast()` returns a dismiss function. Call it to remove the toast programmatically.',+ },+ },+ },+};++// =============================================================================+// Deduplication+// =============================================================================++export const Deduplication: StoryObj = {+ render: function DeduplicationStory() {+ const toast = useXDSToast();+ return (+ <XDSStack direction="row" gap={2}>+ <XDSButton+ label="Offline (ignore)"+ onClick={() =>+ toast({+ body: 'You are offline',+ uniqueID: 'offline',+ collisionBehavior: 'ignore',+ isAutoHide: false,+ })+ }+ />+ <XDSButton+ label="Progress (overwrite)"+ variant="secondary"+ onClick={() =>+ toast({+ body: `Uploading... ${Math.floor(Math.random() * 100)}%`,+ uniqueID: 'upload-progress',+ collisionBehavior: 'overwrite',+ isAutoHide: false,+ })+ }+ />+ </XDSStack>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ '`uniqueID` prevents duplicate toasts. `ignore` keeps the existing; `overwrite` replaces it.',+ },+ },+ },+};++// =============================================================================+// Stacking+// =============================================================================++export const Stacking: StoryObj = {+ render: function StackingStory() {+ const toast = useXDSToast();+ const countRef = useRef(0);+ return (+ <XDSButton+ label="Add toast"+ onClick={() => {+ countRef.current++;+ const types: XDSToastType[] = ['info', 'error'];+ const type = types[countRef.current % types.length];+ toast({+ body: `Toast #${countRef.current} — ${type} notification.`,+ type,+ });+ }}+ />+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'Multiple toasts stack vertically. Default max visible is 5.',+ },+ },+ },+};++// =============================================================================+// No Provider (fallback)+// =============================================================================++export const NoProvider: StoryObj = {+ render: function NoProviderStory() {+ const toast = useXDSToast();+ return (+ <XDSCard padding={4}>+ <XDSStack gap={2}>+ <p style={{margin: 0, fontSize: 14}}>+ No XDSLayerProvider — the hook creates a fallback viewport on+ document.body automatically.+ </p>+ <XDSButton+ label="Show toast"+ onClick={() =>+ toast({+ body: 'Works without a provider!',+ })+ }+ />+ </XDSStack>+ </XDSCard>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ '`useXDSToast()` works without a provider. It lazily mounts a fallback viewport on first call.',+ },+ },+ },+};++// =============================================================================+// Toast over Dialog+// =============================================================================++export const ToastOverDialog: StoryObj = {+ render: function ToastOverDialogStory() {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <XDSStack gap={2}>+ <XDSButton label="Open dialog" onClick={() => setIsOpen(true)} />+ <XDSDialog+ isOpen={isOpen}+ onClose={() => setIsOpen(false)}+ title="Dialog with scoped toasts">+ <XDSToastViewport isTopLayer={false}>+ <DialogToastContent onClose={() => setIsOpen(false)} />+ </XDSToastViewport>+ </XDSDialog>+ </XDSStack>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'Dialog with its own `XDSToastViewport` — toasts render inside the dialog\'s top layer context and appear above the dialog overlay.',+ },+ },+ },+};++function DialogToastContent({onClose}: {onClose: () => void}) {+ const toast = useXDSToast();+ return (+ <XDSStack gap={3}>+ <p>+ This dialog has its own toast viewport. Toasts fired here render+ inside the dialog — above its overlay.+ </p>+ <XDSStack direction="row" gap={2} wrap="wrap">+ <XDSButton+ label="Close"+ variant="secondary"+ onClick={onClose}+ />+ <XDSButton+ label="Show toast"+ onClick={() => {+ toast({body: 'Toast from inside the dialog!'});+ }}+ />+ <XDSButton+ label="Error toast"+ variant="destructive"+ onClick={() => {+ toast({body: 'Something went wrong.', type: 'error'});+ }}+ />+ </XDSStack>+ </XDSStack>+ );+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex d86dd63742..7c217878f3 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -406,6 +406,12 @@"import": "./dist/Timestamp/index.mjs","require": "./dist/Timestamp/index.js"},+ "./Toast": {+ "source": "./src/Toast/index.ts",+ "types": "./dist/Toast/index.d.ts",+ "import": "./dist/Toast/index.mjs",+ "require": "./dist/Toast/index.js"+ },"./ToggleButton": {"source": "./src/ToggleButton/index.ts","types": "./dist/ToggleButton/index.d.ts",diff --git a/packages/core/src/Layer/XDSLayerContext.ts b/packages/core/src/Layer/XDSLayerContext.tsnew file mode 100644index 0000000000..717285ed48--- /dev/null+++ b/packages/core/src/Layer/XDSLayerContext.ts@@ -0,0 +1,54 @@+'use client';++/**+ * @file XDSLayerContext.ts+ * @input React context+ * @output Exports XDSLayerContext and related types+ * @position Context definition for XDSLayerProvider+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Layer/index.ts+ * - /packages/core/src/Layer/XDSLayerProvider.tsx+ */++import {createContext, useContext} from 'react';++/**+ * Toast configuration passed through the layer provider.+ */+export interface LayerToastConfig {+ /** Position of the toast stack. @default 'bottomEnd' */+ position?: 'topEnd' | 'topStart' | 'bottomEnd' | 'bottomStart';+ /** Maximum visible toasts. @default 5 */+ maxVisible?: number;+ /** Inset from viewport edges. */+ inset?: {+ top?: number;+ bottom?: number;+ start?: number;+ end?: number;+ };+}++/**+ * Context value provided by XDSLayerProvider.+ */+export interface XDSLayerContextValue {+ /** Toast configuration from the provider. */+ toastConfig: LayerToastConfig;+ /** Whether this is a real provider (not fallback). */+ isProvider: true;+}++/**+ * React context for the layer provider.+ * Default value is null — hooks detect this and use the fallback.+ */+export const XDSLayerContext = createContext<XDSLayerContextValue | null>(null);++/**+ * Hook to access the layer context. Returns null if no provider exists.+ */+export function useXDSLayerContext(): XDSLayerContextValue | null {+ return useContext(XDSLayerContext);+}diff --git a/packages/core/src/Layer/XDSLayerProvider.tsx b/packages/core/src/Layer/XDSLayerProvider.tsxnew file mode 100644index 0000000000..3189007bd3--- /dev/null+++ b/packages/core/src/Layer/XDSLayerProvider.tsx@@ -0,0 +1,59 @@+'use client';++import {useMemo, type ReactNode} from 'react';+import {+ XDSLayerContext,+ useXDSLayerContext,+ type XDSLayerContextValue,+ type LayerToastConfig,+} from './XDSLayerContext';+import {XDSToastViewport} from '../Toast/XDSToastViewport';++export interface XDSLayerProviderProps {+ children: ReactNode;+ /** Toast configuration. Omit to use defaults. */+ toast?: LayerToastConfig;+}++/**+ * App-level provider for layer systems (toast, sheet, imperative modals).+ *+ * Optional — hooks fall back to a lazy self-mounting viewport when no+ * provider exists. Nested providers are no-ops.+ *+ * @example+ * ```+ * <XDSLayerProvider toast={{ position: 'topEnd', maxVisible: 3 }}>+ * <App />+ * </XDSLayerProvider>+ * ```+ */+export function XDSLayerProvider({+ children,+ toast: toastConfig = {},+}: XDSLayerProviderProps) {+ const existingContext = useXDSLayerContext();++ const contextValue = useMemo<XDSLayerContextValue>(+ () => ({toastConfig, isProvider: true}),+ [toastConfig],+ );++ // Nested provider — pass through+ if (existingContext) {+ return <>{children}</>;+ }++ return (+ <XDSLayerContext.Provider value={contextValue}>+ <XDSToastViewport+ position={toastConfig.position}+ maxVisible={toastConfig.maxVisible}+ inset={toastConfig.inset}>+ {children}+ </XDSToastViewport>+ </XDSLayerContext.Provider>+ );+}++XDSLayerProvider.displayName = 'XDSLayerProvider';diff --git a/packages/core/src/Layer/index.ts b/packages/core/src/Layer/index.tsindex 6c64dc8eb5..2e95deb3a8 100644--- a/packages/core/src/Layer/index.ts+++ b/packages/core/src/Layer/index.ts@@ -27,6 +27,12 @@ export type {FixedLayerReturn,} from './useXDSLayer';+// Layer provider+export {XDSLayerProvider} from './XDSLayerProvider';+export type {XDSLayerProviderProps} from './XDSLayerProvider';+export {XDSLayerContext, useXDSLayerContext} from './XDSLayerContext';+export type {XDSLayerContextValue, LayerToastConfig} from './XDSLayerContext';+// Shared entry animation styles for layer-based componentsexport {layerAnimations} from './layerAnimations.stylex';diff --git a/packages/core/src/Toast/Toast.doc.mjs b/packages/core/src/Toast/Toast.doc.mjsnew file mode 100644index 0000000000..7e15d5825e--- /dev/null+++ b/packages/core/src/Toast/Toast.doc.mjs@@ -0,0 +1,83 @@+/** @type {import('../docs-types').ComponentDoc} */++export const docs = {+ name: 'Toast',+ description:+ 'Toast notification system with auto-dismiss, stacking, deduplication, and smooth animations. Uses XDSMediaTheme for inverted surface theming.',++ keywords: ["toast","notification","snackbar","alert","message","feedback","status"],+ features: [+ "Types: 'info' (default), 'error'",+ 'Auto-dismiss: info toasts dismiss after 5s, error toasts persist',+ 'Pause on hover/focus: timer pauses during interaction',+ 'Stacking: multiple toasts stack with smooth enter/exit animations',+ 'Deduplication: uniqueID with ignore or overwrite collision behavior',+ 'Programmatic dismiss: show() returns a dismiss function',+ 'End content slot: trailing actions (buttons, links)',+ 'Fallback viewport: works without a provider via document.body fallback',+ 'Inverted surface: uses XDSMediaTheme for correct colors on dark/light backgrounds',+ 'Accessible: role=status/alert, aria-live=polite/assertive',+ ],++ props: [+ {+ name: 'body',+ type: 'ReactNode',+ description: 'Primary message content.',+ required: true,+ },+ {+ name: 'type',+ type: "'info' | 'error'",+ 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.',+ },+ {+ name: 'autoHideDuration',+ type: 'number',+ description: 'Duration in ms before auto-dismiss.',+ default: '5000',+ },+ {+ name: 'endContent',+ type: 'ReactNode',+ description: 'Content rendered at the trailing end (e.g. Undo button, link).',+ },+ {+ name: 'uniqueID',+ type: 'string',+ description: 'Unique identifier for deduplication.',+ },+ {+ name: 'collisionBehavior',+ type: "'overwrite' | 'ignore'",+ description: 'Behavior when a toast with matching uniqueID already exists.',+ default: "'overwrite'",+ },+ {+ name: 'onHide',+ type: '(reason: "auto" | "manual") => void',+ description: 'Callback fired when the toast is removed.',+ },+ ],++ examples: [+ {+ label: 'Basic',+ code: `const toast = useXDSToast();\ntoast({ body: "Changes saved" });`,+ },+ {+ label: 'Error',+ code: `toast({ body: "Failed to save", type: "error" });`,+ },+ {+ label: 'With action',+ code: `toast({\n body: "Item deleted",\n isAutoHide: false,\n endContent: <XDSButton label="Undo" variant="secondary" size="sm" onClick={undo} />,\n});`,+ },+ ],+};diff --git a/packages/core/src/Toast/XDSToast.tsx b/packages/core/src/Toast/XDSToast.tsxnew file mode 100644index 0000000000..dfd735db50--- /dev/null+++ b/packages/core/src/Toast/XDSToast.tsx@@ -0,0 +1,203 @@+'use client';++import {useCallback, useEffect, useRef} from 'react';+import type {ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSButton} from '../Button';+import {XDSIcon} from '../Icon';+import {+ colorVars,+ spacingVars,+ radiusVars,+ durationVars,+ easeVars,+ shadowVars,+ typographyVars,+ typeScaleDefaults,+} from '../theme/tokens.stylex';+import {xdsClassName, mergeProps} from '../utils';+import {useXDSTheme} from '../theme';+import {XDSMediaTheme} from '../theme/XDSMediaTheme';+import type {XDSToastType, XDSToastDismissReason} from './types';++const styles = stylex.create({+ root: {+ paddingBlock: spacingVars['--spacing-4'],+ paddingInline: spacingVars['--spacing-4'],+ borderRadius: radiusVars['--radius-container'],+ width: 400,+ maxWidth: 'calc(100vw - 32px)',+ boxShadow: shadowVars['--shadow-med'],+ opacity: 1,+ fontFamily: typographyVars['--font-family-body'],+ fontSize: typeScaleDefaults['--text-body-size'],+ lineHeight: typeScaleDefaults['--text-body-leading'],+ transform: 'translateY(0)',+ transitionProperty: 'opacity, transform',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0.01ms',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ '@starting-style': {+ opacity: 0,+ transform: 'translateY(8px)',+ },+ },+ variantDefault: {+ backgroundColor: colorVars['--color-background-inverted'],+ },+ inner: {+ display: 'flex',+ alignItems: 'flex-start',+ gap: spacingVars['--spacing-3'],+ width: '100%',+ },+ variantError: {+ backgroundColor: colorVars['--color-background-error-inverted'],+ },+ content: {+ flex: 1,+ minWidth: 0,+ },+ exiting: {+ opacity: 0,+ transform: 'translateY(-8px)',+ },+ endContent: {+ flexShrink: 0,+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ marginBlock: `calc(${spacingVars['--spacing-1']} * -1)`,+ marginInlineEnd: `calc(${spacingVars['--spacing-1']} * -1)`,+ },+});++export interface XDSToastProps {+ type: XDSToastType;+ body: ReactNode;+ endContent?: ReactNode;+ isAutoHide: boolean;+ autoHideDuration: number;+ isExiting?: boolean;+ onDismiss: (reason: XDSToastDismissReason) => void;+}++/**+ * Individual toast notification.+ *+ * Renders with inverted surface colors for the default variant,+ * and error-inverted for the error variant. Uses XDSMediaTheme+ * to set the correct token context for children. Pauses auto-dismiss+ * on hover and focus.+ *+ * @example+ * ```+ * <XDSToast+ * type="info"+ * body="Saved successfully"+ * isAutoHide={true}+ * autoHideDuration={5000}+ * onDismiss={(reason) => removeToast(id, reason)}+ * />+ * ```+ */+export function XDSToast({+ type,+ body,+ endContent,+ isAutoHide,+ autoHideDuration,+ isExiting = false,+ onDismiss,+}: XDSToastProps) {+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const isPausedRef = useRef(false);+ const remainingRef = useRef(autoHideDuration);+ const startTimeRef = useRef(Date.now());++ const startTimer = useCallback(() => {+ if (!isAutoHide) return;+ if (timerRef.current) clearTimeout(timerRef.current);+ startTimeRef.current = Date.now();+ timerRef.current = setTimeout(() => {+ onDismiss('auto');+ }, remainingRef.current);+ }, [isAutoHide, onDismiss]);++ const pauseTimer = useCallback(() => {+ if (!isAutoHide || isPausedRef.current) return;+ isPausedRef.current = true;+ if (timerRef.current) {+ clearTimeout(timerRef.current);+ timerRef.current = null;+ }+ const elapsed = Date.now() - startTimeRef.current;+ remainingRef.current = Math.max(remainingRef.current - elapsed, 1000);+ }, [isAutoHide]);++ const resumeTimer = useCallback(() => {+ if (!isAutoHide || !isPausedRef.current) return;+ isPausedRef.current = false;+ startTimer();+ }, [isAutoHide, startTimer]);++ useEffect(() => {+ remainingRef.current = autoHideDuration;+ startTimer();+ return () => {+ if (timerRef.current) clearTimeout(timerRef.current);+ };+ }, [autoHideDuration, startTimer]);++ const handleDismiss = useCallback(() => {+ onDismiss('manual');+ }, [onDismiss]);++ const isError = type === 'error';+ // Determine media mode: inverted surface is always dark in light mode,+ // always light in dark mode. Error toast is always on a dark surface.+ const {mode} = useXDSTheme();+ const mediaMode = isError || mode === 'light' ? 'dark' : 'light';++ return (+ <div+ role={isError ? 'alert' : 'status'}+ aria-live={isError ? 'assertive' : 'polite'}+ aria-atomic="true"+ onMouseEnter={pauseTimer}+ onMouseLeave={resumeTimer}+ onFocusCapture={pauseTimer}+ onBlurCapture={resumeTimer}+ {...mergeProps(+ xdsClassName('toast', {type}),+ stylex.props(+ styles.root,+ isError ? styles.variantError : styles.variantDefault,+ isExiting && styles.exiting,+ ),+ )}>+ <XDSMediaTheme mode={mediaMode}>+ <div {...stylex.props(styles.inner)}>+ <div {...stylex.props(styles.content)}>+ {body}+ </div>++ <div {...stylex.props(styles.endContent)}>+ {endContent}+ <XDSButton+ variant="ghost"+ size="sm"+ icon={<XDSIcon icon="close" size="sm" color="inherit" />}+ label="Dismiss notification"+ onClick={handleDismiss}+ />+ </div>+ </div>+ </XDSMediaTheme>+ </div>+ );+}++XDSToast.displayName = 'XDSToast';diff --git a/packages/core/src/Toast/XDSToastContext.ts b/packages/core/src/Toast/XDSToastContext.tsnew file mode 100644index 0000000000..0a72357a7c--- /dev/null+++ b/packages/core/src/Toast/XDSToastContext.ts@@ -0,0 +1,18 @@+import {createContext} from 'react';+import type {XDSToastEntry, XDSToastDismissReason} from './types';++/** Internal context value for toast state management. */+export interface XDSToastContextValue {+ /** Add a toast. */+ addToast: (entry: XDSToastEntry) => void;+ /** Remove a toast by ID with a reason. */+ removeToast: (id: string, reason: XDSToastDismissReason) => void;+ /** Find a toast by uniqueID. */+ findByUniqueID: (uniqueID: string) => XDSToastEntry | undefined;+}++/**+ * React context for toast state. Default is null — the hook+ * falls back to a self-mounting viewport when no provider exists.+ */+export const XDSToastContext = createContext<XDSToastContextValue | null>(null);diff --git a/packages/core/src/Toast/XDSToastViewport.tsx b/packages/core/src/Toast/XDSToastViewport.tsxnew file mode 100644index 0000000000..1d436e1443--- /dev/null+++ b/packages/core/src/Toast/XDSToastViewport.tsx@@ -0,0 +1,217 @@+'use client';++import {useCallback, useEffect, useMemo, useRef, useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {spacingVars, durationVars, easeVars} from '../theme/tokens.stylex';+import {XDSToast} from './XDSToast';+import {XDSToastContext, type XDSToastContextValue} from './XDSToastContext';+import type {+ XDSToastEntry,+ XDSToastPosition,+ XDSToastDismissReason,+} from './types';++const styles = stylex.create({+ viewport: {+ position: 'fixed',+ zIndex: 500,+ display: 'flex',+ flexDirection: 'column',+ padding: spacingVars['--spacing-4'],+ pointerEvents: 'none',+ // Reset popover styles — the popover attribute puts us in the top+ // layer (above dialogs), but we don't want its default styles.+ inset: 'unset',+ border: 'none',+ background: 'none',+ overflow: 'visible',+ },+ bottomEnd: {bottom: 0, insetInlineEnd: 0, alignItems: 'flex-end'},+ bottomStart: {bottom: 0, insetInlineStart: 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',+ gridTemplateRows: '1fr',+ paddingBlockEnd: spacingVars['--spacing-3'],+ transitionProperty: 'grid-template-rows, padding',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0.01ms',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ '@starting-style': {+ gridTemplateRows: '0fr',+ paddingBlockEnd: 0,+ },+ },+ toastWrapperExiting: {+ gridTemplateRows: '0fr',+ paddingBlockEnd: 0,+ },+ toastWrapperInner: {+ overflow: 'hidden',+ },+});++export interface XDSToastViewportProps {+ position?: XDSToastPosition;+ maxVisible?: number;+ inset?: {top?: number; bottom?: number; start?: number; end?: number};+ /**+ * Promote viewport to CSS top layer via popover="manual".+ * Set to false when inside a dialog or other top-layer element.+ * @default true+ */+ isTopLayer?: boolean;+ children?: React.ReactNode;+}++export function XDSToastViewport({+ position = 'bottomEnd',+ maxVisible = 5,+ inset,+ isTopLayer = true,+ children,+}: XDSToastViewportProps) {+ const [toasts, setToasts] = useState<XDSToastEntry[]>([]);+ const [exitingIds, setExitingIds] = useState<Set<string>>(new Set());+ const toastsRef = useRef(toasts);+ toastsRef.current = toasts;++ const addToast = useCallback((entry: XDSToastEntry) => {+ setToasts(prev => {+ const {uniqueID, collisionBehavior = 'overwrite'} = entry.options;+ if (uniqueID) {+ const existing = prev.find(t => t.options.uniqueID === uniqueID);+ if (existing) {+ if (collisionBehavior === 'ignore') return prev;+ return prev.map(t => (t.options.uniqueID === uniqueID ? entry : t));+ }+ }+ return [...prev, entry];+ });+ }, []);++ const removeToast = useCallback(+ (id: string, reason: XDSToastDismissReason) => {+ const entry = toastsRef.current.find(t => t.id === id);+ if (entry) entry.options.onHide?.(reason);+ setExitingIds(prev => {+ if (prev.has(id)) return prev;+ return new Set(prev).add(id);+ });+ },+ [],+ );++ const handleExited = useCallback((id: string) => {+ setExitingIds(prev => {+ if (!prev.has(id)) return prev;+ const next = new Set(prev);+ next.delete(id);+ return next;+ });+ setToasts(prev => prev.filter(t => t.id !== id));+ }, []);++ const findByUniqueID = useCallback((uid: string) => {+ return toastsRef.current.find(t => t.options.uniqueID === uid);+ }, []);++ const contextValue = useMemo<XDSToastContextValue>(+ () => ({addToast, removeToast, findByUniqueID}),+ [addToast, removeToast, findByUniqueID],+ );++ const visibleToasts = toasts.slice(-maxVisible);+ const insetStyle: React.CSSProperties = {};+ if (inset?.top) insetStyle.top = inset.top;+ if (inset?.bottom) insetStyle.bottom = inset.bottom;+ if (inset?.start) insetStyle.insetInlineStart = inset.start;+ if (inset?.end) insetStyle.insetInlineEnd = inset.end;++ // Show the popover on mount so it enters the top layer+ const viewportRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (!isTopLayer) return;+ const el = viewportRef.current;+ if (el && typeof el.showPopover === 'function') {+ try { el.showPopover(); } catch { /* already showing */ }+ }+ }, [isTopLayer]);++ const posStyle =+ position === 'topEnd'+ ? styles.topEnd+ : position === 'topStart'+ ? styles.topStart+ : position === 'bottomStart'+ ? styles.bottomStart+ : styles.bottomEnd;++ return (+ <XDSToastContext.Provider value={contextValue}>+ {children}+ <div+ ref={viewportRef}+ role="region"+ aria-label="Notifications"+ // 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}+ {...stylex.props(styles.viewport, posStyle)}+ style={Object.keys(insetStyle).length > 0 ? insetStyle : undefined}>+ {visibleToasts.map(entry => {+ const o = entry.options;+ const type = o.type ?? 'info';+ const isAutoHide = o.isAutoHide ?? (type === 'error' ? false : true);+ const dur = o.autoHideDuration ?? 5000;+ const isExiting = exitingIds.has(entry.id);+ return (+ <div+ key={entry.id}+ {...stylex.props(+ styles.toastWrapper,+ isExiting && styles.toastWrapperExiting,+ )}+ onTransitionEnd={+ isExiting+ ? (e: React.TransitionEvent) => {+ if (e.propertyName === 'grid-template-rows') {+ handleExited(entry.id);+ }+ }+ : undefined+ }>+ <div {...stylex.props(styles.toastWrapperInner)}>+ <XDSToast+ type={type}+ body={o.body}++ endContent={o.endContent}+ isAutoHide={isAutoHide}+ autoHideDuration={dur}+ isExiting={isExiting}+ onDismiss={reason => removeToast(entry.id, reason)}+ />+ </div>+ </div>+ );+ })}+ </div>+ </XDSToastContext.Provider>+ );+}+XDSToastViewport.displayName = 'XDSToastViewport';diff --git a/packages/core/src/Toast/index.ts b/packages/core/src/Toast/index.tsnew file mode 100644index 0000000000..63c8116d85--- /dev/null+++ b/packages/core/src/Toast/index.ts@@ -0,0 +1,17 @@+'use client';++export {useXDSToast} from './useXDSToast';++export type {+ XDSToastType,+ XDSToastPosition,+ XDSToastCollisionBehavior,+ XDSToastDismissReason,+ XDSToastOptions,+ XDSToastDismissFn,+ XDSShowToastFn,+} from './types';++// Exported for XDSLayerProvider integration+export {XDSToastViewport} from './XDSToastViewport';+export type {XDSToastViewportProps} from './XDSToastViewport';diff --git a/packages/core/src/Toast/types.ts b/packages/core/src/Toast/types.tsnew file mode 100644index 0000000000..25f5f151c7--- /dev/null+++ b/packages/core/src/Toast/types.ts@@ -0,0 +1,63 @@+import type {ReactNode} from 'react';++/** Toast status type. Controls color scheme. */+export type XDSToastType = 'info' | 'error';++/** Position for the toast stack relative to the viewport. */+export type XDSToastPosition =+ | 'topEnd'+ | 'topStart'+ | 'bottomEnd'+ | 'bottomStart';++/** Behavior when a toast with the same uniqueID already exists. */+export type XDSToastCollisionBehavior = 'overwrite' | 'ignore';++/** Reason why a toast was dismissed. */+export type XDSToastDismissReason = 'auto' | 'manual';++/** Options for showing a toast. */+export interface XDSToastOptions {+ /** Primary message content. */+ body: ReactNode;+ /**+ * Toast type controlling color.+ * @default 'info'+ */+ type?: XDSToastType;+ /**+ * Whether the toast auto-dismisses.+ * Defaults to true for info, false for error.+ */+ isAutoHide?: boolean;+ /**+ * Duration in ms before auto-dismiss.+ * @default 5000+ */+ autoHideDuration?: number;+ /** Content rendered at the end of the toast (trailing slot). */+ endContent?: ReactNode;++ /** Unique identifier for deduplication. */+ uniqueID?: string;+ /**+ * Behavior when a toast with matching uniqueID already exists.+ * @default 'overwrite'+ */+ collisionBehavior?: XDSToastCollisionBehavior;+ /** Callback fired when the toast is removed. */+ onHide?: (reason: XDSToastDismissReason) => void;+}++/** Function to programmatically dismiss a toast. */+export type XDSToastDismissFn = () => void;++/** Function returned by useXDSToast to show toasts. */+export type XDSShowToastFn = (options: XDSToastOptions) => XDSToastDismissFn;++/** Internal toast state with ID and metadata. */+export interface XDSToastEntry {+ id: string;+ options: XDSToastOptions;+ createdAt: number;+}diff --git a/packages/core/src/Toast/useXDSToast.tsx b/packages/core/src/Toast/useXDSToast.tsxnew file mode 100644index 0000000000..1f0db20393--- /dev/null+++ b/packages/core/src/Toast/useXDSToast.tsx@@ -0,0 +1,139 @@+'use client';++import {useCallback, useContext, useEffect, useRef} from 'react';+import {createRoot} from 'react-dom/client';+import {XDSToastContext, type XDSToastContextValue} from './XDSToastContext';+import {XDSToastViewport} from './XDSToastViewport';+import type {+ XDSToastOptions,+ XDSToastDismissFn,+ XDSShowToastFn,+ XDSToastEntry,+} from './types';++// Fallback singleton+let fallbackContext: XDSToastContextValue | null = null;+let fallbackRoot: ReturnType<typeof createRoot> | null = null;+let fallbackWarned = false;++function getFallbackContext(): XDSToastContextValue {+ if (fallbackContext) return fallbackContext;++ if (typeof document === 'undefined') {+ throw new Error(+ 'useXDSToast: Cannot create fallback viewport during SSR. ' ++ 'Wrap your app with <XDSLayerProvider> or <XDSAppShell>.',+ );+ }++ if (!fallbackWarned) {+ fallbackWarned = true;+ console.warn(+ 'useXDSToast: No XDSLayerProvider found. Using fallback viewport. ' ++ 'Wrap your app with <XDSLayerProvider> or <XDSAppShell> for full control.',+ );+ }++ const container = document.createElement('div');+ container.setAttribute('data-xds-toast-fallback', '');+ document.body.appendChild(container);++ let resolveCtx: (ctx: XDSToastContextValue) => void;+ const ctxReady = new Promise<XDSToastContextValue>(r => {+ resolveCtx = r;+ });++ const FallbackCapture = () => {+ const ctx = useContext(XDSToastContext);+ const doneRef = useRef(false);+ useEffect(() => {+ if (ctx && !doneRef.current) {+ doneRef.current = true;+ fallbackContext = ctx;+ resolveCtx!(ctx);+ }+ }, [ctx]);+ return null;+ };++ fallbackRoot = createRoot(container);+ fallbackRoot.render(+ <XDSToastViewport>+ <FallbackCapture />+ </XDSToastViewport>,+ );++ // Proxy that queues calls until real context is captured+ const pending: XDSToastEntry[] = [];+ const proxy: XDSToastContextValue = {+ addToast: entry => {+ if (fallbackContext && fallbackContext !== proxy) {+ fallbackContext.addToast(entry);+ } else {+ pending.push(entry);+ ctxReady.then(ctx => {+ for (const e of pending) ctx.addToast(e);+ pending.length = 0;+ });+ }+ },+ removeToast: (id, reason) => {+ if (fallbackContext && fallbackContext !== proxy) {+ fallbackContext.removeToast(id, reason);+ }+ },+ findByUniqueID: uid => {+ if (fallbackContext && fallbackContext !== proxy) {+ return fallbackContext.findByUniqueID(uid);+ }+ return undefined;+ },+ };++ fallbackContext = proxy;+ return proxy;+}++let toastIdCounter = 0;+function generateToastId(): string {+ return `xds-toast-${++toastIdCounter}`;+}++/**+ * Hook to show toast notifications.+ *+ * Returns an imperative function that shows a toast and returns a dismiss function.+ * Works with or without a provider — falls back to a self-mounting viewport.+ *+ * @example+ * ```+ * function SaveButton() {+ * const toast = useXDSToast();+ * const handleSave = async () => {+ * try {+ * await saveData();+ * toast({ body: 'Saved successfully' });+ * } catch {+ * toast({ body: 'Failed to save', type: 'error' });+ * }+ * };+ * return <XDSButton label="Save" onClick={handleSave} />;+ * }+ * ```+ */+export function useXDSToast(): XDSShowToastFn {+ const contextFromProvider = useContext(XDSToastContext);++ const showToast = useCallback(+ (options: XDSToastOptions): XDSToastDismissFn => {+ const ctx = contextFromProvider ?? getFallbackContext();+ const id = generateToastId();+ const entry: XDSToastEntry = {id, options, createdAt: Date.now()};+ ctx.addToast(entry);+ return () => ctx.removeToast(id, 'manual');+ },+ [contextFromProvider],+ );++ return showToast;+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 449ea490c8..72aadc0947 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -91,6 +91,22 @@ export type {FixedLayerReturn,} from './Layer';+// Layer provider+export {XDSLayerProvider} from './Layer';+export type {XDSLayerProviderProps, LayerToastConfig} from './Layer';++// Toast+export {useXDSToast} from './Toast';+export type {+ XDSToastType,+ XDSToastPosition,+ XDSToastCollisionBehavior,+ XDSToastDismissReason,+ XDSToastOptions,+ XDSToastDismissFn,+ XDSShowToastFn,+} from './Toast';+// Popover component and hookexport * from './Popover';diff --git a/packages/core/src/theme/XDSMediaTheme.tsx b/packages/core/src/theme/XDSMediaTheme.tsxindex af1a96fc7d..fcf28916fb 100644--- a/packages/core/src/theme/XDSMediaTheme.tsx+++ b/packages/core/src/theme/XDSMediaTheme.tsx@@ -24,7 +24,7 @@* @example* ```tsx* // Dark surface (e.g. toast on a light page)- * <div style={{ backgroundColor: 'var(--color-surface-inverted)' }}>+ * <div style={{ backgroundColor: 'var(--color-background-inverted)' }}>* <XDSMediaTheme mode="dark">* <XDSButton label="Undo" variant="ghost" />* </XDSMediaTheme>diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.tsindex 1460c9e8fb..57e26919da 100644--- a/packages/core/src/theme/tokens.stylex.ts+++ b/packages/core/src/theme/tokens.stylex.ts@@ -48,6 +48,8 @@ export const colorDefaults = {// Surface variants'--color-background-card': 'light-dark(#FFFFFF, #1F1F22)','--color-background-popover': 'light-dark(#FFFFFF, #28292C)',+ '--color-background-inverted': 'light-dark(#0A1317, #FFFFFF)',+ '--color-background-error-inverted': 'light-dark(#AA071E, #E3193B)',// Status/Sentiment'--color-success': 'light-dark(#0D8626, #0D8626)',