显示通知,支持动作、定时关闭和屏幕阅读器播报。

toast 告诉某人发生了某件事,比如保存了一处更改或发送了一条消息,然后自行消失。它可以提供一个像 Undo 这样的动作,和先前的 toast 堆叠在一起,并在不取得焦点的情况下向屏幕阅读器播报。

控制台
import * as React from "react"
import {
  Toast,
  ToastAction,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [toast] = React.useState(() => createToaster())
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  return (
    <>
      <button
        onClick={() =>
          toast("Event created", {
            description: "Friday, June 12 at 10:00 AM",
            action: { label: "Undo", onAction: () => log("Event removed") },
          })
        }
      >
        Create Event
      </button>
      <ToastRegion toaster={toast}>
        {() => (
          <Toast>
            <div data-slot="stack">
              <ToastTitle />
              <ToastDescription />
            </div>
            <ToastAction data-variant="solid" />
          </Toast>
        )}
      </ToastRegion>
    </>
  )
}

export { Example }
按 Create Event。选择 Undo、把 toast 滑走,或者等它关闭。Undo 会记录 Event removed。

安装

npm install @ui-sdk/react @ui-sdk/core

组合

用下面的组合构建一个 ToastRegion:

ToastRegion
├── Toast
│   ├── ToastTitle
│   ├── ToastDescription
│   ├── ToastAction
│   └── ToastClose
└── Toast
    ├── ToastTitle
    └── ToastDescription

区域通过它的 children 函数,为队列中的每个 toast 渲染一个 Toast,最新的在前。toast 由标题命名,由描述说明。空的标题、描述和动作部件会显示 toast 数据中的文本,所以区域的渲染函数通常就是同样那几个部件。

用法

导入各个部件并把它们组合起来,然后在动作完成时调用 toast():

import {
  Toast,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  toast,
} from "@ui-sdk/react/toast"

function Example() {
  return (
    <>
      <button
        type="button"
        onClick={() =>
          toast("Event created", { description: "Friday at 10:00 AM" })
        }
      >
        Create Event
      </button>
      <ToastRegion>
        {() => (
          <Toast>
            <ToastTitle />
            <ToastDescription />
          </Toast>
        )}
      </ToastRegion>
    </>
  )
}

export { Example }

toast() 可以在任何地方使用,不只是组件里,并返回 toast 的 id。在应用的根节点附近放置一次区域。没有 children 时,它用无样式的部件渲染每个 toast 的标题、描述、动作和取消按钮。

下面的示例各自调用 createToaster() 得到自己的队列,并把它作为 toaster 传给它们的区域,所以它们的 toast 不会混在一起。

类型

toast.success、.info、.warning、.error 和 .loading 设置 toast 的类型,toast 通过 data-type 暴露它,供图标或颜色使用。错误会立即播报,其他类型会等到停顿之后再播报;设置 priority 可以改变这一点。加载中的 toast 会一直保留,直到被更新或关闭。

import * as React from "react"
import {
  Toast,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"
import {
  CircleCheckIcon,
  InfoIcon,
  LoaderCircleIcon,
  OctagonXIcon,
  TriangleAlertIcon,
} from "lucide-react"

function upload() {
  return new Promise((resolve) => setTimeout(resolve, 2000))
}

function Example() {
  const [toast] = React.useState(() => createToaster())
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  return (
    <>
      <div data-slot="row">
        <button onClick={() => toast("Event created")}>Default</button>
        <button onClick={() => toast.success("Changes saved")}>Success</button>
        <button onClick={() => toast.info("A new version is available")}>
          Info
        </button>
        <button onClick={() => toast.warning("Storage is almost full")}>
          Warning
        </button>
        <button onClick={() => toast.error("Couldn't save changes")}>
          Error
        </button>
        <button
          onClick={() =>
            toast.promise(upload, {
              loading: "Uploading photos…",
              success: "Photos uploaded",
              error: "Upload failed",
            })
          }
        >
          Loading
        </button>
      </div>
      <ToastRegion toaster={toast}>
        {() => (
          <Toast>
            <CircleCheckIcon data-show="success" aria-hidden="true" />
            <InfoIcon data-show="info" aria-hidden="true" />
            <TriangleAlertIcon data-show="warning" aria-hidden="true" />
            <OctagonXIcon data-show="error" aria-hidden="true" />
            <LoaderCircleIcon data-show="loading" aria-hidden="true" />
            <ToastTitle />
          </Toast>
        )}
      </ToastRegion>
    </>
  )
}

export { Example }
选择一种类型。每个 toast 显示它类型的图标,Loading 在完成时会变成 Photos uploaded。

位置

把区域的 side 设为 top 或 bottom,把 align 设为 start、center 或 end。start 和 end 跟随书写方向。toast 可以朝它所在的那一侧滑动,如果不是居中,还可以朝它对齐的那一端滑动。

import * as React from "react"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/react/select"
import {
  Toast,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"
import { CheckIcon, ChevronDownIcon } from "lucide-react"

const sides = [
  { value: "top", label: "Top" },
  { value: "bottom", label: "Bottom" },
]
const aligns = [
  { value: "start", label: "Start" },
  { value: "center", label: "Center" },
  { value: "end", label: "End" },
]
type Side = "top" | "bottom"
type Align = "start" | "center" | "end"

function Example() {
  const [toast] = React.useState(() => createToaster())
  const [side, setSide] = React.useState<Side>("bottom")
  const [align, setAlign] = React.useState<Align>("end")
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <Select
          items={sides}
          value={side}
          onValueChange={(next) => next && setSide(next as Side)}
        >
          <SelectLabel>Side</SelectLabel>
          <SelectTrigger>
            <SelectValue />
            <ChevronDownIcon aria-hidden="true" />
          </SelectTrigger>
          <SelectContent>
            {sides.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
                <SelectItemIndicator>
                  <CheckIcon aria-hidden="true" />
                </SelectItemIndicator>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select
          items={aligns}
          value={align}
          onValueChange={(next) => next && setAlign(next as Align)}
        >
          <SelectLabel>Align</SelectLabel>
          <SelectTrigger>
            <SelectValue />
            <ChevronDownIcon aria-hidden="true" />
          </SelectTrigger>
          <SelectContent>
            {aligns.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
                <SelectItemIndicator>
                  <CheckIcon aria-hidden="true" />
                </SelectItemIndicator>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <button
        onClick={() =>
          toast("Event created", { description: "Friday, June 12 at 10:00 AM" })
        }
      >
        Create Event
      </button>
      <ToastRegion toaster={toast} side={side} align={align}>
        {() => (
          <Toast>
            <div data-slot="stack">
              <ToastTitle />
              <ToastDescription />
            </div>
          </Toast>
        )}
      </ToastRegion>
    </div>
  )
}

export { Example }
选择一个方向和对齐方式,然后按 Create Event,看看页面那个边缘出现的 toast。

动作与取消

添加一个 action,比如 Undo,以及一个关闭 toast 的 cancel 按钮。它们的回调可以更新你的应用。onDismiss 告诉你 toast 为什么关闭,details.cancel() 让它保持打开;被取消的超时会重新开始倒计时。

控制台
import * as React from "react"
import {
  Toast,
  ToastAction,
  ToastClose,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [toast] = React.useState(() => createToaster())
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  return (
    <>
      <button
        onClick={() =>
          toast("Message archived", {
            action: { label: "Undo", onAction: () => log("Message restored") },
            cancel: { label: "Dismiss", onCancel: () => log("Kept archived") },
            onDismiss: ({ reason }) => log(`Closed (${reason})`),
          })
        }
      >
        Archive Message
      </button>
      <ToastRegion toaster={toast}>
        {(item) => (
          <Toast>
            <ToastTitle />
            {item.cancel && (
              <ToastClose action={item.cancel.onCancel}>
                {item.cancel.label}
              </ToastClose>
            )}
            <ToastAction data-variant="solid" />
          </Toast>
        )}
      </ToastRegion>
    </>
  )
}

export { Example }
按 Archive Message,然后选择 Undo 或 Dismiss、把 toast 滑走,或者让它超时。控制台会记录它关闭的原因。

给动作一个 href,把它渲染成链接。它保留正常的链接行为,包括在新标签页中打开。

import * as React from "react"
import {
  Toast,
  ToastAction,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"

function Example() {
  const [toast] = React.useState(() => createToaster())
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  return (
    <>
      <button
        onClick={() =>
          toast("Invoice sent", {
            description: "Hollis Grant · $240.00",
            action: { label: "View", href: "#" },
          })
        }
      >
        Send Invoice
      </button>
      <ToastRegion toaster={toast}>
        {() => (
          <Toast>
            <div data-slot="stack">
              <ToastTitle />
              <ToastDescription />
            </div>
            <ToastAction data-variant="solid" />
          </Toast>
        )}
      </ToastRegion>
    </>
  )
}

export { Example }
按 Send Invoice,然后打开 toast 里的 View。

Promise

toast.promise() 先显示一个加载中的 toast,然后在 promise 兑现或拒绝时更新同一个 toast。每条消息可以是字符串、带描述或动作的选项,或者结果的函数。加载期间被关闭的 toast 会保持关闭。

import * as React from "react"
import {
  Toast,
  ToastAction,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"

function Example() {
  const [toast] = React.useState(() => createToaster())
  const attempts = React.useRef(0)
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  function save() {
    const succeeds = ++attempts.current % 2 === 1
    return new Promise<void>((resolve, reject) =>
      setTimeout(
        () => (succeeds ? resolve() : reject(new Error("Network error"))),
        1500
      )
    )
  }

  function saveChanges() {
    toast.promise(save, {
      loading: "Saving changes…",
      success: "Changes saved",
      error: {
        title: "Couldn't save changes",
        description: "Check your connection and try again.",
        action: { label: "Retry", onAction: saveChanges },
      },
    })
  }

  return (
    <>
      <button onClick={saveChanges}>Save Changes</button>
      <ToastRegion toaster={toast}>
        {() => (
          <Toast>
            <div data-slot="stack">
              <ToastTitle />
              <ToastDescription />
            </div>
            <ToastAction data-variant="solid" />
          </Toast>
        )}
      </ToastRegion>
    </>
  )
}

export { Example }
按 Save Changes,看着 Saving changes 变成 Changes saved。再按一次查看错误,然后选择 Retry。

堆叠

maxVisible 限制一次显示多少个 toast,默认三个;其余的留在队列里等待,显示时计时器才开始。指针或焦点在堆叠中时,堆叠会展开。设置 expanded 让它保持展开。样式展示了布局这个堆叠的 CSS。

import * as React from "react"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/react/checkbox"
import {
  Toast,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"
import { CheckIcon } from "lucide-react"

const notifications = [
  { title: "Event created", description: "Friday, June 12 at 10:00 AM" },
  { title: "Message sent" },
  {
    title: "Hollis Grant joined",
    description: "They can now edit the Launch plan and see its comments.",
  },
  { title: "Changes saved" },
  { title: "Invoice sent", description: "Inès Moreau · $240.00" },
  { title: "Photos uploaded", description: "12 photos added to Summer trip" },
]

function Example() {
  const [toast] = React.useState(() => createToaster())
  const [expanded, setExpanded] = React.useState(false)
  const count = React.useRef(0)
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <Checkbox
            checked={expanded}
            onCheckedChange={(next) => setExpanded(next === true)}
          >
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          Always expanded
        </label>
      </div>
      <button
        onClick={() =>
          toast(notifications[count.current++ % notifications.length])
        }
      >
        Add Toast
      </button>
      <ToastRegion toaster={toast} maxVisible={4} expanded={expanded}>
        {() => (
          <Toast>
            <div data-slot="stack">
              <ToastTitle />
              <ToastDescription />
            </div>
          </Toast>
        )}
      </ToastRegion>
    </div>
  )
}

export { Example }
多按几次 Add Toast,然后悬停堆叠把它展开。超过四个 toast 后,其余的会等待轮到自己。勾选 Always expanded 让它保持展开。

时长

duration 以毫秒为单位,可以设在 toaster 上,也可以设在单个 toast 上;用 Infinity 让 toast 一直保留到被关闭。默认是五秒。指针或焦点在区域中时,以及页面隐藏或窗口不活跃时,计时器会暂停。

import * as React from "react"
import {
  Toast,
  ToastClose,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"

function Example() {
  const [toast] = React.useState(() => createToaster())
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  return (
    <>
      <div data-slot="row">
        <button onClick={() => toast("Link copied", { duration: 1000 })}>
          1 Second
        </button>
        <button onClick={() => toast("Changes saved")}>5 Seconds</button>
        <button
          onClick={() =>
            toast("Your session expires in 5 minutes", {
              duration: Infinity,
              dismissible: false,
              cancel: { label: "Got It" },
            })
          }
        >
          Until Dismissed
        </button>
      </div>
      <ToastRegion toaster={toast}>
        {(item) => (
          <Toast>
            <ToastTitle />
            {item.cancel && (
              <ToastClose data-variant="solid" action={item.cancel.onCancel}>
                {item.cancel.label}
              </ToastClose>
            )}
          </Toast>
        )}
      </ToastRegion>
    </>
  )
}

export { Example }
按每个按钮。悬停 toast 可以暂停它的计时器。会话 toast 会一直保留,直到你按 Got It。

更新与关闭

保留 toast() 返回的 id,用来更新或关闭那个 toast,或者传入你自己的 id。toast.update() 返回 toast 是否还在,不带 id 的 toast.dismiss() 会关闭每一个 toast。

控制台
import * as React from "react"
import {
  Toast,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"
import { CircleCheckIcon, LoaderCircleIcon } from "lucide-react"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [toast] = React.useState(() => createToaster())
  const timer = React.useRef<ReturnType<typeof setInterval> | undefined>(
    undefined
  )
  React.useEffect(
    () => () => {
      clearInterval(timer.current)
      toast.dismiss()
    },
    [toast]
  )

  function upload() {
    clearInterval(timer.current)
    const id = toast.loading("Uploading report.pdf… 0%", { id: "upload" })
    let progress = 0
    timer.current = setInterval(() => {
      progress += 20
      const done = progress >= 100
      const open = toast.update(
        id,
        done
          ? { title: "Report uploaded", type: "success" }
          : { title: `Uploading report.pdf… ${progress}%` }
      )
      if (!open) {
        log("Upload canceled")
      }
      if (done || !open) {
        clearInterval(timer.current)
      }
    }, 700)
  }

  return (
    <>
      <div data-slot="row">
        <button onClick={upload}>Upload Report</button>
        <button onClick={() => toast.dismiss("upload")}>Cancel Upload</button>
        <button onClick={() => toast.dismiss()}>Dismiss All</button>
      </div>
      <ToastRegion toaster={toast}>
        {() => (
          <Toast>
            <CircleCheckIcon data-show="success" aria-hidden="true" />
            <LoaderCircleIcon data-show="loading" aria-hidden="true" />
            <ToastTitle />
          </Toast>
        )}
      </ToastRegion>
    </>
  )
}

export { Example }
按 Upload Report,看着一个 toast 一路计数到 Report uploaded。Cancel Upload 会提前关闭它,Dismiss All 会清除每一个 toast。

异步动作

从动作返回一个 promise,让 toast 在它运行期间保持打开。动作的状态在运行期间带有 pending,失败时带有 error,所以按钮可以显示 Restoring… 或提供重试,在动作结束之前按压会被忽略。await 之后所做的变更见 Button。

控制台
import * as React from "react"
import {
  Toast,
  ToastAction,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"
import { useLog } from "./log"

function restore() {
  return new Promise((resolve) => setTimeout(resolve, 1500))
}

function Example() {
  const log = useLog()
  const [toast] = React.useState(() => createToaster({ duration: 6000 }))
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  return (
    <>
      <button
        onClick={() =>
          toast("File deleted", {
            description: "Q3 report.pdf",
            action: {
              label: "Undo",
              onAction: async () => {
                await restore()
                log("Q3 report.pdf restored")
              },
            },
          })
        }
      >
        Delete File
      </button>
      <ToastRegion toaster={toast}>
        {() => (
          <Toast>
            <div data-slot="stack">
              <ToastTitle />
              <ToastDescription />
            </div>
            <ToastAction data-variant="solid">
              {(state) =>
                state.pending ? "Restoring…" : state.error ? "Retry" : "Undo"
              }
            </ToastAction>
          </Toast>
        )}
      </ToastRegion>
    </>
  )
}

export { Example }
按 Delete File,然后按 Undo。按钮会显示 Restoring…,直到恢复完成,然后 toast 关闭。

键盘快捷键

F6 把焦点移到最新的 toast,再移回来。设置区域的 shortcut 可以使用其他按键,设为 null 则关闭它。区域通过 aria-keyshortcuts 声明它。

控制台
import * as React from "react"
import {
  Toast,
  ToastAction,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [toast] = React.useState(() => createToaster({ duration: 10000 }))
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  return (
    <>
      <button
        onClick={() =>
          toast("Message sent", {
            action: { label: "Undo", onAction: () => log("Message unsent") },
          })
        }
      >
        Send Message
      </button>
      <ToastRegion toaster={toast} shortcut="alt+t" aria-label="Alerts">
        {() => (
          <Toast>
            <ToastTitle />
            <ToastAction data-variant="solid" />
          </Toast>
        )}
      </ToastRegion>
    </>
  )
}

export { Example }
按 Send Message,然后按 Alt+T(Mac 上是 Option+T)聚焦 toast。按 Escape 关闭它,或者再按一次 Alt+T 返回。

浮层宿主与确认框

除了放置区域,也可以在应用的根节点附近渲染一次 OverlayHost。它渲染 toaster 的区域,使用你给它的 toast.children,并把 confirm() 问题渲染成警告对话框。对于同一个 toaster,你自己放置的区域会取代宿主。

要给问题设置样式,用 confirm 控制器渲染一个 AlertDialog,并从它内容的 payload 读取问题。Alert Dialog更详细地介绍了 createConfirm()。

import * as React from "react"
import {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogTitle,
  createConfirm,
  type ConfirmOptions,
} from "@ui-sdk/react/alert-dialog"
import { OverlayHost, createOverlays } from "@ui-sdk/react/overlays"
import { Toast, ToastTitle, createToaster } from "@ui-sdk/react/toast"
import { CircleCheckIcon } from "lucide-react"

function Example() {
  const [overlays] = React.useState(() => createOverlays())
  const [toast] = React.useState(() => createToaster({ overlays }))
  const [confirm] = React.useState(() => createConfirm({ overlays }))
  const [projects, setProjects] = React.useState(["Acme", "Globex", "Initech"])
  const reset = React.useRef<HTMLButtonElement>(null)
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  async function remove(name: string, button: HTMLButtonElement) {
    const confirmed = await confirm({
      title: `Delete ${name}?`,
      description:
        "The project and its files will be deleted for everyone on your team.",
      confirmLabel: "Delete",
      cancelLabel: "Cancel",
    })
    if (!confirmed) {
      return
    }
    const row = button.closest("li")
    const next = (
      row?.nextElementSibling ?? row?.previousElementSibling
    )?.querySelector("button")
    ;(next ?? reset.current)?.focus()
    setProjects((list) => list.filter((project) => project !== name))
    toast.success(`${name} deleted`, { priority: "assertive" })
  }

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button
          ref={reset}
          type="button"
          onClick={() => setProjects(["Acme", "Globex", "Initech"])}
        >
          Reset Projects
        </button>
      </div>
      <ul data-slot="list" aria-label="Projects">
        {projects.map((name) => (
          <li data-slot="row" key={name}>
            {name}
            <button
              type="button"
              data-size="sm"
              aria-label={`Delete ${name}`}
              onClick={(event) => remove(name, event.currentTarget)}
            >
              Delete
            </button>
          </li>
        ))}
        {projects.length === 0 && (
          <li data-slot="row">All projects deleted.</li>
        )}
      </ul>
      <OverlayHost
        overlays={overlays}
        toast={{
          children: () => (
            <Toast>
              <CircleCheckIcon data-show="success" aria-hidden="true" />
              <ToastTitle />
            </Toast>
          ),
        }}
      />
      <AlertDialog controller={confirm.controller}>
        <AlertDialogBackdrop />
        <AlertDialogContent<ConfirmOptions>>
          {(state) => (
            <>
              <div data-slot="stack">
                <AlertDialogTitle>{state.payload?.title}</AlertDialogTitle>
                <AlertDialogDescription>
                  {state.payload?.description}
                </AlertDialogDescription>
              </div>
              <div data-slot="row">
                <AlertDialogClose>
                  {state.payload?.cancelLabel}
                </AlertDialogClose>
                <AlertDialogClose data-variant="solid" value="confirm">
                  {state.payload?.confirmLabel}
                </AlertDialogClose>
              </div>
            </>
          )}
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}

export { Example }
按某个项目上的 Delete 并确认。那一行会消失,并有一个 toast 说明这一点。Reset Projects 会把它们带回来。

自定义渲染

把 toast 需要的其他内容放在 data 里传入,并从区域 children 函数收到的 toast 中读取它。每个部件也接受 render;这个示例自己渲染每个 toast 的 li,并把折叠堆叠后面隐藏的那些设为不可交互(inert)。

控制台
import * as React from "react"
import {
  Toast,
  ToastAction,
  ToastClose,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/react/toast"
import { XIcon } from "lucide-react"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [toast] = React.useState(() => createToaster())
  React.useEffect(
    () => () => {
      toast.dismiss()
    },
    [toast]
  )

  return (
    <>
      <button
        onClick={() =>
          toast({
            title: "Hollis Grant",
            description: "Can you review the draft?",
            data: { initials: "HG" },
            action: {
              label: "Reply",
              onAction: () => log("Replying to Hollis Grant"),
            },
          })
        }
      >
        New Message
      </button>
      <ToastRegion toaster={toast} aria-label="Messages">
        {(item) => (
          <Toast
            render={(props, state) => (
              <li
                {...props}
                inert={
                  state.leaving ||
                  (!state.expanded && state.index > 0) ||
                  undefined
                }
              />
            )}
          >
            <span data-slot="media">
              {(item.data as { initials: string }).initials}
            </span>
            <div data-slot="stack">
              <ToastTitle />
              <ToastDescription />
            </div>
            <ToastAction data-variant="solid" />
            <ToastClose aria-label="Close">
              <XIcon aria-hidden="true" />
            </ToastClose>
          </Toast>
        )}
      </ToastRegion>
    </>
  )
}

export { Example }
按 New Message,显示一个带有 Hollis Grant 首字母的 toast。选择 Reply 或关闭它。

样式

toast 没有样式,区域和它的 toast 带有为堆叠做动画所需的东西:

  • 堆叠。 区域会设置 --toast-front-height,即最新 toast 的高度,以及把它们全部相加的 --toast-stack-height。每个 toast 会得到 --toast-index,最新的是 0,--toast-offset,即它前面那些 toast 的高度,以及它自己的高度 --toast-height。在区域里绝对定位这些 toast,并设置 height: var(--toast-height),让高度的变化产生动画。
  • 折叠与展开。 data-front 标记最新的 toast。堆叠折叠时,把位于它后面的 toast 裁剪到 --toast-front-height,并按它们的索引露出一部分。堆叠展开时,区域和它的 toast 会得到 data-expanded;按 --toast-offset 移动每个 toast。
  • 滑动。 toast 被滑动时会得到 data-swiping,--toast-swipe-x 和 --toast-swipe-y 保存它移动了多远。用这两个变量平移它,并关闭过渡。滑动关闭它时,data-swipe-direction 说明方向,好让它朝那个方向离开。从可选择的文本上开始的鼠标拖动会选中文本,所以在 toast 上设置 user-select: none,就能从任何位置滑动它。
  • 入场与退场。 toast 在第一帧带有 data-starting-style,离开期间带有 data-ending-style,并保持挂载,直到它的过渡结束。

页面底部的一个堆叠,用纯 CSS 写成:

[data-slot="toast-region"] {
  width: 356px;
  height: var(--toast-front-height);
}

[data-slot="toast-region"][data-expanded] {
  height: calc(var(--toast-stack-height) + (var(--toast-count) - 1) * 12px);
}

[data-slot="toast"] {
  --y: calc(var(--toast-index) * -12px);
  position: absolute;
  inset-inline: 0;
  bottom: 0;
  z-index: calc(100 - var(--toast-index));
  overflow: hidden;
  height: var(--toast-height);
  translate: var(--toast-swipe-x, 0px)
    calc(var(--y) + var(--toast-swipe-y, 0px));
  scale: calc(1 - var(--toast-index) * 0.05);
  transition-property: translate, scale, opacity, height;
  transition-duration: 400ms;
  user-select: none;
}

[data-slot="toast"]:not([data-front], [data-expanded]) {
  height: var(--toast-front-height);
}

[data-slot="toast"][data-expanded] {
  --y: calc(-1 * (var(--toast-offset) + var(--toast-index) * 12px));
  scale: 1;
}

[data-slot="toast"][data-starting-style] {
  transition: none;
}

[data-slot="toast"][data-starting-style][data-front] {
  --y: 100%;
}

[data-slot="toast"]:is(
  [data-starting-style]:not([data-front]),
  [data-ending-style]
) {
  opacity: 0;
}

[data-slot="toast"][data-swiping] {
  transition: none;
}

@media (prefers-reduced-motion: reduce) {
  [data-slot="toast"] {
    transition-property: opacity;
  }
}

每个部件都有一个 data-slot,比如 toast,它的状态属性列在数据属性下。

ToastRegion

变量内容
--toast-front-heightThe newest toast's height. Clip the toasts behind it to it in a collapsed stack.
--toast-stack-heightThe toasts' heights added up, for the height of an expanded stack.
--toast-countHow many toasts show.
--keyboard-insetHow many pixels of the page the on-screen keyboard covers, 0 without one.
--visual-viewport-widthThe width of the part of the page you can see.
--visual-viewport-heightThe height of the part of the page you can see, above the keyboard.
--visual-viewport-topHow far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up.

Toast

变量内容
--toast-indexThe toast's place in the stack, 0 for the newest. A closing toast keeps its place.
--toast-offsetThe height of the toasts in front of this one, in pixels. Add gaps with --toast-index to place an expanded stack.
--toast-heightThe toast's own height with its content laid out freely, whatever height it's given. Set it as the height to animate the stack.
--toast-swipe-xHow far a swipe moved the toast sideways, in pixels. Translate the toast by it.
--toast-swipe-yHow far a swipe moved the toast up or down, in pixels.

数据属性

ToastTitle 和 ToastDescription 没有状态属性。ToastClose 的 action 返回的 Promise 运行期间,它会像 ToastAction 一样得到 data-pending。

ToastRegion

[data-slot="toast-region"]

属性含义
data-sidetopbottomThe edge of the viewport the region sits on.
data-alignstartcenterendWhere along that edge.
data-expandedPresent while the stack is expanded: hovered, focused, or always with expanded.
data-keyboardPresent on the region while the on-screen keyboard covers part of the page.

Toast

[data-slot="toast"]

属性含义
data-typedefaultsuccesserrorinfowarningloadingWhat the toast is about.
data-frontPresent on the newest toast, in front of a collapsed stack. A closing toast keeps it while it animates out.
data-expandedPresent while the stack is expanded: hovered, focused, or always with expanded.
data-starting-stylePresent for a toast's first frame. Style the state you animate from.
data-ending-stylePresent while a toast animates out. Style the state you animate to.

ToastAction

[data-slot="toast-action"]

属性含义
data-pendingPresent on an action or close button while its handler's Promise runs.

API 参考

Toast

id?string
Reuses a toast: a toast with this id that's still showing is updated instead of added again.
title?Content
The main message.
description?Content
More detail, under the title.
type?ToastType
What it's about, for styling through data-type, and for how it's announced.
duration?number
How long it shows, in ms, while nothing pauses it. Infinity keeps it until dismissed.
priority?"assertive" | "polite"
How screen readers announce it: "polite" waits for a pause, "assertive" interrupts.
action?ToastAction<Content>
A button that does something, like Undo.
cancel?ToastCancel<Content>
A button that dismisses it, like Cancel.
dismissible?boolean
Whether the user can dismiss it: swiping, Escape and Close parts. Timers and dismiss() still close it.
data?unknown
Anything else, for your own rendering, like an avatar.
onDismiss?((details: ToastDismissDetails) => void)
Runs when it closes, with why. Calling details.cancel() keeps it.

toast(message, options) 和 toast(options) 返回 toast 的 id。toast.success、.info、.warning、.error 和 .loading 设置类型。toast.promise(promise, { loading, success, error }) 也返回 id,toast.update(id, options) 返回 toast 是否还在。toast.dismiss(id) 关闭一个,toast.dismiss() 关闭每一个。

动作

labelContent
The button's text.
onAction?((event: Event | undefined, details: ToastActionDetails) => unknown)
Runs when it's pressed. A returned Promise marks the action pending, then dismisses the toast once it resolves. A rejection keeps the toast. details.source says how it was pressed, for changes made after an await.
href?string
Makes the action a link.
dismiss?boolean
Whether pressing it dismisses the toast.
labelContent
The button's text.
onCancel?((event: Event | undefined, details: ToastActionDetails) => void)
Runs when it's pressed, before the toast closes. details.source says how it was pressed.

ToastRegion

toaster?Toaster<any>
The queue it shows. A second toaster, from createToaster(), gives a second region its own toasts.
side?"bottom" | "top"
The edge of the viewport it sits on. Swiping toward it dismisses a toast.
align?"center" | "end" | "start"
Where along that edge. "start" and "end" follow the writing direction, and swiping toward them dismisses too.
maxVisible?number
How many toasts show at once. Older ones wait, with their timers stopped, until there's room.
expanded?boolean
Whether the stack is always expanded. Otherwise it expands while the pointer or focus is in it.
shortcut?string | null
The key that moves focus into the region and back, like "F6" or "alt+t". null turns it off.
pendingAnnouncement?string
What screen readers hear once a toast's action or close button has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.
debug?boolean
Logs every state change with its reason to the console, in development builds.

ToastAction

onAction?((event: Event | undefined, details: ToastActionDetails) => unknown)
Runs when it's pressed, instead of the toast's own action.onAction. A returned Promise marks it pending. details.source says how it was pressed, for changes made after an await.
dismiss?boolean
Whether pressing it dismisses the toast.

ToastClose

action?((event: Event | undefined, details: ToastActionDetails) => unknown)
Runs before the toast closes. A returned Promise keeps it open and the button pending until it settles. details.source says how it was pressed, for changes made after an await.

Confirm

titlestring
The question, like "Delete this project?".
description?string
What agreeing does.
confirmLabel?string
The agreeing button's text.
cancelLabel?string
The other button's text.

状态

ToastRegion:

side"top" | "bottom"
The edge it sits on.
align"start" | "center" | "end"
Where along that edge.
expandedboolean
Whether the stack is expanded.
toastsreadonly ToastItem<unknown>[]
The toasts to render, newest first, including ones animating out.

Toast:

typeToastType
What it's about.
indexnumber
Its place in the stack, 0 for the newest.
frontboolean
Whether it's the newest, on top of a collapsed stack. A closing toast keeps it.
expandedboolean
Whether the stack is expanded.
leavingboolean
Whether it's animating out.

ToastAction 和 ToastClose:

pendingboolean
Whether a Promise its handler returned is still running.
errorunknown
Why its handler failed, until it's pressed again.

原因

timeoutnone
A duration ran out, like a toast's, or a rotating carousel's interval.
close-pressMouseEvent | KeyboardEvent | SubmitEvent
A Close part was pressed, or a form with method="dialog" was submitted.
swipeTouchEvent | PointerEvent
A swipe gesture: a finger, mouse or pen dragged it.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
actionMouseEvent | KeyboardEvent
A Close part's action finished.
imperativenone
A controller or api call.

无障碍

toast 通过共享的实时区域(live region)播报,每个只播报一次,而不把可见区域本身变成实时区域:默认礼貌播报,错误时即时(assertive)播报。区域里有 toast 时,它是一个名为 Notifications 的地标;设置 aria-label 可以用页面语言为它命名。让消息保持简短,对于必须一直可用的消息,使用 duration: Infinity。

键盘

F6 或区域的 shortcut 把焦点移到最新的 toast,再次按压会把焦点送回它来的地方。Tab 在 toast 和它们的按钮之间移动,越过最后一个再按 Tab 也会回到原处。Escape 关闭当前聚焦的 toast;焦点随后移到下一个 toast,如果已是最后一个,则回到它来的地方。模态对话框打开时区域仍然可达,焦点在内部时它的计时器会暂停。

经过测试的行为

下面每一行都是一个自动化测试。

Showing
  • A toast shows its title, description and action in the Notifications region.
  • Newer toasts come first.
  • The newest toast is marked as the front one.
  • Each toast says what it's about through data-type.
  • The region sits on its side and alignment.
  • It shows above everything, in the top layer.
  • A promise toast loads, then shows the result.
  • A toast with an id that's showing is updated in place.
Closing
  • A toast closes after its duration.
  • Infinity keeps it until it's dismissed.
  • The Dismiss button closes it.
  • The action runs and closes it.
  • Escape on a focused toast closes it.
  • A closing toast stays while it animates out.
  • A toast that can't be dismissed ignores Escape.
Timers
  • Hovering the region pauses its timers, and leaving resumes them.
  • Focus in the region pauses its timers.
Keyboard
  • F6 moves focus to the newest toast, and again back where it was.
  • The shortcut is configurable.
  • The region names its shortcut.
  • When the focused toast closes, focus goes to the next one, then back where it was.
Stacking
  • Only maxVisible toasts show; the rest wait for room.
  • The stack expands while hovered or focused.
  • Expanded keeps the stack expanded.
  • Toasts measure their heights and offsets for the stack.
  • A toast measures its content's height, whatever height it's given.
  • A toast given its measured height animates to a new one when its content changes.
  • A toast measures again when a child, its class or its padding changes.
  • A toast closing from the front stays in front while it animates out.
Swiping
  • Swiping toward the region's side dismisses.
  • Swiping toward the aligned edge dismisses too.
  • A short swipe snaps back.
  • Swiping away from the side never dismisses.
  • A toast that can't be dismissed doesn't swipe.
Over a modal dialog
  • A toast shown from a modal dialog is visible, usable and above it.
  • A toast stays above a dialog opened after it, and leaves a page's own popover alone.
Updates after closing
  • A promise toast dismissed while loading stays closed.
  • An update after a toast closed never brings it back.
More pausing and keys
  • The window losing focus pauses timers, and getting it back resumes them.
  • F6 does nothing while there are no toasts, so the browser keeps it.
  • A toast on the top edge swipes up, and a swipe down snaps back.

运行于 React、Vue 和 web components。

还测试了:

Enhancements
  • Update() says whether the toast was still there.
  • A toast beyond maxVisible never expires unseen.
  • There's no empty Notifications landmark.
  • Focus never falls to the page when a toast focused by the mouse closes.
  • A pending action shows it and holds the toast open until it settles.
Pausing
  • A hidden page pauses timers.
  • Pause reasons hold separately: getting the window back doesn't resume while focus is in the region.
Announcements
  • The live regions exist before the first toast.
  • A toast is announced politely, with its title and description.
  • An error is announced assertively.
  • Toasts that arrive together are announced together.
  • Text that already ends a sentence gets no second stop.
  • The visible region isn't a live region, so nothing is read twice.
The shortcut
  • F6 works from a text field and types nothing.
  • A shortcut of null turns it off.
  • Tab past the last toast goes back where F6 came from.
Over modal dialogs
  • F6 reaches the toasts from inside a modal dialog, and goes back into it.
  • Escape on a toast closes the toast, not the dialog beneath.
  • A dialog opened after a toast doesn't cover it, and pressing it doesn't close the dialog.
Swiping
  • Dragging across a toast's text with a mouse selects it instead of dismissing.

运行于 React、Vue 和 web components。

在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器记录:

  • Announcements while reaching a toast with F6 and leaving it.

运行于 React、Vue 和 web components。