显示通知,支持动作、定时关闭和屏幕阅读器播报。
toast 告诉某人发生了某件事,比如保存了一处更改或发送了一条消息,然后自行消失。它可以提供一个像 Undo 这样的动作,和先前的 toast 堆叠在一起,并在不取得焦点的情况下向屏幕阅读器播报。
<script lang="ts">
import { onDestroy } from "svelte"
import {
Toast,
ToastAction,
ToastDescription,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
import { useLog } from "./log"
const log = useLog()
const toast = createToaster()
onDestroy(() => {
toast.dismiss()
})
</script>
<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>安装
npm install @ui-sdk/svelte @ui-sdk/core组合
用下面的组合构建一个 ToastRegion:
ToastRegion
├── Toast
│ ├── ToastTitle
│ ├── ToastDescription
│ ├── ToastAction
│ └── ToastClose
└── Toast
├── ToastTitle
└── ToastDescription区域通过它的 children snippet,为队列中的每个 toast 渲染一个 Toast,最新的在前。toast 由标题命名,由描述说明。空的标题、描述和动作部件会显示 toast 数据中的文本,所以区域的渲染函数通常就是同样那几个部件。
用法
导入各个部件并把它们组合起来,然后在动作完成时调用 toast():
<script lang="ts">
import {
Toast,
ToastDescription,
ToastRegion,
ToastTitle,
toast,
} from "@ui-sdk/svelte/toast"
</script>
<button
type="button"
onclick={() => toast("Event created", { description: "Friday at 10:00 AM" })}
>
Create Event
</button>
<ToastRegion>
<Toast>
<ToastTitle />
<ToastDescription />
</Toast>
</ToastRegion>toast() 可以在任何地方使用,不只是组件里,并返回 toast 的 id。在应用的根节点附近放置一次区域。没有自己的内容时,它用无样式的部件渲染每个 toast 的标题、描述、动作和取消按钮。
下面的示例各自调用 createToaster() 得到自己的队列,并把它作为 toaster 传给它们的区域,所以它们的 toast 不会混在一起。
类型
toast.success、.info、.warning、.error 和 .loading 设置 toast 的类型,toast 通过 data-type 暴露它,供图标或颜色使用。错误会立即播报,其他类型会等到停顿之后再播报;设置 priority 可以改变这一点。加载中的 toast 会一直保留,直到被更新或关闭。
<script lang="ts">
import { onDestroy } from "svelte"
import {
CircleCheckIcon,
InfoIcon,
LoaderCircleIcon,
OctagonXIcon,
TriangleAlertIcon,
} from "@lucide/svelte"
import {
Toast,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
function upload() {
return new Promise((resolve) => setTimeout(resolve, 2000))
}
const toast = createToaster()
onDestroy(() => {
toast.dismiss()
})
</script>
<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>位置
把区域的 side 设为 top 或 bottom,把 align 设为 start、center 或 end。start 和 end 跟随书写方向。toast 可以朝它所在的那一侧滑动,如果不是居中,还可以朝它对齐的那一端滑动。
<script lang="ts">
import { onDestroy } from "svelte"
import { CheckIcon, ChevronDownIcon } from "@lucide/svelte"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@ui-sdk/svelte/select"
import {
Toast,
ToastDescription,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
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()
let side = $state<Side>("bottom")
let align = $state<Align>("end")
onDestroy(() => {
toast.dismiss()
})
</script>
<div data-slot="stack">
<div data-slot="controls">
<Select
items={sides}
value={side}
onValueChange={(next) => next && (side = next as Side)}
>
<SelectLabel>Side</SelectLabel>
<SelectTrigger>
<SelectValue />
<ChevronDownIcon aria-hidden="true" />
</SelectTrigger>
<SelectContent>
{#each sides as option (option.value)}
<SelectItem value={option.value}>
{option.label}
<SelectItemIndicator>
<CheckIcon aria-hidden="true" />
</SelectItemIndicator>
</SelectItem>
{/each}
</SelectContent>
</Select>
<Select
items={aligns}
value={align}
onValueChange={(next) => next && (align = next as Align)}
>
<SelectLabel>Align</SelectLabel>
<SelectTrigger>
<SelectValue />
<ChevronDownIcon aria-hidden="true" />
</SelectTrigger>
<SelectContent>
{#each aligns as option (option.value)}
<SelectItem value={option.value}>
{option.label}
<SelectItemIndicator>
<CheckIcon aria-hidden="true" />
</SelectItemIndicator>
</SelectItem>
{/each}
</SelectContent>
</Select>
</div>
<button
onclick={() =>
toast("Event created", { description: "Friday, June 12 at 10:00 AM" })}
>
Create Event
</button>
<ToastRegion toaster={toast} {side} {align}>
<Toast>
<div data-slot="stack">
<ToastTitle />
<ToastDescription />
</div>
</Toast>
</ToastRegion>
</div>动作与取消
添加一个 action,比如 Undo,以及一个关闭 toast 的 cancel 按钮。它们的回调可以更新你的应用。onDismiss 告诉你 toast 为什么关闭,details.cancel() 让它保持打开;被取消的超时会重新开始倒计时。
<script lang="ts">
import { onDestroy } from "svelte"
import {
Toast,
ToastAction,
ToastClose,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
import { useLog } from "./log"
const log = useLog()
const toast = createToaster()
onDestroy(() => {
toast.dismiss()
})
</script>
<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}>
{#snippet children(item)}
<Toast>
<ToastTitle />
{#if item.cancel}
<ToastClose action={item.cancel.onCancel}
>{item.cancel.label}</ToastClose
>
{/if}
<ToastAction data-variant="solid" />
</Toast>
{/snippet}
</ToastRegion>链接
给动作一个 href,把它渲染成链接。它保留正常的链接行为,包括在新标签页中打开。
<script lang="ts">
import { onDestroy } from "svelte"
import {
Toast,
ToastAction,
ToastDescription,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
const toast = createToaster()
onDestroy(() => {
toast.dismiss()
})
</script>
<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>Promise
toast.promise() 先显示一个加载中的 toast,然后在 promise 兑现或拒绝时更新同一个 toast。每条消息可以是字符串、带描述或动作的选项,或者结果的函数。加载期间被关闭的 toast 会保持关闭。
<script lang="ts">
import { onDestroy } from "svelte"
import {
Toast,
ToastAction,
ToastDescription,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
const toast = createToaster()
let attempts = 0
onDestroy(() => {
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>
<button onclick={saveChanges}>Save Changes</button>
<ToastRegion toaster={toast}>
<Toast>
<div data-slot="stack">
<ToastTitle />
<ToastDescription />
</div>
<ToastAction data-variant="solid" />
</Toast>
</ToastRegion>堆叠
maxVisible 限制一次显示多少个 toast,默认三个;其余的留在队列里等待,显示时计时器才开始。指针或焦点在堆叠中时,堆叠会展开。设置 expanded 让它保持展开。样式展示了布局这个堆叠的 CSS。
<script lang="ts">
import { onDestroy } from "svelte"
import { CheckIcon } from "@lucide/svelte"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/svelte/checkbox"
import {
Toast,
ToastDescription,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
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()
let expanded = $state(false)
let count = 0
onDestroy(() => {
toast.dismiss()
})
</script>
<div data-slot="stack">
<div data-slot="controls">
<label data-slot="label">
<Checkbox
checked={expanded}
onCheckedChange={(next) => (expanded = next === true)}
>
<CheckboxIndicator>
<CheckIcon aria-hidden="true" />
</CheckboxIndicator>
</Checkbox>
Always expanded
</label>
</div>
<button onclick={() => toast(notifications[count++ % notifications.length])}
>Add Toast</button
>
<ToastRegion toaster={toast} maxVisible={4} {expanded}>
<Toast>
<div data-slot="stack">
<ToastTitle />
<ToastDescription />
</div>
</Toast>
</ToastRegion>
</div>时长
duration 以毫秒为单位,可以设在 toaster 上,也可以设在单个 toast 上;用 Infinity 让 toast 一直保留到被关闭。默认是五秒。指针或焦点在区域中时,以及页面隐藏或窗口不活跃时,计时器会暂停。
<script lang="ts">
import { onDestroy } from "svelte"
import {
Toast,
ToastClose,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
const toast = createToaster()
onDestroy(() => {
toast.dismiss()
})
</script>
<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}>
{#snippet children(item)}
<Toast>
<ToastTitle />
{#if item.cancel}
<ToastClose data-variant="solid" action={item.cancel.onCancel}>
{item.cancel.label}
</ToastClose>
{/if}
</Toast>
{/snippet}
</ToastRegion>更新与关闭
保留 toast() 返回的 id,用来更新或关闭那个 toast,或者传入你自己的 id。toast.update() 返回 toast 是否还在,不带 id 的 toast.dismiss() 会关闭每一个 toast。
<script lang="ts">
import { onDestroy } from "svelte"
import { CircleCheckIcon, LoaderCircleIcon } from "@lucide/svelte"
import {
Toast,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
import { useLog } from "./log"
const log = useLog()
const toast = createToaster()
let timer: ReturnType<typeof setInterval> | undefined
onDestroy(() => {
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>
<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>异步动作
从动作返回一个 promise,让 toast 在它运行期间保持打开。动作的状态在运行期间带有 pending,失败时带有 error,所以按钮可以显示 Restoring… 或提供重试,在动作结束之前按压会被忽略。await 之后所做的变更见 Button。
<script lang="ts">
import { onDestroy } from "svelte"
import {
Toast,
ToastAction,
ToastDescription,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
import { useLog } from "./log"
function restore() {
return new Promise((resolve) => setTimeout(resolve, 1500))
}
const log = useLog()
const toast = createToaster({ duration: 6000 })
onDestroy(() => {
toast.dismiss()
})
</script>
<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">
{#snippet children(state)}
{state.pending ? "Restoring…" : state.error ? "Retry" : "Undo"}
{/snippet}
</ToastAction>
</Toast>
</ToastRegion>键盘快捷键
F6 把焦点移到最新的 toast,再移回来。设置区域的 shortcut 可以使用其他按键,设为 null 则关闭它。区域通过 aria-keyshortcuts 声明它。
<script lang="ts">
import { onDestroy } from "svelte"
import {
Toast,
ToastAction,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
import { useLog } from "./log"
const log = useLog()
const toast = createToaster({ duration: 10000 })
onDestroy(() => {
toast.dismiss()
})
</script>
<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>浮层宿主与确认框
除了放置区域,也可以在应用的根节点附近渲染一次 OverlayHost。它渲染 toaster 的区域,使用你给它的 toast.children snippet,并把 confirm() 问题渲染成警告对话框。对于同一个 toaster,你自己放置的区域会取代宿主。
要给问题设置样式,用 confirm 控制器渲染一个 AlertDialog,并从它内容的 payload 读取问题。Alert Dialog更详细地介绍了 createConfirm()。
<script lang="ts">
import { onDestroy } from "svelte"
import { CircleCheckIcon } from "@lucide/svelte"
import {
AlertDialog,
AlertDialogBackdrop,
AlertDialogClose,
AlertDialogContent,
AlertDialogDescription,
AlertDialogTitle,
createConfirm,
type ConfirmOptions,
} from "@ui-sdk/svelte/alert-dialog"
import type { DialogContentState } from "@ui-sdk/svelte/dialog"
import { OverlayHost, createOverlays } from "@ui-sdk/svelte/overlays"
import { Toast, ToastTitle, createToaster } from "@ui-sdk/svelte/toast"
const overlays = createOverlays()
const toast = createToaster({ overlays })
const confirm = createConfirm({ overlays })
let projects = $state(["Acme", "Globex", "Initech"])
let reset: HTMLButtonElement
onDestroy(() => {
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)?.focus()
projects = projects.filter((project) => project !== name)
toast.success(`${name} deleted`, { priority: "assertive" })
}
</script>
{#snippet toastItem()}
<Toast>
<CircleCheckIcon data-show="success" aria-hidden="true" />
<ToastTitle />
</Toast>
{/snippet}
<div data-slot="stack">
<div data-slot="controls">
<button
type="button"
bind:this={reset}
onclick={() => (projects = ["Acme", "Globex", "Initech"])}
>
Reset Projects
</button>
</div>
<ul data-slot="list" aria-label="Projects">
{#each projects as name (name)}
<li data-slot="row">
{name}
<button
type="button"
data-size="sm"
aria-label={`Delete ${name}`}
onclick={(event) => remove(name, event.currentTarget)}
>
Delete
</button>
</li>
{:else}
<li data-slot="row">All projects deleted.</li>
{/each}
</ul>
<OverlayHost {overlays} toast={{ children: toastItem }} />
<AlertDialog controller={confirm.controller}>
<AlertDialogBackdrop />
<AlertDialogContent>
{#snippet children(state: DialogContentState<ConfirmOptions>)}
<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>
{/snippet}
</AlertDialogContent>
</AlertDialog>
</div>自定义渲染
把 toast 需要的其他内容放在 data 里传入,并从区域 children snippet 收到的 toast 中读取它。每个部件也接受 render snippet;这个示例自己渲染每个 toast 的 li,并把折叠堆叠后面隐藏的那些设为不可交互(inert)。
<script lang="ts">
import { onDestroy } from "svelte"
import { XIcon } from "@lucide/svelte"
import {
Toast,
ToastAction,
ToastClose,
ToastDescription,
ToastRegion,
ToastTitle,
createToaster,
} from "@ui-sdk/svelte/toast"
import { useLog } from "./log"
const log = useLog()
const toast = createToaster()
onDestroy(() => {
toast.dismiss()
})
</script>
<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">
{#snippet children(item)}
<Toast>
{#snippet render({ props, state, children })}
<li
{...props}
inert={state.leaving ||
(!state.expanded && state.index > 0) ||
undefined}
>
{@render children?.(state)}
</li>
{/snippet}
<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>
{/snippet}
</ToastRegion>样式
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-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 | topbottomThe edge of the viewport the region sits on. |
data-align | startcenterendWhere 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 | defaultsuccesserrorinfowarningloadingWhat 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.
Infinitykeeps 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.sourcesays how it was pressed, for changes made after anawait. 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.sourcesays 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".nullturns 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.sourcesays how it was pressed, for changes made after anawait. 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.sourcesays how it was pressed, for changes made after anawait.
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
actionfinished. imperativenone- A controller or
apicall.
无障碍
toast 通过共享的实时区域(live region)播报,每个只播报一次,而不把可见区域本身变成实时区域:默认礼貌播报,错误时即时(assertive)播报。区域里有 toast 时,它是一个名为 Notifications 的地标;设置 aria-label 可以用页面语言为它命名。让消息保持简短,对于必须一直可用的消息,使用 duration: Infinity。
键盘
F6 或区域的 shortcut 把焦点移到最新的 toast,再次按压会把焦点送回它来的地方。Tab 在 toast 和它们的按钮之间移动,越过最后一个再按 Tab 也会回到原处。Escape 关闭当前聚焦的 toast;焦点随后移到下一个 toast,如果已是最后一个,则回到它来的地方。模态对话框打开时区域仍然可达,焦点在内部时它的计时器会暂停。
经过测试的行为
下面每一行都是一个自动化测试。
- 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.
- 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.
- Hovering the region pauses its timers, and leaving resumes them.
- Focus in the region pauses its timers.
- 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.
- 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 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.
- 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.
- A promise toast dismissed while loading stays closed.
- An update after a toast closed never brings it back.
- 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。
还测试了:
- 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.
- A hidden page pauses timers.
- Pause reasons hold separately: getting the window back doesn't resume while focus is in the region.
- 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.
- 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.
- 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.
- 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。