# Toast

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

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

```vue title="demo.vue"
<script setup lang="ts">
import {
  Toast,
  ToastAction,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted } from "vue"
import { useLog } from "./log"

const log = useLog()
const toast = createToaster()
onUnmounted(() => {
  toast.dismiss()
})

function createEvent() {
  toast("Event created", {
    description: "Friday, June 12 at 10:00 AM",
    action: { label: "Undo", onAction: () => log("Event removed") },
  })
}
</script>

<template>
  <button @click="createEvent">Create Event</button>
  <ToastRegion :toaster="toast">
    <Toast>
      <div data-slot="stack">
        <ToastTitle />
        <ToastDescription />
      </div>
      <ToastAction data-variant="solid" />
    </Toast>
  </ToastRegion>
</template>
```

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

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

## 组合
用下面的组合构建一个 `ToastRegion`：

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

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

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

```vue
<script setup lang="ts">
import {
  Toast,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  toast,
} from "@ui-sdk/vue/toast"
</script>

<template>
  <button
    type="button"
    @click="toast('Event created', { description: 'Friday at 10:00 AM' })"
  >
    Create Event
  </button>
  <ToastRegion>
    <Toast>
      <ToastTitle />
      <ToastDescription />
    </Toast>
  </ToastRegion>
</template>
```

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

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

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

```vue title="types.vue"
<script setup lang="ts">
import {
  CircleCheckIcon,
  InfoIcon,
  LoaderCircleIcon,
  OctagonXIcon,
  TriangleAlertIcon,
} from "@lucide/vue"
import {
  Toast,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted } from "vue"

const toast = createToaster()
onUnmounted(() => {
  toast.dismiss()
})

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

function uploadPhotos() {
  toast.promise(upload, {
    loading: "Uploading photos…",
    success: "Photos uploaded",
    error: "Upload failed",
  })
}
</script>

<template>
  <div data-slot="row">
    <button @click="toast('Event created')">Default</button>
    <button @click="toast.success('Changes saved')">Success</button>
    <button @click="toast.info('A new version is available')">Info</button>
    <button @click="toast.warning('Storage is almost full')">Warning</button>
    <button @click="toast.error(`Couldn't save changes`)">Error</button>
    <button @click="uploadPhotos">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>
</template>
```

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

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

```vue title="position.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/vue/select"
import {
  Toast,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted, ref } from "vue"

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"

const toast = createToaster()
const side = ref<Side>("bottom")
const align = ref<Align>("end")
onUnmounted(() => {
  toast.dismiss()
})
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <Select
        :items="sides"
        :value="side"
        @value-change="(next) => next && (side = next as Side)"
      >
        <SelectLabel>Side</SelectLabel>
        <SelectTrigger>
          <SelectValue />
          <ChevronDownIcon aria-hidden="true" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem
            v-for="option in sides"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
            <SelectItemIndicator>
              <CheckIcon aria-hidden="true" />
            </SelectItemIndicator>
          </SelectItem>
        </SelectContent>
      </Select>
      <Select
        :items="aligns"
        :value="align"
        @value-change="(next) => next && (align = next as Align)"
      >
        <SelectLabel>Align</SelectLabel>
        <SelectTrigger>
          <SelectValue />
          <ChevronDownIcon aria-hidden="true" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem
            v-for="option in aligns"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
            <SelectItemIndicator>
              <CheckIcon aria-hidden="true" />
            </SelectItemIndicator>
          </SelectItem>
        </SelectContent>
      </Select>
    </div>
    <button
      @click="
        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>
</template>
```

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

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

```vue title="action.vue"
<script setup lang="ts">
import {
  Toast,
  ToastAction,
  ToastClose,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted } from "vue"
import { useLog } from "./log"

const log = useLog()
const toast = createToaster()
onUnmounted(() => {
  toast.dismiss()
})

function archive() {
  toast("Message archived", {
    action: { label: "Undo", onAction: () => log("Message restored") },
    cancel: { label: "Dismiss", onCancel: () => log("Kept archived") },
    onDismiss: ({ reason }) => log(`Closed (${reason})`),
  })
}
</script>

<template>
  <button @click="archive">Archive Message</button>
  <ToastRegion :toaster="toast">
    <template #default="{ toast: item }">
      <Toast>
        <ToastTitle />
        <ToastClose v-if="item.cancel" :action="item.cancel.onCancel">{{
          item.cancel.label
        }}</ToastClose>
        <ToastAction data-variant="solid" />
      </Toast>
    </template>
  </ToastRegion>
</template>
```

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

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

```vue title="link.vue"
<script setup lang="ts">
import {
  Toast,
  ToastAction,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted } from "vue"

const toast = createToaster()
onUnmounted(() => {
  toast.dismiss()
})

function sendInvoice() {
  toast("Invoice sent", {
    description: "Hollis Grant · $240.00",
    action: { label: "View", href: "#" },
  })
}
</script>

<template>
  <button @click="sendInvoice">Send Invoice</button>
  <ToastRegion :toaster="toast">
    <Toast>
      <div data-slot="stack">
        <ToastTitle />
        <ToastDescription />
      </div>
      <ToastAction data-variant="solid" />
    </Toast>
  </ToastRegion>
</template>
```

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

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

```vue title="promise.vue"
<script setup lang="ts">
import {
  Toast,
  ToastAction,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted } from "vue"

const toast = createToaster()
let attempts = 0
onUnmounted(() => {
  toast.dismiss()
})

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 },
    },
  })
}
</script>

<template>
  <button @click="saveChanges">Save Changes</button>
  <ToastRegion :toaster="toast">
    <Toast>
      <div data-slot="stack">
        <ToastTitle />
        <ToastDescription />
      </div>
      <ToastAction data-variant="solid" />
    </Toast>
  </ToastRegion>
</template>
```

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

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

```vue title="stacking.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/vue/checkbox"
import {
  Toast,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted, ref } from "vue"

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" },
]

const toast = createToaster()
const expanded = ref(false)
let count = 0
onUnmounted(() => {
  toast.dismiss()
})
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <label data-slot="label">
        <Checkbox
          :checked="expanded"
          @checked-change="(next) => (expanded = next === true)"
        >
          <CheckboxIndicator>
            <CheckIcon aria-hidden="true" />
          </CheckboxIndicator>
        </Checkbox>
        Always expanded
      </label>
    </div>
    <button @click="toast(notifications[count++ % notifications.length])">
      Add Toast
    </button>
    <ToastRegion :toaster="toast" :max-visible="4" :expanded="expanded">
      <Toast>
        <div data-slot="stack">
          <ToastTitle />
          <ToastDescription />
        </div>
      </Toast>
    </ToastRegion>
  </div>
</template>
```

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

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

```vue title="duration.vue"
<script setup lang="ts">
import {
  Toast,
  ToastClose,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted } from "vue"

const toast = createToaster()
onUnmounted(() => {
  toast.dismiss()
})

function untilDismissed() {
  toast("Your session expires in 5 minutes", {
    duration: Infinity,
    dismissible: false,
    cancel: { label: "Got It" },
  })
}
</script>

<template>
  <div data-slot="row">
    <button @click="toast('Link copied', { duration: 1000 })">1 Second</button>
    <button @click="toast('Changes saved')">5 Seconds</button>
    <button @click="untilDismissed">Until Dismissed</button>
  </div>
  <ToastRegion :toaster="toast">
    <template #default="{ toast: item }">
      <Toast>
        <ToastTitle />
        <ToastClose
          v-if="item.cancel"
          data-variant="solid"
          :action="item.cancel.onCancel"
        >
          {{ item.cancel.label }}
        </ToastClose>
      </Toast>
    </template>
  </ToastRegion>
</template>
```

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

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

```vue title="update.vue"
<script setup lang="ts">
import { CircleCheckIcon, LoaderCircleIcon } from "@lucide/vue"
import {
  Toast,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted } from "vue"
import { useLog } from "./log"

const log = useLog()
const toast = createToaster()
let timer: ReturnType<typeof setInterval> | undefined
onUnmounted(() => {
  clearInterval(timer)
  toast.dismiss()
})

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("Upload canceled")
    }
    if (done || !open) {
      clearInterval(timer)
    }
  }, 700)
}
</script>

<template>
  <div data-slot="row">
    <button @click="upload">Upload Report</button>
    <button @click="toast.dismiss('upload')">Cancel Upload</button>
    <button @click="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>
</template>
```

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

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

```vue title="async-action.vue"
<script setup lang="ts">
import {
  Toast,
  ToastAction,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted } from "vue"
import { useLog } from "./log"

const log = useLog()
const toast = createToaster({ duration: 6000 })
onUnmounted(() => {
  toast.dismiss()
})

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

function deleteFile() {
  toast("File deleted", {
    description: "Q3 report.pdf",
    action: {
      label: "Undo",
      onAction: async () => {
        await restore()
        log("Q3 report.pdf restored")
      },
    },
  })
}
</script>

<template>
  <button @click="deleteFile">Delete File</button>
  <ToastRegion :toaster="toast">
    <Toast>
      <div data-slot="stack">
        <ToastTitle />
        <ToastDescription />
      </div>
      <ToastAction v-slot="{ state }" data-variant="solid">
        {{ state.pending ? "Restoring…" : state.error ? "Retry" : "Undo" }}
      </ToastAction>
    </Toast>
  </ToastRegion>
</template>
```

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

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

```vue title="shortcut.vue"
<script setup lang="ts">
import {
  Toast,
  ToastAction,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted } from "vue"
import { useLog } from "./log"

const log = useLog()
const toast = createToaster({ duration: 10000 })
onUnmounted(() => {
  toast.dismiss()
})

function sendMessage() {
  toast("Message sent", {
    action: { label: "Undo", onAction: () => log("Message unsent") },
  })
}
</script>

<template>
  <button @click="sendMessage">Send Message</button>
  <ToastRegion :toaster="toast" shortcut="alt+t" aria-label="Alerts">
    <Toast>
      <ToastTitle />
      <ToastAction data-variant="solid" />
    </Toast>
  </ToastRegion>
</template>
```

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

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

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

```vue title="overlay-host.vue"
<script setup lang="ts">
import { CircleCheckIcon } from "@lucide/vue"
import {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogTitle,
  createConfirm,
  type ConfirmOptions,
} from "@ui-sdk/vue/alert-dialog"
import { OverlayHost, createOverlays } from "@ui-sdk/vue/overlays"
import { Toast, ToastTitle, createToaster } from "@ui-sdk/vue/toast"
import { onUnmounted, ref, useTemplateRef } from "vue"

const overlays = createOverlays()
const toast = createToaster({ overlays })
const confirm = createConfirm({ overlays })
const ConfirmAlertDialogContent = AlertDialogContent<ConfirmOptions>
const projects = ref(["Acme", "Globex", "Initech"])
const reset = useTemplateRef<HTMLButtonElement>("reset")
onUnmounted(() => {
  toast.dismiss()
})

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.value)?.focus()
  projects.value = projects.value.filter((project) => project !== name)
  toast.success(`${name} deleted`, { priority: "assertive" })
}
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <button
        ref="reset"
        type="button"
        @click="projects = ['Acme', 'Globex', 'Initech']"
      >
        Reset Projects
      </button>
    </div>
    <ul data-slot="list" aria-label="Projects">
      <li v-for="name in projects" :key="name" data-slot="row">
        {{ name }}
        <button
          type="button"
          data-size="sm"
          :aria-label="`Delete ${name}`"
          @click="remove(name, $event.currentTarget as HTMLButtonElement)"
        >
          Delete
        </button>
      </li>
      <li v-if="projects.length === 0" data-slot="row">
        All projects deleted.
      </li>
    </ul>
    <OverlayHost :overlays="overlays">
      <template #toast>
        <Toast>
          <CircleCheckIcon data-show="success" aria-hidden="true" />
          <ToastTitle />
        </Toast>
      </template>
    </OverlayHost>
    <AlertDialog :controller="confirm.controller">
      <AlertDialogBackdrop />
      <ConfirmAlertDialogContent v-slot="{ 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>
      </ConfirmAlertDialogContent>
    </AlertDialog>
  </div>
</template>
```

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

## 自定义渲染
把 toast 需要的其他内容放在 `data` 里传入，并从区域默认插槽收到的 `toast` 中读取它。每个部件也接受 `#render` 插槽；这个示例自己渲染每个 toast 的 `li`，并把折叠堆叠后面隐藏的那些设为不可交互（inert）。

```vue title="custom.vue"
<script setup lang="ts">
import { XIcon } from "@lucide/vue"
import {
  Toast,
  ToastAction,
  ToastClose,
  ToastDescription,
  ToastRegion,
  ToastTitle,
  createToaster,
} from "@ui-sdk/vue/toast"
import { onUnmounted } from "vue"
import { useLog } from "./log"

const log = useLog()
const toast = createToaster()
onUnmounted(() => {
  toast.dismiss()
})

function newMessage() {
  toast({
    title: "Hollis Grant",
    description: "Can you review the draft?",
    data: { initials: "HG" },
    action: { label: "Reply", onAction: () => log("Replying to Hollis Grant") },
  })
}
</script>

<template>
  <button @click="newMessage">New Message</button>
  <ToastRegion :toaster="toast" aria-label="Messages">
    <template #default="{ toast: item }">
      <Toast>
        <template #render="{ props, state, children }">
          <li
            v-bind="props"
            :inert="
              state.leaving || (!state.expanded && state.index > 0) || undefined
            "
          >
            <component :is="children" />
          </li>
        </template>
        <template #default>
          <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>
        </template>
      </Toast>
    </template>
  </ToastRegion>
</template>
```

按 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/vue/components/toast#data-attributes)下。

### ToastRegion
- `--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.

### 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.

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

### ToastRegion
`[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.

### 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.

### ToastAction
`[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: 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
- `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.

### 状态
`ToastRegion`：

- `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.

`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.

`ToastAction` 和 `ToastClose`：

- `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.
