Ordo UI
组件Feedback

Toast

@mox-hub/ui 组件 · Feedback · canonical

toast@mox-hub/uiFeedbackcanonicalsrc/components/toast.tsx
变体演示toast

Props API

Prop类型默认值说明
children*ReactNode——
position*ToastPosition"top-right"—
offset*ToastOffset——
container*HTMLElement | ShadowRoot | RefObject<HTMLElement | ShadowRoot>——
portalProps*Omit<ToastPortalProps, "ref"> & RefAttributes<HTMLDivElement>——
closeLabel*string——

源码

packages/ui/src/components/toast.tsx
"use client"

import { Toast } from "@base-ui/react/toast"
import {
  CircleAlertIcon,
  CircleCheckIcon,
  InfoIcon,
  LoaderCircleIcon,
  TriangleAlertIcon,
  XIcon,
} from "lucide-react"
import type React from "react"
import { cn } from "../lib/utils"
import { buttonVariants } from "./button"

/*
 * coss ui Toast(base-ui 配方移植,registry @coss/toast)
 * 底层为 base-ui Toast + createToastManager;命令式 API 见文件尾部 sonner 兼容层。
 */

const TOAST_ICONS = {
  error: CircleAlertIcon,
  info: InfoIcon,
  loading: LoaderCircleIcon,
  success: CircleCheckIcon,
  warning: TriangleAlertIcon,
} as const

type SwipeDirection = "up" | "down" | "left" | "right"

type ToastData = {
  rootProps?: Omit<
    React.ComponentProps<typeof Toast.Root>,
    "children" | "className" | "swipeDirection" | "toast"
  >
  tooltipStyle?: boolean
}

function getSwipeDirection(position: ToastPosition): SwipeDirection[] {
  const verticalDirection: SwipeDirection = position.startsWith("top")
    ? "up"
    : "down"

  if (position.includes("center")) {
    return [verticalDirection]
  }

  if (position.includes("left")) {
    return ["left", verticalDirection]
  }

  return ["right", verticalDirection]
}

function upsertReplayClassName(toast: {
  type?: string
  updateKey?: number
}): string | undefined {
  const k = toast.updateKey ?? 0
  if (k <= 0) return undefined
  // P3-08:颜色由 root 上的 --toast-replay-color 决定(success/error/warning/info/中性),
  // 动画本身只读该变量,不再把所有非 error 更新都闪成成功绿。
  return k % 2 === 0 ? "animate-toast-replay-a" : "animate-toast-replay-b"
}

/** #40:常驻 toast 的键盘关闭出口;悬停/聚焦显形,coarse pointer 常显。 */
function ToastCloseButton({ label }: { label: string }) {
  return (
    <Toast.Close
      aria-label={label}
      title={label}
      className="flex size-control-2xs shrink-0 items-center justify-center rounded-full text-muted-foreground opacity-0 transition-opacity duration-fast hover:bg-muted hover:text-foreground group-hover/toast:opacity-100 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring/50 pointer-coarse:size-11 pointer-coarse:opacity-100"
    >
      <XIcon className="size-3.5" />
    </Toast.Close>
  )
}

function Toasts({
  position,
  offset,
  container,
  portalProps,
  closeLabel,
}: {
  position: ToastPosition
  offset?: ToastOffset
  container?: React.ComponentProps<typeof Toast.Portal>["container"]
  portalProps?: React.ComponentProps<typeof Toast.Portal>
  closeLabel: string
}): React.ReactElement {
  const { toasts } = Toast.useToastManager()
  const swipeDirection = getSwipeDirection(position)
  // 调用方 offset 以 inline CSS 变量覆盖类里的默认 --toast-inset(4/8 档),
  // number 按 px,string 原样交给 CSS(可传 calc()/env() 安全区表达式)。
  const offsetStyle =
    offset == null
      ? undefined
      : ({
          "--toast-inset": typeof offset === "number" ? `${offset}px` : offset,
        } as React.CSSProperties)

  return (
    <Toast.Portal
      data-slot="toast-portal"
      {...portalProps}
      container={container ?? portalProps?.container}
    >
      <Toast.Viewport
        style={offsetStyle}
        className={cn(
          "fixed z-toast mx-auto flex w-[calc(100%-var(--toast-inset)*2)] max-w-90 [--toast-inset:--spacing(4)] sm:[--toast-inset:--spacing(8)]",
          // Vertical positioning
          "data-[position*=top]:top-(--toast-inset)",
          "data-[position*=bottom]:bottom-(--toast-inset)",
          // Horizontal positioning
          "data-[position*=left]:left-(--toast-inset)",
          "data-[position*=right]:right-(--toast-inset)",
          "data-[position*=center]:left-1/2 data-[position*=center]:-translate-x-1/2"
        )}
        data-position={position}
        data-slot="toast-viewport"
      >
        {toasts.map((toast) => {
          const Icon = toast.type
            ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS]
            : null
          const toastData = toast.data as ToastData | undefined

          return (
            <Toast.Root
              key={toast.id}
              className={cn(
                // 层级交给 Viewport 的 z-toast + DOM 顺序/transform,不再用 9999 逃离七档(审计 P1-12);
                // 过渡走全站 motion token(120–240ms),移除 0.5s 自定义缓动。
                "group/toast absolute h-(--toast-calc-height) w-full select-none rounded-lg border border-border bg-[color-mix(in_srgb,var(--popover),var(--color-black)_calc(1%*max(0,var(--toast-index,0))))] not-dark:bg-clip-padding text-popover-foreground shadow-xs/5 transition-toast duration-slow ease-emphasis in-data-[type=success]:[--toast-replay-color:var(--color-success)] in-data-[type=error]:[--toast-replay-color:var(--color-destructive)] in-data-[type=warning]:[--toast-replay-color:var(--color-warning)] in-data-[type=info]:[--toast-replay-color:var(--color-info)] in-data-[type=loading]:[--toast-replay-color:var(--color-muted-foreground)] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-expanded:bg-popover dark:bg-[color-mix(in_srgb,var(--popover),var(--color-black)_calc(6%*max(0,var(--toast-index,0))))] dark:data-expanded:bg-popover dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
                // Base positioning using data-position
                "data-[position*=right]:right-0 data-[position*=right]:left-auto",
                "data-[position*=left]:right-auto data-[position*=left]:left-0",
                "data-[position*=center]:right-0 data-[position*=center]:left-0",
                "data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-[50%_calc(50%-50%*min(var(--toast-index,0),1))]",
                "data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-[50%_calc(50%+50%*min(var(--toast-index,0),1))]",
                // Gap fill for hover
                "after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
                "data-[position*=top]:after:top-full",
                "data-[position*=bottom]:after:bottom-full",
                // Define some variables
                "[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
                // Define offset-y variable
                "data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
                "data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
                // Default state transform
                "data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
                "data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
                // Limited state
                "data-limited:opacity-0",
                // Expanded state
                "data-expanded:h-(--toast-height)",
                "data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
                // Starting and ending animations
                "data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
                "data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
                "data-ending-style:opacity-0",
                // Ending animations (direction-aware)
                "data-[position*=top]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(-100%-var(--toast-inset)))]",
                "data-[position*=bottom]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
                "data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
                "data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
                "data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
                "data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
                // Ending animations (expanded)
                "data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
                "data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
                "data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
                "data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%-var(--toast-inset)))]",
                upsertReplayClassName(toast)
              )}
              {...toastData?.rootProps}
              data-position={position}
              data-slot="toast-popup"
              swipeDirection={swipeDirection}
              toast={toast}
            >
              <Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-slow data-behind:not-data-expanded:pointer-events-none data-behind:opacity-0 data-expanded:opacity-100">
                <div className="flex min-w-0 flex-1 gap-2">
                  {Icon && (
                    <div
                      aria-hidden="true"
                      className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
                      data-slot="toast-icon"
                    >
                      <Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
                    </div>
                  )}

                  <div className="flex min-w-0 flex-1 flex-col gap-0.5">
                    <Toast.Title
                      className="line-clamp-2 break-words font-medium"
                      data-slot="toast-title"
                    />
                    <Toast.Description
                      className="break-words text-muted-foreground"
                      data-slot="toast-description"
                    />
                  </div>
                </div>
                {toast.actionProps && (
                  <Toast.Action
                    className={cn(
                      buttonVariants({ size: "xs" }),
                      "shrink-0 pointer-coarse:min-h-11"
                    )}
                    data-slot="toast-action"
                  >
                    {toast.actionProps.children}
                  </Toast.Action>
                )}
                {toast.timeout === 0 ? (
                  <ToastCloseButton label={closeLabel} />
                ) : null}
              </Toast.Content>
            </Toast.Root>
          )
        })}
      </Toast.Viewport>
    </Toast.Portal>
  )
}

function AnchoredToasts({
  portalProps,
  closeLabel,
}: {
  portalProps?: React.ComponentProps<typeof Toast.Portal>
  closeLabel: string
}): React.ReactElement {
  const { toasts } = Toast.useToastManager()

  return (
    <Toast.Portal data-slot="toast-portal-anchored" {...portalProps}>
      <Toast.Viewport
        className="outline-none"
        data-slot="toast-viewport-anchored"
      >
        {toasts.map((toast) => {
          const Icon = toast.type
            ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS]
            : null
          const toastData = toast.data as ToastData | undefined
          const tooltipStyle = toastData?.tooltipStyle ?? false
          const positionerProps = toast.positionerProps

          if (!positionerProps?.anchor) {
            return null
          }

          return (
            <Toast.Positioner
              key={toast.id}
              className="z-modal max-w-[min(--spacing(64),var(--available-width))]"
              data-slot="toast-positioner"
              sideOffset={positionerProps.sideOffset ?? 4}
              toast={toast}
            >
              <Toast.Root
                className={cn(
                  "group/toast relative text-balance border border-border bg-popover not-dark:bg-clip-padding text-popover-foreground text-xs transition-[scale,opacity] duration-fast ease-standard in-data-[type=success]:[--toast-replay-color:var(--color-success)] in-data-[type=error]:[--toast-replay-color:var(--color-destructive)] in-data-[type=warning]:[--toast-replay-color:var(--color-warning)] in-data-[type=info]:[--toast-replay-color:var(--color-info)] in-data-[type=loading]:[--toast-replay-color:var(--color-muted-foreground)] before:pointer-events-none before:absolute before:inset-0 before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
                  tooltipStyle
                    ? "rounded-md shadow-xs/5 before:rounded-[calc(var(--radius-md)-1px)]"
                    : "rounded-lg shadow-xs/5 before:rounded-[calc(var(--radius-lg)-1px)]",
                  upsertReplayClassName(toast)
                )}
                {...toastData?.rootProps}
                data-slot="toast-popup"
                toast={toast}
              >
                {tooltipStyle ? (
                  <Toast.Content className="pointer-events-auto flex items-center gap-1 px-2 py-1">
                    <Toast.Title data-slot="toast-title" />
                    {toast.timeout === 0 ? (
                      <ToastCloseButton label={closeLabel} />
                    ) : null}
                  </Toast.Content>
                ) : (
                  <Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm">
                    <div className="flex min-w-0 flex-1 gap-2">
                      {Icon && (
                        <div
                          aria-hidden="true"
                          className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
                          data-slot="toast-icon"
                        >
                          <Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
                        </div>
                      )}

                      <div className="flex min-w-0 flex-1 flex-col gap-0.5">
                        <Toast.Title
                          className="line-clamp-2 break-words font-medium"
                          data-slot="toast-title"
                        />
                        <Toast.Description
                          className="break-words text-muted-foreground"
                          data-slot="toast-description"
                        />
                      </div>
                    </div>
                    {toast.actionProps && (
                      <Toast.Action
                        className={cn(
                          buttonVariants({ size: "xs" }),
                          "shrink-0 pointer-coarse:min-h-11"
                        )}
                        data-slot="toast-action"
                      >
                        {toast.actionProps.children}
                      </Toast.Action>
                    )}
                    {toast.timeout === 0 ? (
                      <ToastCloseButton label={closeLabel} />
                    ) : null}
                  </Toast.Content>
                )}
              </Toast.Root>
            </Toast.Positioner>
          )
        })}
      </Toast.Viewport>
    </Toast.Portal>
  )
}

export const toastManager: ReturnType<typeof Toast.createToastManager> =
  Toast.createToastManager()

export const anchoredToastManager: ReturnType<
  typeof Toast.createToastManager
> = Toast.createToastManager()

export type ToastPosition =
  | "top-left"
  | "top-center"
  | "top-right"
  | "bottom-left"
  | "bottom-center"
  | "bottom-right"

/**
 * 视口与窗口边缘的间距(DF-11):
 * - number 按 px 处理;
 * - string 原样写入 `--toast-inset`,可传 `calc(env(safe-area-inset-bottom) + 1rem)`
 *   之类的安全区表达式。
 */
export type ToastOffset = number | string

export interface ToastProviderProps extends Toast.Provider.Props {
  position?: ToastPosition
  /** 视口内缩;缺省沿用 16px(sm 以上 32px) */
  offset?: ToastOffset
  /** Portal 挂载容器;缺省 document.body,可避开画布/状态栏所在的层叠上下文 */
  container?: React.ComponentProps<typeof Toast.Portal>["container"]
  portalProps?: React.ComponentProps<typeof Toast.Portal>
  /** 常驻 toast 关闭按钮的可访问名(默认「关闭」) */
  closeLabel?: string
}

export function ToastProvider({
  children,
  position = "top-right",
  offset,
  container,
  portalProps,
  closeLabel,
  ...props
}: ToastProviderProps): React.ReactElement {
  const resolvedCloseLabel = closeLabel ?? "关闭"
  return (
    <Toast.Provider toastManager={toastManager} {...props}>
      {children}
      <Toasts
        portalProps={portalProps}
        position={position}
        offset={offset}
        container={container}
        closeLabel={resolvedCloseLabel}
      />
    </Toast.Provider>
  )
}

export interface AnchoredToastProviderProps extends Toast.Provider.Props {
  portalProps?: React.ComponentProps<typeof Toast.Portal>
  /** 常驻 toast 关闭按钮的可访问名(默认「关闭」) */
  closeLabel?: string
}

export function AnchoredToastProvider({
  children,
  portalProps,
  closeLabel,
  ...props
}: AnchoredToastProviderProps): React.ReactElement {
  const resolvedCloseLabel = closeLabel ?? "关闭"
  return (
    <Toast.Provider toastManager={anchoredToastManager} {...props}>
      {children}
      <AnchoredToasts
        portalProps={portalProps}
        closeLabel={resolvedCloseLabel}
      />
    </Toast.Provider>
  )
}

/* ============================================
   sonner 兼容层(历史 API,2026-08 sonner → coss toast 迁移保留)
   toast.success/error/info/warning/loading/dismiss/promise 命令式签名不变,
   调用点只改 import 来源('sonner' → '../toast')。
   ============================================ */

export interface ExternalToast {
  description?: React.ReactNode
  /** 自动关闭延时 ms;Infinity 表示常驻 */
  duration?: number
  id?: string | number
  action?: { label: React.ReactNode; onClick?: () => void }
}

type ToastType = "success" | "error" | "info" | "warning" | "loading"

function enqueue(
  type: ToastType | undefined,
  message: React.ReactNode,
  opts?: ExternalToast
): string {
  return toastManager.add({
    id: opts?.id != null ? String(opts.id) : undefined,
    type,
    title: message,
    description: opts?.description,
    timeout: opts?.duration === Infinity ? 0 : opts?.duration,
    actionProps: opts?.action
      ? { children: opts.action.label, onClick: opts.action.onClick }
      : undefined,
  })
}

type ToastFn = {
  (message: React.ReactNode, opts?: ExternalToast): string
  success: (message: React.ReactNode, opts?: ExternalToast) => string
  error: (message: React.ReactNode, opts?: ExternalToast) => string
  info: (message: React.ReactNode, opts?: ExternalToast) => string
  warning: (message: React.ReactNode, opts?: ExternalToast) => string
  loading: (message: React.ReactNode, opts?: ExternalToast) => string
  dismiss: (id?: string | number) => void
  promise: <Value>(
    promiseValue: Promise<Value>,
    opts: {
      loading: string
      success: string | ((result: Value) => string)
      error: string | ((error: unknown) => string)
    }
  ) => Promise<Value>
}

const toast = ((message: React.ReactNode, opts?: ExternalToast) =>
  enqueue(undefined, message, opts)) as ToastFn

toast.success = (message, opts) => enqueue("success", message, opts)
toast.error = (message, opts) => enqueue("error", message, opts)
toast.info = (message, opts) => enqueue("info", message, opts)
toast.warning = (message, opts) => enqueue("warning", message, opts)
toast.loading = (message, opts) => enqueue("loading", message, opts)
toast.dismiss = (id) => toastManager.close(id != null ? String(id) : undefined)
toast.promise = <Value,>(
  promiseValue: Promise<Value>,
  opts: {
    loading: string
    success: string | ((result: Value) => string)
    error: string | ((error: unknown) => string)
  }
) =>
  toastManager.promise(promiseValue, {
    loading: { title: opts.loading, type: "loading" },
    success: (result) => ({
      title:
        typeof opts.success === "function" ? opts.success(result) : opts.success,
      type: "success",
    }),
    error: (error) => ({
      title: typeof opts.error === "function" ? opts.error(error) : opts.error,
      type: "error",
    }),
  })

export { toast, Toast as ToastPrimitive }

可访问性与 RTL

  • 键盘:交互件保留:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。
  • RTL:间距、对齐与方向性图标使用逻辑属性 (ms-* /text-start /rtl:-scale-x-100);通过 ThemeProvider 或I18nProvider 的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。
  • 文案:优先用组件labels /translate /translator props,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。
  • 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。

用法说明

全局轻提示,用 ToastProvider 包裹应用后通过 toast() 或 toastManager 触发;支持成功、错误与带操作提示。需避开底部状态栏/画布控件时给 ToastProvider 传 offset(number=px,或 calc(env(safe-area-inset-bottom)+…)),需要自定义层叠上下文时传 container。

避开状态栏 / 自定义容器(DF-11)

ToastProvider 新增两个可选 prop,默认行为不变:

prop类型说明
offsetnumber | string视口与窗口边缘的间距。number 按 px;string 原样写入 --toast-inset,可传安全区表达式
containerHTMLElement | ShadowRoot | RefObject | nullPortal 挂载容器,缺省 document.body
<ToastProvider
  position="bottom-right"
  offset="calc(env(safe-area-inset-bottom) + 4rem)"
>
  <App />
</ToastProvider>

底部状态栏/画布控件上方弹出时,用 offset 抬高安全距离;若应用已有自己的层叠上下文, 用 container 把 toast portal 挂到对应容器内。