# Toast

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

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

```ts title="demo.ts"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"
import { log } from "./log"

function mount(root: HTMLElement) {
  const toast = createToaster()
  root.innerHTML = `
    <button>Create Event</button>
    <ui-toast-region>
      <template>
        <ui-toast>
          <div data-slot="stack">
            <ui-toast-title></ui-toast-title>
            <ui-toast-description></ui-toast-description>
          </div>
          <ui-toast-action><button data-variant="solid"></button></ui-toast-action>
        </ui-toast>
      </template>
    </ui-toast-region>
  `
  root.querySelector("ui-toast-region")!.toaster = toast
  root.querySelector("button")!.addEventListener("click", () =>
    toast("Event created", {
      description: "Friday, June 12 at 10:00 AM",
      action: { label: "Undo", onAction: () => log(root, "Event removed") },
    })
  )
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

按 Create Event。选择 Undo、把 toast 滑走，或者等它关闭。Undo 会记录 Event removed。

## 安装
```bash
npm install @ui-sdk/web @ui-sdk/core
```

导入组件来注册它的元素。这个导入在服务端是安全的。

```ts
import "@ui-sdk/web/toast"
```

## 组合
用下面的组合构建一个 `ui-toast-region`：

```text
ui-toast-region
└── template
    └── ui-toast
        ├── ui-toast-title
        ├── ui-toast-description
        ├── ui-toast-action
        │   └── button
        └── ui-toast-close
            └── button
```

区域为队列中的每个 toast 克隆它 `template` 里的 `ui-toast`，最新的在前。toast 由标题命名，由描述说明。空的标题、描述和动作部件会显示 toast 数据中的文本，所以区域的模板通常就是同样那几个部件。空的 `ui-toast-close` 显示 toast 的取消按钮并运行它的 `onCancel`，toast 没有取消按钮时隐藏。由 `aria-label`、`aria-labelledby` 或 `title` 命名的关闭按钮，比如用 CSS 画出的图标，仍然是你自己的关闭按钮。

## 用法
导入各个部件并把它们组合起来，然后在动作完成时调用 `toast()`：

```html
<script type="module">
  import { toast } from "@ui-sdk/web/toast"

  document
    .querySelector("#create-event")
    .addEventListener("click", () =>
      toast("Event created", { description: "Friday at 10:00 AM" })
    )
</script>

<button id="create-event" type="button">Create Event</button>
<ui-toast-region>
  <template>
    <ui-toast>
      <ui-toast-title></ui-toast-title>
      <ui-toast-description></ui-toast-description>
    </ui-toast>
  </template>
</ui-toast-region>
```

`toast()` 可以在任何地方使用，不只是事件监听器里，并返回 toast 的 id。在没有构建步骤的页面上，从 `https://ui-sdk.cn/web@0/toast.js` 导入它。在应用的根节点附近放置一次区域。没有模板时，它用无样式的部件渲染每个 toast 的标题、描述、动作和取消按钮。

下面的示例各自调用 `createToaster()` 得到自己的队列，并把它设置在区域的 `toaster` property 上，所以它们的 toast 不会混在一起。

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

```ts title="types.ts"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"
import {
  CircleCheck,
  createElement,
  Info,
  LoaderCircle,
  OctagonX,
  TriangleAlert,
} from "lucide"

const upload = () => new Promise((resolve) => setTimeout(resolve, 2000))

function mount(root: HTMLElement) {
  const toast = createToaster()
  root.innerHTML = `
    <div data-slot="row">
      <button>Default</button>
      <button>Success</button>
      <button>Info</button>
      <button>Warning</button>
      <button>Error</button>
      <button>Loading</button>
    </div>
    <ui-toast-region>
      <template>
        <ui-toast>
          ${createElement(CircleCheck, { "data-show": "success", "aria-hidden": "true" }).outerHTML}
          ${createElement(Info, { "data-show": "info", "aria-hidden": "true" }).outerHTML}
          ${createElement(TriangleAlert, { "data-show": "warning", "aria-hidden": "true" }).outerHTML}
          ${createElement(OctagonX, { "data-show": "error", "aria-hidden": "true" }).outerHTML}
          ${createElement(LoaderCircle, { "data-show": "loading", "aria-hidden": "true" }).outerHTML}
          <ui-toast-title></ui-toast-title>
        </ui-toast>
      </template>
    </ui-toast-region>
  `
  root.querySelector("ui-toast-region")!.toaster = toast
  const [plain, success, info, warning, error, loading] =
    root.querySelectorAll("button")
  plain.addEventListener("click", () => toast("Event created"))
  success.addEventListener("click", () => toast.success("Changes saved"))
  info.addEventListener("click", () => toast.info("A new version is available"))
  warning.addEventListener("click", () =>
    toast.warning("Storage is almost full")
  )
  error.addEventListener("click", () => toast.error("Couldn't save changes"))
  loading.addEventListener("click", () =>
    toast.promise(upload, {
      loading: "Uploading photos…",
      success: "Photos uploaded",
      error: "Upload failed",
    })
  )
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

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

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

```ts title="position.ts"
import "@ui-sdk/web/select"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"
import { Check, ChevronDown, createElement } from "lucide"

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

const check = createElement(Check, { "aria-hidden": "true" }).outerHTML
const chevron = createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML

function select(
  attribute: string,
  label: string,
  value: string,
  options: { value: string; label: string }[]
) {
  return `
    <ui-select data-attribute="${attribute}" default-value="${value}">
      <ui-select-label>${label}</ui-select-label>
      <ui-select-trigger>
        <button>
          <ui-select-value></ui-select-value>
          ${chevron}
        </button>
      </ui-select-trigger>
      <ui-select-content hidden>
        ${options
          .map(
            (option) => `
              <ui-select-item value="${option.value}">
                ${option.label}
                <ui-select-item-indicator>${check}</ui-select-item-indicator>
              </ui-select-item>
            `
          )
          .join("")}
      </ui-select-content>
    </ui-select>
  `
}

function mount(root: HTMLElement) {
  const toast = createToaster()
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        ${select("side", "Side", "bottom", sides)}
        ${select("align", "Align", "end", aligns)}
      </div>
      <button>Create Event</button>
      <ui-toast-region side="bottom" align="end">
        <template>
          <ui-toast>
            <div data-slot="stack">
              <ui-toast-title></ui-toast-title>
              <ui-toast-description></ui-toast-description>
            </div>
          </ui-toast>
        </template>
      </ui-toast-region>
    </div>
  `
  const region = root.querySelector("ui-toast-region")!
  region.toaster = toast
  for (const control of root.querySelectorAll("ui-select")) {
    control.addEventListener("valuechange", (event) => {
      const value = event.detail.value
      if (typeof value === "string") {
        region.setAttribute(control.dataset.attribute!, value)
      }
    })
  }
  root
    .querySelector("[data-slot='controls'] + button")!
    .addEventListener("click", () =>
      toast("Event created", { description: "Friday, June 12 at 10:00 AM" })
    )
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

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

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

```ts title="action.ts"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"
import { log } from "./log"

function mount(root: HTMLElement) {
  const toast = createToaster()
  root.innerHTML = `
    <button>Archive Message</button>
    <ui-toast-region>
      <template>
        <ui-toast>
          <ui-toast-title></ui-toast-title>
          <ui-toast-close><button></button></ui-toast-close>
          <ui-toast-action><button data-variant="solid"></button></ui-toast-action>
        </ui-toast>
      </template>
    </ui-toast-region>
  `
  root.querySelector("ui-toast-region")!.toaster = toast
  root.querySelector("button")!.addEventListener("click", () =>
    toast("Message archived", {
      action: { label: "Undo", onAction: () => log(root, "Message restored") },
      cancel: { label: "Dismiss", onCancel: () => log(root, "Kept archived") },
      onDismiss: ({ reason }) => log(root, `Closed (${reason})`),
    })
  )
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

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

## 链接
给动作一个 `href`，并在 `ui-toast-action` 里写 `<a>` 而不是 `<button>`，把它渲染成链接；区域的 `renderToast` 会从 toast 设置链接的 `href`。它保留正常的链接行为，包括在新标签页中打开。

```ts title="link.ts"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"

function mount(root: HTMLElement) {
  const toast = createToaster()
  root.innerHTML = `
    <button>Send Invoice</button>
    <ui-toast-region>
      <template>
        <ui-toast>
          <div data-slot="stack">
            <ui-toast-title></ui-toast-title>
            <ui-toast-description></ui-toast-description>
          </div>
          <ui-toast-action><a data-variant="solid"></a></ui-toast-action>
        </ui-toast>
      </template>
    </ui-toast-region>
  `
  const region = root.querySelector("ui-toast-region")!
  region.toaster = toast
  region.renderToast = (item, el) => {
    if (item.action?.href) {
      el.querySelector("a")!.href = item.action.href
    }
  }
  root.querySelector("button")!.addEventListener("click", () =>
    toast("Invoice sent", {
      description: "Hollis Grant · $240.00",
      action: { label: "View", href: "#" },
    })
  )
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

按 Send Invoice，然后打开 toast 里的 View。

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

```ts title="promise.ts"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"

function mount(root: HTMLElement) {
  const toast = createToaster()
  let attempts = 0

  function save() {
    const succeeds = ++attempts % 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 },
      },
    })
  }

  root.innerHTML = `
    <button>Save Changes</button>
    <ui-toast-region>
      <template>
        <ui-toast>
          <div data-slot="stack">
            <ui-toast-title></ui-toast-title>
            <ui-toast-description></ui-toast-description>
          </div>
          <ui-toast-action><button data-variant="solid"></button></ui-toast-action>
        </ui-toast>
      </template>
    </ui-toast-region>
  `
  root.querySelector("ui-toast-region")!.toaster = toast
  root.querySelector("button")!.addEventListener("click", saveChanges)
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

按 Save Changes，看着 Saving changes 变成 Changes saved。再按一次查看错误，然后选择 Retry。

## 堆叠
`max-visible` 限制一次显示多少个 toast，默认三个；其余的留在队列里等待，显示时计时器才开始。指针或焦点在堆叠中时，堆叠会展开。设置 `expanded` 让它保持展开。[样式](https://ui-sdk.cn/docs/web-components/components/toast#styling)展示了布局这个堆叠的 CSS。

```ts title="stacking.ts"
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"
import { Check, createElement } from "lucide"

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 mount(root: HTMLElement) {
  const toast = createToaster()
  let count = 0
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <ui-checkbox>
            <ui-checkbox-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-checkbox-indicator>
          </ui-checkbox>
          Always expanded
        </label>
      </div>
      <button>Add Toast</button>
      <ui-toast-region max-visible="4">
        <template>
          <ui-toast>
            <div data-slot="stack">
              <ui-toast-title></ui-toast-title>
              <ui-toast-description></ui-toast-description>
            </div>
          </ui-toast>
        </template>
      </ui-toast-region>
    </div>
  `
  const region = root.querySelector("ui-toast-region")!
  region.toaster = toast
  root
    .querySelector("ui-checkbox")!
    .addEventListener("checkedchange", (event) => {
      region.expanded = event.detail.value === true
    })
  root
    .querySelector("button")!
    .addEventListener("click", () =>
      toast(notifications[count++ % notifications.length])
    )
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

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

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

```ts title="duration.ts"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"

function mount(root: HTMLElement) {
  const toast = createToaster()
  root.innerHTML = `
    <div data-slot="row">
      <button>1 Second</button>
      <button>5 Seconds</button>
      <button>Until Dismissed</button>
    </div>
    <ui-toast-region>
      <template>
        <ui-toast>
          <ui-toast-title></ui-toast-title>
          <ui-toast-close><button data-variant="solid"></button></ui-toast-close>
        </ui-toast>
      </template>
    </ui-toast-region>
  `
  root.querySelector("ui-toast-region")!.toaster = toast
  const [second, seconds, untilDismissed] = root.querySelectorAll("button")
  second.addEventListener("click", () =>
    toast("Link copied", { duration: 1000 })
  )
  seconds.addEventListener("click", () => toast("Changes saved"))
  untilDismissed.addEventListener("click", () =>
    toast("Your session expires in 5 minutes", {
      duration: Infinity,
      dismissible: false,
      cancel: { label: "Got It" },
    })
  )
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

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

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

```ts title="update.ts"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"
import { CircleCheck, createElement, LoaderCircle } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  const toast = createToaster()
  let timer: ReturnType<typeof setInterval> | undefined

  function upload() {
    clearInterval(timer)
    const id = toast.loading("Uploading report.pdf… 0%", { id: "upload" })
    let progress = 0
    timer = 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(root, "Upload canceled")
      }
      if (done || !open) {
        clearInterval(timer)
      }
    }, 700)
  }

  root.innerHTML = `
    <div data-slot="row">
      <button>Upload Report</button>
      <button>Cancel Upload</button>
      <button>Dismiss All</button>
    </div>
    <ui-toast-region>
      <template>
        <ui-toast>
          ${createElement(CircleCheck, { "data-show": "success", "aria-hidden": "true" }).outerHTML}
          ${createElement(LoaderCircle, { "data-show": "loading", "aria-hidden": "true" }).outerHTML}
          <ui-toast-title></ui-toast-title>
        </ui-toast>
      </template>
    </ui-toast-region>
  `
  root.querySelector("ui-toast-region")!.toaster = toast
  const [start, cancel, dismissAll] = root.querySelectorAll("button")
  start.addEventListener("click", upload)
  cancel.addEventListener("click", () => toast.dismiss("upload"))
  dismissAll.addEventListener("click", () => toast.dismiss())
  return () => {
    clearInterval(timer)
    toast.dismiss()
  }
}

export { mount }
```

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

## 异步动作
从动作返回一个 promise，让 toast 在它运行期间保持打开。它的按钮在运行期间得到 `data-pending`，并在动作结束之前忽略按压，动作可以改变按钮的文字来显示 **Restoring…**，或者失败时提供重试。`await` 之后所做的变更见 [Button](https://ui-sdk.cn/docs/web-components/components/button#changes-after-an-await)。

```ts title="async-action.ts"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"
import { log } from "./log"

const restore = () => new Promise((resolve) => setTimeout(resolve, 1500))

function mount(root: HTMLElement) {
  const toast = createToaster({ duration: 6000 })
  root.innerHTML = `
    <button>Delete File</button>
    <ui-toast-region>
      <template>
        <ui-toast>
          <div data-slot="stack">
            <ui-toast-title></ui-toast-title>
            <ui-toast-description></ui-toast-description>
          </div>
          <ui-toast-action><button data-variant="solid"></button></ui-toast-action>
        </ui-toast>
      </template>
    </ui-toast-region>
  `
  root.querySelector("ui-toast-region")!.toaster = toast
  root.querySelector("button")!.addEventListener("click", () =>
    toast("File deleted", {
      description: "Q3 report.pdf",
      action: {
        label: "Undo",
        onAction: async (event) => {
          const button = (event?.target as Element | undefined)?.closest(
            "button"
          )
          if (button) {
            button.textContent = "Restoring…"
          }
          try {
            await restore()
          } catch (error) {
            if (button) {
              button.textContent = "Retry"
            }
            throw error
          }
          log(root, "Q3 report.pdf restored")
        },
      },
    })
  )
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

按 Delete File，然后按 Undo。按钮会显示 Restoring…，直到恢复完成，然后 toast 关闭。

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

```ts title="shortcut.ts"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"
import { log } from "./log"

function mount(root: HTMLElement) {
  const toast = createToaster({ duration: 10000 })
  root.innerHTML = `
    <button>Send Message</button>
    <ui-toast-region shortcut="alt+t" aria-label="Alerts">
      <template>
        <ui-toast>
          <ui-toast-title></ui-toast-title>
          <ui-toast-action><button data-variant="solid"></button></ui-toast-action>
        </ui-toast>
      </template>
    </ui-toast-region>
  `
  root.querySelector("ui-toast-region")!.toaster = toast
  root.querySelector("button")!.addEventListener("click", () =>
    toast("Message sent", {
      action: { label: "Undo", onAction: () => log(root, "Message unsent") },
    })
  )
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

按 Send Message，然后按 Alt+T（Mac 上是 Option+T）聚焦 toast。按 Escape 关闭它，或者再按一次 Alt+T 返回。

## 浮层宿主与确认框
除了放置区域，也可以在应用的根节点附近添加一个 `ui-overlay-host`。它渲染 toaster 的区域，并把 `confirm()` 问题渲染成警告对话框。在它连接之前设置它的 `toast` property：`attributes` 放在区域上，`template` 保存每个 toast 复制的 `ui-toast`。对于同一个 toaster，你自己放置的区域会取代宿主。

要给问题设置样式，用 confirm 控制器渲染一个 `ui-alert-dialog`，并从它的 `payloadchange` 事件读取问题。[Alert Dialog](/docs/web-components/components/alert-dialog)更详细地介绍了 `createConfirm()`。

```ts title="overlay-host.ts"
import "@ui-sdk/web/alert-dialog"
import "@ui-sdk/web/overlays"
import {
  createConfirm,
  createOverlays,
  createToaster,
  type ConfirmOptions,
  type UiAlertDialogElement,
} from "@ui-sdk/web"
import { CircleCheck, createElement } from "lucide"

const names = ["Acme", "Globex", "Initech"]

function mount(root: HTMLElement) {
  const overlays = createOverlays()
  const toast = createToaster({ overlays })
  const confirm = createConfirm({ overlays })
  let projects = names
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button">Reset Projects</button>
      </div>
      <ul data-slot="list" aria-label="Projects"></ul>
      <ui-alert-dialog>
        <ui-alert-dialog-backdrop hidden></ui-alert-dialog-backdrop>
        <ui-alert-dialog-content hidden>
          <div data-slot="stack">
            <ui-alert-dialog-title></ui-alert-dialog-title>
            <ui-alert-dialog-description></ui-alert-dialog-description>
          </div>
          <div data-slot="row">
            <ui-alert-dialog-close><button></button></ui-alert-dialog-close>
            <ui-alert-dialog-close value="confirm"><button data-variant="solid"></button></ui-alert-dialog-close>
          </div>
        </ui-alert-dialog-content>
      </ui-alert-dialog>
    </div>
  `
  const reset = root.querySelector("button")!
  const list = root.querySelector("ul")!

  function render() {
    list.innerHTML = projects.length
      ? projects
          .map(
            (name) =>
              `<li data-slot="row">${name}<button type="button" data-size="sm" aria-label="Delete ${name}">Delete</button></li>`
          )
          .join("")
      : `<li data-slot="row">All projects deleted.</li>`
    list.querySelectorAll("button").forEach((button, index) => {
      const name = projects[index]
      button.addEventListener("click", () => remove(name, index))
    })
  }

  async function remove(name: string, index: number) {
    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
    }
    projects = projects.filter((project) => project !== name)
    render()
    ;(
      list.querySelectorAll("button")[Math.min(index, projects.length - 1)] ??
      reset
    ).focus()
    toast.success(`${name} deleted`, { priority: "assertive" })
  }

  reset.addEventListener("click", () => {
    projects = names
    render()
  })
  render()

  const dialog =
    root.querySelector<UiAlertDialogElement<ConfirmOptions>>("ui-alert-dialog")!
  const [cancel, agree] = dialog.querySelectorAll("button")
  dialog.controller = confirm.controller
  dialog.addEventListener("payloadchange", (event) => {
    const question = event.detail.value
    dialog.querySelector("ui-alert-dialog-title")!.textContent =
      question?.title ?? ""
    dialog.querySelector("ui-alert-dialog-description")!.textContent =
      question?.description ?? ""
    cancel.textContent = question?.cancelLabel ?? ""
    agree.textContent = question?.confirmLabel ?? ""
  })

  const template = document.createElement("template")
  template.innerHTML = `
    <ui-toast>
      ${createElement(CircleCheck, { "data-show": "success", "aria-hidden": "true" }).outerHTML}
      <ui-toast-title></ui-toast-title>
    </ui-toast>
  `
  dialog.before(
    Object.assign(document.createElement("ui-overlay-host"), {
      overlays,
      toast: { template },
    })
  )
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

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

## 自定义渲染
把 toast 需要的其他内容放在 `data` 里传入，并在区域的 `renderToast(toast, el)` 中读取它，这个函数会在每个 toast 元素显示时以及每次更新之后运行。

```ts title="custom.ts"
import "@ui-sdk/web/toast"
import { createToaster } from "@ui-sdk/web"
import { createElement, X } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  const toast = createToaster()
  root.innerHTML = `
    <button>New Message</button>
    <ui-toast-region aria-label="Messages">
      <template>
        <ui-toast>
          <span data-slot="media"></span>
          <div data-slot="stack">
            <ui-toast-title></ui-toast-title>
            <ui-toast-description></ui-toast-description>
          </div>
          <ui-toast-action><button data-variant="solid"></button></ui-toast-action>
          <ui-toast-close>
            <button aria-label="Close">${createElement(X, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-toast-close>
        </ui-toast>
      </template>
    </ui-toast-region>
  `
  const region = root.querySelector("ui-toast-region")!
  region.toaster = toast
  region.renderToast = (item, el) => {
    el.querySelector("[data-slot='media']")!.textContent = (
      item.data as { initials: string }
    ).initials
  }
  root.querySelector("button")!.addEventListener("click", () =>
    toast({
      title: "Hollis Grant",
      description: "Can you review the draft?",
      data: { initials: "HG" },
      action: {
        label: "Reply",
        onAction: () => log(root, "Replying to Hollis Grant"),
      },
    })
  )
  return () => {
    toast.dismiss()
  }
}

export { mount }
```

按 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 写成：

```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`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/web-components/components/toast#data-attributes)下。动作或关闭按钮的属性会落在它的按钮上。

### `<ui-toast-region>`
- `--toast-front-height`: The newest toast's height. Clip the toasts behind it to it in a collapsed stack.
- `--toast-stack-height`: The toasts' heights added up, for the height of an expanded stack.
- `--toast-count`: How many toasts show.
- `--keyboard-inset`: How many pixels of the page the on-screen keyboard covers, 0 without one.
- `--visual-viewport-width`: The width of the part of the page you can see.
- `--visual-viewport-height`: The height of the part of the page you can see, above the keyboard.
- `--visual-viewport-top`: How far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up.

### `<ui-toast>`
- `--toast-index`: The toast's place in the stack, 0 for the newest. A closing toast keeps its place.
- `--toast-offset`: The height of the toasts in front of this one, in pixels. Add gaps with `--toast-index` to place an expanded stack.
- `--toast-height`: The 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-x`: How far a swipe moved the toast sideways, in pixels. Translate the toast by it.
- `--toast-swipe-y`: How far a swipe moved the toast up or down, in pixels.

## 数据属性
`ui-toast-title` 和 `ui-toast-description` 没有状态属性。`ui-toast-close` 里的按钮在它的动作返回的 Promise 运行期间，会像 `ui-toast-action` 里的按钮一样得到 `data-pending`。

### `<ui-toast-region>`
`[data-slot="toast-region"]`

- `data-side` (`top`, `bottom`): The edge of the viewport the region sits on.
- `data-align` (`start`, `center`, `end`): Where along that edge.
- `data-expanded`: Present while the stack is expanded: hovered, focused, or always with `expanded`.
- `data-keyboard`: Present on the region while the on-screen keyboard covers part of the page.

### `<ui-toast>`
`[data-slot="toast"]`

- `data-type` (`default`, `success`, `error`, `info`, `warning`, `loading`): What the toast is about.
- `data-front`: Present on the newest toast, in front of a collapsed stack. A closing toast keeps it while it animates out.
- `data-expanded`: Present while the stack is expanded: hovered, focused, or always with `expanded`.
- `data-starting-style`: Present for a toast's first frame. Style the state you animate from.
- `data-ending-style`: Present while a toast animates out. Style the state you animate to.

### `<ui-toast-action>`
`[data-slot="toast-action"]`

- `data-pending`: Present 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()` 关闭每一个。

### 动作
- `label` (`Content`): 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.

- `label` (`Content`): 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
- `action event`: 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
- `title` (`string`): 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.

### 状态
`ui-toast-region`：

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

`ui-toast`：

- `type` (`ToastType`): What it's about.
- `index` (`number`): Its place in the stack, 0 for the newest.
- `front` (`boolean`): Whether it's the newest, on top of a collapsed stack. A closing toast keeps it.
- `expanded` (`boolean`): Whether the stack is expanded.
- `leaving` (`boolean`): Whether it's animating out.

`ui-toast-action` 和 `ui-toast-close`：

- `pending` (`boolean`): Whether a Promise its handler returned is still running.
- `error` (`unknown`): Why its handler failed, until it's pressed again.

### 原因
- `timeout` (`none`): A duration ran out, like a toast's, or a rotating carousel's interval.
- `close-press` (`MouseEvent | KeyboardEvent | SubmitEvent`): A Close part was pressed, or a form with `method="dialog"` was submitted.
- `swipe` (`PointerEvent | TouchEvent`): A swipe gesture: a finger, mouse or pen dragged it.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `action` (`MouseEvent | KeyboardEvent`): A Close part's `action` finished.
- `imperative` (`none`): A controller or `api` call.

## 无障碍
toast 通过共享的[实时区域（live region）](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Guides/Live_regions)播报，每个只播报一次，而不把可见区域本身变成实时区域：默认礼貌播报，错误时即时（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.

Runs in 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.

Runs in React、Vue 和 web components.

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

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

Runs in React、Vue 和 web components.
