打开一个悬浮在页面之上的专注任务。
对话框给任务一块自己的空间:分享链接、编辑一条记录,或者收集几项信息。它负责焦点、Escape、外部按压,以及回到你开始的地方。
<script lang="ts">
import { XIcon } from "@lucide/svelte"
import {
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import { Input } from "@ui-sdk/svelte/input"
</script>
<Dialog>
<DialogTrigger>Share</DialogTrigger>
<DialogBackdrop />
<DialogContent>
<div data-slot="stack">
<DialogTitle>Share link</DialogTitle>
<DialogDescription
>Anyone who has this link will be able to view this.</DialogDescription
>
</div>
<Field>
<FieldLabel>Link</FieldLabel>
<Input defaultValue="https://example.com/project" readonly />
</Field>
<div data-slot="row">
<DialogClose data-variant="solid">Done</DialogClose>
</div>
<DialogClose aria-label="Close">
<XIcon aria-hidden="true" />
</DialogClose>
</DialogContent>
</Dialog>安装
npm install @ui-sdk/svelte @ui-sdk/core组合
用下面的组合构建一个 Dialog:
Dialog
├── DialogTrigger
├── DialogBackdrop
└── DialogContent
├── DialogTitle
├── DialogDescription
└── DialogClose标题为对话框命名,描述给它上下文。一个对话框可以有多个 Close 部件。给只有图标的关闭按钮一个无障碍名称,就像第一个示例那样。
backdrop 部件是可选的。没有它时,为内容的 ::backdrop 设置样式。如果一个问题需要用户明确作答,改用 Alert Dialog。
用法
导入各个部件并把它们组合起来:
<script lang="ts">
import {
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
</script>
<Dialog>
<DialogTrigger>Open</DialogTrigger>
<DialogBackdrop />
<DialogContent>
<DialogTitle>Project details</DialogTitle>
<DialogDescription>Review the details before continuing.</DialogDescription>
<DialogClose>Close</DialogClose>
</DialogContent>
</Dialog>自己构建
@ui-sdk/svelte/dialog 自带一个现成的 Dialog。如果你想用自己的名字构建自己的版本,从 @ui-sdk/core 里的 dialog 原语(primitive)开始:
import { dialog } from "@ui-sdk/core/dialog"
import { createParts } from "@ui-sdk/svelte/primitive"
const {
Root: Share,
Trigger: ShareTrigger,
Backdrop: ShareBackdrop,
Content: SharePanel,
Title: ShareTitle,
Description: ShareDescription,
Close: ShareClose,
} = createParts(dialog, {
trigger: "button",
backdrop: "div",
content: "div",
title: "h2",
description: "p",
close: "button",
})
export {
Share,
ShareBackdrop,
ShareClose,
ShareDescription,
SharePanel,
ShareTitle,
ShareTrigger,
}<Share>
<ShareTrigger>Share</ShareTrigger>
<ShareBackdrop />
<SharePanel>
<ShareTitle>Share this page</ShareTitle>
<ShareDescription>Anyone with the link can view it.</ShareDescription>
<ShareClose>Done</ShareClose>
</SharePanel>
</Share>每个部件都保留其现成对应部件的行为、状态和数据属性:内容在顶层(top layer)打开,把焦点困在内部,并让页面不可交互(inert)。更多内容见渲染和自定义部件。
可滚动内容
把标题和操作按钮留在滚动区域之外。限制视口高度、让中间的网格行收缩,再加上 overflow-y: auto,长内容就仍然可用。initialFocus="content" 把焦点放在对话框本身,这样阅读从顶部开始。
<script lang="ts">
import {
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
const paragraphs = [
"These terms govern your use of the service. By creating an account, you agree to them and to the privacy policy that explains how we handle your data.",
"You're responsible for the content you upload and for keeping your password safe. Tell us right away if you think someone else has used your account.",
"We may change the service, and these terms, as the product grows. When a change affects you, we'll let you know by email at least 30 days before it takes effect.",
"You can stop using the service at any time. We'll keep your data for 30 days after you close your account, so you can export it, and then delete it.",
"The service is provided as is. To the extent the law allows, we aren't liable for indirect damages, lost profits or lost data.",
"If you have questions about these terms, write to us. We read every message and reply within two working days.",
]
</script>
<Dialog>
<DialogTrigger>Scrollable Content</DialogTrigger>
<DialogBackdrop />
<DialogContent initialFocus="content">
<div data-slot="stack">
<DialogTitle>Terms of service</DialogTitle>
<DialogDescription>Please read before you continue.</DialogDescription>
</div>
<div data-slot="scroll">
{#each paragraphs as paragraph (paragraph)}
<p>{paragraph}</p>
{/each}
</div>
<div data-slot="row">
<DialogClose>Decline</DialogClose>
<DialogClose data-variant="solid" value="accept">Accept</DialogClose>
</div>
</DialogContent>
</Dialog>表单
method="dialog" 的表单在有效提交时关闭对话框。提交按钮的 value 会成为 returnValue,就像 Close 部件的 value 一样。普通表单会保持打开,直到你自己关闭对话框。
<script lang="ts">
import {
Dialog,
DialogBackdrop,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import { Input } from "@ui-sdk/svelte/input"
import { useLog } from "./log"
const log = useLog()
</script>
<Dialog
onOpenChange={(open, details) => {
if (!open) {
log(
details.returnValue
? `Saved as ${details.returnValue}`
: `Closed (${details.reason})`
)
}
}}
>
<DialogTrigger>New Article</DialogTrigger>
<DialogBackdrop />
<DialogContent>
<div data-slot="stack">
<DialogTitle>New article</DialogTitle>
<DialogDescription
>Save it as a draft or publish it now.</DialogDescription
>
</div>
<form data-slot="stack" method="dialog">
<Field>
<FieldLabel>Title</FieldLabel>
<Input required defaultValue="Shipping updates for spring" />
</Field>
<div data-slot="row">
<button type="submit" value="draft">Save Draft</button>
<button data-variant="solid" type="submit" value="published"
>Publish</button
>
</div>
</form>
</DialogContent>
</Dialog>焦点
用 initialFocus 选择焦点从哪里开始,用 finalFocus 选择关闭后焦点去哪里。两者都接受一个选择器、一个元素,或一个返回它们的函数。默认回到触发器,或者回到在控制器打开对话框之前聚焦的元素。共用的焦点规则见浮层焦点。
<DialogContent initialFocus="#invite-email" finalFocus={() => nextStep} />受控
用 bind:open 把对话框的状态保留在你的组件里。在 onOpenChange 中用 details.cancel() 取消一次提议的变更。onOpenChangeComplete 报告打开或关闭何时完成;通用的变更约定见状态与事件。
<script lang="ts">
import { CheckIcon } from "@lucide/svelte"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/svelte/checkbox"
import {
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
import { useLog } from "./log"
const topics = [
{ label: "Product updates", checked: true },
{ label: "Security alerts", checked: true },
{ label: "Weekly digest", checked: false },
]
const log = useLog()
let open = $state(false)
</script>
<div data-slot="stack">
<div data-slot="controls">
<label data-slot="label">
<Checkbox
checked={open}
onCheckedChange={(next) => (open = next === true)}
>
<CheckboxIndicator>
<CheckIcon aria-hidden="true" />
</CheckboxIndicator>
</Checkbox>
Open
</label>
</div>
<Dialog
bind:open
onOpenChange={(next, details) =>
log(`${next ? "Opened" : "Closed"} (${details.reason})`)}
onOpenChangeComplete={(next) =>
log(next ? "Finished opening" : "Finished closing")}
>
<DialogTrigger>Notification Settings</DialogTrigger>
<DialogBackdrop />
<DialogContent>
<div data-slot="stack">
<DialogTitle>Notification settings</DialogTitle>
<DialogDescription>Choose what we email you about.</DialogDescription>
</div>
<div data-slot="stack">
{#each topics as topic (topic.label)}
<label data-slot="label">
<Checkbox defaultChecked={topic.checked}>
<CheckboxIndicator>
<CheckIcon aria-hidden="true" />
</CheckboxIndicator>
</Checkbox>
{topic.label}
</label>
{/each}
</div>
<div data-slot="row">
<DialogClose data-variant="solid">Done</DialogClose>
</div>
</DialogContent>
</Dialog>
</div>键盘快捷键
触发器的 shortcut 让它能从键盘打开。mod+j 在 Apple 平台上表示 Command+J,在其他平台表示 Control+J。Shortcut 部件显示对应的按键,触发器暴露 aria-keyshortcuts。
<script lang="ts">
import { PlusIcon } from "@lucide/svelte"
import {
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogShortcut,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import { Input } from "@ui-sdk/svelte/input"
</script>
<Dialog>
<DialogTrigger shortcut="mod+j">
<PlusIcon aria-hidden="true" />
New Contact
<DialogShortcut />
</DialogTrigger>
<DialogBackdrop />
<DialogContent>
<div data-slot="stack">
<DialogTitle>New contact</DialogTitle>
<DialogDescription>Add someone to your address book.</DialogDescription>
</div>
<form data-slot="stack" method="dialog">
<Field>
<FieldLabel>Name</FieldLabel>
<Input name="name" required placeholder="Kofi Mensah" />
</Field>
<Field>
<FieldLabel>Email</FieldLabel>
<Input
name="email"
type="email"
required
placeholder="kofi@example.com"
/>
</Field>
<div data-slot="row">
<DialogClose>Cancel</DialogClose>
<button data-variant="solid" type="submit" value="save"
>Save Contact</button
>
</div>
</form>
</DialogContent>
</Dialog>动画
内容和 backdrop 部件在打开期间带有 data-starting-style,关闭期间带有 data-ending-style。从这些状态做过渡,对话框会保持挂载,直到退场结束。onOpenChangeComplete 在过渡之后运行,keepMounted 让内容在关闭期间留在页面里。
[data-slot="dialog-content"] {
transition:
opacity 0.2s,
translate 0.25s cubic-bezier(0.22, 1, 0.36, 1),
scale 0.25s cubic-bezier(0.22, 1, 0.36, 1);
&:is([data-starting-style], [data-ending-style]) {
opacity: 0;
translate: 0 16px;
scale: 0.96;
}
&[data-ending-style] {
transition-duration: 0.15s;
}
}<script lang="ts">
import {
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
import { useLog } from "./log"
const log = useLog()
</script>
<Dialog
onOpenChangeComplete={(open) =>
log(open ? "Finished opening" : "Finished closing")}
>
<DialogTrigger>Slide In</DialogTrigger>
<DialogBackdrop />
<DialogContent keepMounted>
<div data-slot="stack">
<DialogTitle>Slide and fade</DialogTitle>
<DialogDescription
>300ms in and out. Focus returns as soon as it starts closing.</DialogDescription
>
</div>
<div data-slot="row">
<DialogClose data-variant="solid">Close</DialogClose>
</div>
</DialogContent>
</Dialog>模态
modal 控制对话框如何与页面共享空间:
true是默认值,让页面不可交互、锁定滚动,并把 Tab 保持在内部。"trap-focus"把 Tab 保持在内部,同时页面仍然可以滚动和接受点击。点击页面也会关闭对话框,除非closeOnOutsidePress为 false。false让对话框与页面并排,焦点可以离开它。焦点在内部时 Escape 会关闭它;只有启用closeOnOutsidePress时,外部按压才会关闭它。
如果想在模态对话框打开时让页面的一小块区域保持可用,比如聊天启动器,就把它传给 persistentElements:一个元素或选择器的数组,或者一个在对话框打开时返回元素的函数。这些元素本身不会改变堆叠顺序。
对话框渲染在你放置它们的位置,并使用浏览器的顶层。如果它们的 DOM 需要放在别处,比如影子根(shadow root),就设置 container。浮层指南涵盖容器和 iframe。
<script lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/svelte"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/svelte/checkbox"
import {
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@ui-sdk/svelte/select"
const modes = [
{ value: "true", label: "Modal" },
{ value: "trap-focus", label: "Trap focus" },
{ value: "false", label: "Non-modal" },
]
type Mode = "true" | "trap-focus" | "false"
const notes = {
true: "The rest of the page is inert and doesn't scroll.",
"trap-focus":
"Tab stays inside, and the page still scrolls and takes clicks.",
false:
"The page stays usable. Tab leaves the notes, and Escape closes them while focus is inside.",
}
let mode = $state<Mode>("false")
let outside = $state(false)
const modal = $derived(
mode === "true" ? true : mode === "false" ? false : "trap-focus"
)
</script>
<div data-slot="stack">
<div data-slot="controls">
<Select
items={modes}
value={mode}
onValueChange={(next) => next && (mode = next as Mode)}
>
<SelectLabel>Modal</SelectLabel>
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{#each modes as option (option.value)}
<SelectItem value={option.value}>
{option.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
{/each}
</SelectContent>
</Select>
<label data-slot="label">
<Checkbox
checked={outside}
onCheckedChange={(next) => (outside = next === true)}
>
<CheckboxIndicator>
<CheckIcon aria-hidden="true" />
</CheckboxIndicator>
</Checkbox>
Close on outside press
</label>
</div>
<Dialog {modal} closeOnOutsidePress={outside}>
<DialogTrigger>Open Notes</DialogTrigger>
{#if modal === true}
<DialogBackdrop />
{/if}
<DialogContent>
<div data-slot="stack">
<DialogTitle>Notes</DialogTitle>
<DialogDescription>{notes[mode]}</DialogDescription>
</div>
<textarea aria-label="Notes" value="Call the printer about the proofs."
></textarea>
<div data-slot="row">
<DialogClose data-variant="solid">Done</DialogClose>
</div>
</DialogContent>
</Dialog>
</div>在 frame 内
对话框会打开在整个页面上方。给内容设置 inline,让它和它的 backdrop 部件留在页面中的原位,比如应用预览内部。由你的 CSS 在 frame 中为它们设置尺寸和位置。把它和 modal="trap-focus" 搭配,frame 周围的页面仍然可用。
<script lang="ts">
import {
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
</script>
<div data-slot="dialog-frame">
<Dialog modal="trap-focus" closeOnOutsidePress={false}>
<DialogTrigger>Delete Draft</DialogTrigger>
<DialogBackdrop />
<DialogContent inline>
<div data-slot="stack">
<DialogTitle>Delete this draft?</DialogTitle>
<DialogDescription
>The preview keeps its dialog inside the frame.</DialogDescription
>
</div>
<div data-slot="row">
<DialogClose>Cancel</DialogClose>
<DialogClose data-variant="destructive">Delete</DialogClose>
</div>
</DialogContent>
</Dialog>
</div>关闭有未保存更改的表单前警告
有未保存的更改时,把 dismissible 设为 false。这时 Escape、外部按压或返回手势都会让对话框保持打开,并报告 onDismissAttempt。显式的 Close 部件和控制器调用仍然有效,所以你可以提供一条明确的退出途径。
<script lang="ts">
import {
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
import { Field, FieldControl, FieldLabel } from "@ui-sdk/svelte/field"
let open = $state(false)
let dirty = $state(false)
let asking = $state(false)
let post: HTMLTextAreaElement | undefined = $state()
function close() {
open = false
dirty = false
asking = false
}
function keepEditing() {
asking = false
post?.focus()
}
</script>
<Dialog
bind:open={() => open, (next) => (next ? (open = true) : close())}
dismissible={!dirty}
onDismissAttempt={() => (asking = true)}
>
<DialogTrigger>Write a Post</DialogTrigger>
<DialogBackdrop />
<DialogContent>
<div data-slot="stack">
<DialogTitle>New post</DialogTitle>
<DialogDescription>Share an update with your team.</DialogDescription>
</div>
<Field>
<FieldLabel>Post</FieldLabel>
<FieldControl
oninput={(event) => (dirty = event.currentTarget.value !== "")}
>
{#snippet render({ props })}
<textarea bind:this={post} {...props} placeholder="What's new?"
></textarea>
{/snippet}
</FieldControl>
</Field>
{#if asking}
<div data-slot="row" role="alert">
Discard your changes?
<div data-slot="row">
<button type="button" onclick={keepEditing}>Keep Editing</button>
<button data-variant="solid" type="button" onclick={close}
>Discard</button
>
</div>
</div>
{:else}
<div data-slot="row">
<DialogClose data-variant="solid" value="post">Post</DialogClose>
</div>
{/if}
</DialogContent>
</Dialog>嵌套对话框
在另一个对话框里打开的对话框会加入它的栈。Escape 关闭最上层的对话框,并把焦点还给它的触发器。关闭父级也会关闭它的子级。data-nested-open 和 --dialog-stack 让你显示哪一层处于活动状态。
<script lang="ts">
import {
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import { Input } from "@ui-sdk/svelte/input"
</script>
<Dialog>
<DialogTrigger>Account</DialogTrigger>
<DialogBackdrop />
<DialogContent>
<div data-slot="stack">
<DialogTitle>Account</DialogTitle>
<DialogDescription>Manage how you sign in.</DialogDescription>
</div>
<div data-slot="card">
<div data-slot="stack">
<span>Password</span>
<span data-slot="hint">Last changed 3 months ago</span>
</div>
<Dialog>
<DialogTrigger>Change Password</DialogTrigger>
<DialogBackdrop />
<DialogContent>
<div data-slot="stack">
<DialogTitle>Change password</DialogTitle>
<DialogDescription>Use at least 12 characters.</DialogDescription>
</div>
<Field>
<FieldLabel>New password</FieldLabel>
<Input type="password" />
</Field>
<div data-slot="row">
<DialogClose>Cancel</DialogClose>
<DialogClose data-variant="solid">Update</DialogClose>
</div>
</DialogContent>
</Dialog>
</div>
<div data-slot="row">
<DialogClose data-variant="solid">Done</DialogClose>
</div>
</DialogContent>
</Dialog>从菜单项打开
把对话框渲染在菜单之外,用对话框的控制器打开它。当菜单项消失时,菜单的触发器就成为焦点返回的位置。
<script lang="ts">
import { CopyIcon, EllipsisIcon, PencilIcon } from "@lucide/svelte"
import {
createDialogController,
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
} from "@ui-sdk/svelte/dialog"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import { Input } from "@ui-sdk/svelte/input"
import { Menu, MenuContent, MenuItem, MenuTrigger } from "@ui-sdk/svelte/menu"
const rename = createDialogController()
</script>
<Menu>
<MenuTrigger aria-label="File actions">
<EllipsisIcon aria-hidden="true" />
</MenuTrigger>
<MenuContent>
<MenuItem onSelect={() => rename.open()}>
<PencilIcon aria-hidden="true" />
Rename…
</MenuItem>
<MenuItem>
<CopyIcon aria-hidden="true" />
Duplicate
</MenuItem>
</MenuContent>
</Menu>
<Dialog controller={rename}>
<DialogBackdrop />
<DialogContent>
<div data-slot="stack">
<DialogTitle>Rename file</DialogTitle>
<DialogDescription>Names must be unique in a folder.</DialogDescription>
</div>
<Field>
<FieldLabel>Name</FieldLabel>
<Input defaultValue="report.pdf" />
</Field>
<div data-slot="row">
<DialogClose>Cancel</DialogClose>
<DialogClose data-variant="solid" value="rename">Rename</DialogClose>
</div>
</DialogContent>
</Dialog>从任意位置打开
把多个触发器连接到同一个 createDialogController<Payload, Result>()。每个触发器传一个 payload;内容的 children 片段从 state.payload 读取它,用 DialogContentState<Payload> 标注类型。controller.open({ payload }) 从代码打开对话框,返回一个在关闭时兑现的 promise,带着原因和可选的 returnValue。每个触发器仍然是它打开的那个对话框的焦点返回目标。共用的控制器模式见控制器。
<script lang="ts">
import {
createDialogController,
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
type DialogContentState,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
import { useLog } from "./log"
type Invoice = {
id: string
customer: string
amount: string
status: "Paid" | "Due"
}
const invoices: Invoice[] = [
{ id: "INV-001", customer: "Acme", amount: "$250.00", status: "Paid" },
{ id: "INV-002", customer: "Globex", amount: "$150.00", status: "Due" },
{ id: "INV-003", customer: "Initech", amount: "$350.00", status: "Due" },
]
const reminder = createDialogController<Invoice, "send">()
const log = useLog()
async function remindFromCode() {
const { reason, returnValue } = await reminder.open({
payload: invoices[2],
})
log(
returnValue === "send" ? "Reminder sent from code" : `Closed (${reason})`
)
}
</script>
<div data-slot="stack">
<div data-slot="controls">
<button type="button" onclick={remindFromCode}>Open from Code</button>
</div>
<ul data-slot="list">
{#each invoices as invoice (invoice.id)}
<li data-slot="row">
{invoice.customer}
<span data-slot="hint">{invoice.amount} · {invoice.status}</span>
<DialogTrigger
controller={reminder}
payload={invoice}
disabled={invoice.status === "Paid"}
aria-label={`Remind ${invoice.customer}`}
>
Remind
</DialogTrigger>
</li>
{/each}
</ul>
<Dialog
controller={reminder}
onOpenChange={(open, details) => {
if (!open && details.returnValue === "send") {
log("Reminder sent")
}
}}
>
<DialogBackdrop />
<DialogContent>
{#snippet children(state: DialogContentState<Invoice>)}
<div data-slot="stack">
<DialogTitle>Remind {state.payload?.customer}</DialogTitle>
<DialogDescription>
{state.payload?.id} for {state.payload?.amount} is due. We'll email the
billing contact.
</DialogDescription>
</div>
<div data-slot="row">
<DialogClose>Cancel</DialogClose>
<DialogClose data-variant="solid" value="send"
>Send reminder</DialogClose
>
</div>
{/snippet}
</DialogContent>
</Dialog>
</div>呈现方式
presentation="sheet" 把同一个任务呈现为底部面板(sheet)。用 "auto" 会在小尺寸触摸屏上选择 sheet,其他情况下使用居中的对话框,每次打开时决定。向下滑动会关闭可关闭的 sheet;受保护的 sheet 会弹回,并报告一次关闭尝试。
设置 data-presentation 的样式来同时支持两种布局。sheet 自己管理位置和移动,所以不要给它套用居中对话框的位移。没有 Backdrop 部件时,--sheet-backdrop 为变暗的页面设置样式。
<script lang="ts">
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import { Input } from "@ui-sdk/svelte/input"
</script>
<Dialog presentation="sheet">
<DialogTrigger>Edit Profile</DialogTrigger>
<DialogContent>
<div data-slot="stack">
<DialogTitle>Edit profile</DialogTitle>
<DialogDescription
>Make changes to your profile here. Save when you're done.</DialogDescription
>
</div>
<Field>
<FieldLabel>Name</FieldLabel>
<Input defaultValue="Hollis Grant" />
</Field>
<Field>
<FieldLabel>Username</FieldLabel>
<Input defaultValue="@hollis" />
</Field>
<div data-slot="row">
<DialogClose>Cancel</DialogClose>
<DialogClose data-variant="solid" value="save">Save Changes</DialogClose>
</div>
</DialogContent>
</Dialog>自定义渲染
每个部件都接受一个 render 片段,接收要展开的属性(props)和部件的状态;children 片段也会收到状态。
<script lang="ts">
import {
Dialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogShortcut,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/svelte/dialog"
</script>
<Dialog>
<DialogTrigger shortcut="mod+i">
{#snippet render({ props, state })}
<button {...props}>
{state.open ? "Viewing" : "View Details"}
<DialogShortcut>
{#snippet children(shortcut)}{shortcut.text}{/snippet}
</DialogShortcut>
</button>
{/snippet}
</DialogTrigger>
<DialogBackdrop />
<DialogContent>
{#snippet children(state)}
<div data-slot="stack">
<DialogTitle>
{#snippet render({ props })}
<h3 {...props}>Details</h3>
{/snippet}
</DialogTitle>
<DialogDescription>
{state.nested
? "Opened from another dialog."
: "Quarterly report, updated today."}
</DialogDescription>
</div>
<div data-slot="row">
<DialogClose>Close</DialogClose>
<DialogClose data-variant="solid" href="https://example.com/details">
{#snippet render({ props })}
<a {...props}>Open the Full Page</a>
{/snippet}
</DialogClose>
</div>
{/snippet}
</DialogContent>
</Dialog>样式
每个部件都有一个 data-slot,比如 dialog-content,并通过数据属性下列出的属性展示状态。用 data-open 和 data-closed 表示每种状态,用 data-starting-style 和 data-ending-style 表示过渡。
DialogContent
| 变量 | 内容 |
|---|---|
--dialog-stack | How many dialogs are open above this one, nested inside it. 0 for the topmost. |
--keyboard-inset | Unless it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one. |
--visual-viewport-width | Unless it presents as a sheet: the width of the part of the page you can see. |
--visual-viewport-height | Unless it presents as a sheet: the height of the part of the page you can see, above the keyboard. |
--visual-viewport-top | Unless it presents as a sheet: 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. |
--drawer-progress | While it presents as a sheet: how far open the sheet is, from 0 closed to 1 at its largest snap point. Never past 1. |
--drawer-dim | While it presents as a sheet: how dim the page behind is, from 0 to 1. The backdrop's opacity follows it. |
--drawer-expand | While it presents as a sheet: 0 at the second-largest snap point and below, 1 at the largest. With one snap point, the whole travel. |
--drawer-stack | While it presents as a sheet: how many sheets opened from inside this one are open above it, rising smoothly as each one opens. Push it back with it. |
--sheet-backdrop | Set it yourself: the color the page dims to while it presents as a sheet. Black at 0.2 by default. |
Viewport
| 变量 | 内容 |
|---|---|
--keyboard-inset | While it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one. |
--visual-viewport-width | While it presents as a sheet: the width of the part of the page you can see. |
--visual-viewport-height | While it presents as a sheet: the height of the part of the page you can see, above the keyboard. |
--visual-viewport-top | While it presents as a sheet: 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. |
数据属性
DialogTrigger
[data-slot="dialog-trigger"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the dialog is closed, including while it animates out. |
data-disabled | Present when the trigger is disabled. |
data-open | Present while the dialog is open. On a trigger, while it's open from that trigger. |
DialogBackdrop
[data-slot="dialog-backdrop"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the dialog is closed, including while it animates out. |
data-open | Present while the dialog is open. On a trigger, while it's open from that trigger. |
data-starting-style | Present for the first frame. Style the state you animate from. |
data-ending-style | Present while the dialog animates out. Style the state you animate to. |
DialogContent
[data-slot="dialog-content"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the dialog is closed, including while it animates out. |
data-presentation | dialogsheetHow the dialog presents this time it's open. |
data-open | Present while the dialog is open. On a trigger, while it's open from that trigger. |
data-starting-style | Present for the first frame. Style the state you animate from. |
data-ending-style | Present while the dialog animates out. Style the state you animate to. |
data-keyboard | Present while the on-screen keyboard covers part of the page. |
DialogClose
[data-slot="dialog-close"]
| 属性 | 含义 |
|---|---|
data-disabled | |
data-pending | Present on a Close part while its action runs. |
API 参考
属性和回调与下面相同,都作为 Svelte props。open 可以用 bind:open 绑定。
Dialog
container?DocumentFragment | Element | null- Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
open?boolean- Whether the dialog is open. Pass it to control the dialog.
defaultOpen?boolean- Whether the dialog starts open, when uncontrolled. Focus moves into it once it's on the page.
onOpenChangeComplete?((open: boolean) => void)- Runs once the dialog has finished opening or closing, after any animation.
dismissible?boolean- Whether Escape, an outside press and Android's back gesture can close the dialog. Close parts, triggers and the controller always can. Pass
falsewhile a form has unsaved changes, and ask inonDismissAttempt. onDismissAttempt?((details: DialogDismissAttemptDetails) => void)- Runs when a dismissal was refused, because
dismissibleis false, an outside press doesn't close it, or a Close part's action is running. Ask "Discard changes?" here. persistentElements?(string | Element)[] | (() => Element[])- Elements that stay usable while the dialog makes the page inert, like a chat launcher or a password manager's button. Elements, CSS selectors, or a function that returns elements, read when the dialog opens. Presses on them never close it.
pendingAnnouncement?string- What screen readers hear once a Close part's action has been running 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.
onOpenChange?((open: boolean, details: DialogOpenChangeDetails) => void)- Runs when the dialog wants to open or close.
details.reasonsays why,details.cancel()stops it, anddetails.returnValuecarries what closed it. onPayloadChange?((payload: unknown, details: ChangeDetails<DialogPayloadChangeReason>) => void)- Runs when the payload the content shows changes: a trigger with another payload opens the dialog, or takes a non-modal dialog over while it's open, which fires no
onOpenChange, and so does a controller'sopen({ payload })on the open dialog.details.cancel()keeps the previous payload. modal?"trap-focus" | booleantrue: the rest of the page is inert and doesn't scroll, focus is trapped, and an outside press only closes the dialog."trap-focus": traps focus, and leaves the page scrollable and clickable.false: a dialog beside the page, which Tab can leave and outside presses don't close.closeOnOutsidePress?boolean- Whether pressing outside the dialog, like on its backdrop, closes it. The press counts once it's released outside too, so dragging a text selection out of a field doesn't close it.
presentation?PresentationSetting<"dialog">- How the dialog presents.
"sheet"slides it up from the bottom of the screen, where it can be swiped away, and"auto"does that on small touch screens. Decided each time it opens; the server renders"dialog"for"auto". controller?PopupController<any, DialogOpenChangeReason, {}, any, DialogPayloadChangeReason>- Opens, closes and inspects the dialog from anywhere, and connects triggers outside it. Create one with
createDialogController().
DialogTrigger
对话框之外的触发器也接受 controller。
disabled?boolean- Stops the trigger from opening the dialog. A native button can't be focused or pressed, unless
focusableWhenDisabledis set. focusableWhenDisabled?boolean- Keeps a disabled trigger in the tab order with
aria-disabledinstead of the native attribute, so it can host a tooltip that says why. Presses still do nothing. payload?unknown- Data for the content to render when this trigger opens the dialog, like the row it belongs to.
shortcut?string- A keyboard shortcut that presses the trigger, like
"mod+k".modis Command on Apple platforms and Control elsewhere. Setsaria-keyshortcuts, and a Shortcut part inside shows it. A modal dialog pauses the page's shortcuts while it's open. controller?PopupController<any, DialogOpenChangeReason, {}, any, DialogPayloadChangeReason>- Connects a trigger outside the dialog, like one per table row, to the dialog with this controller.
DialogBackdrop
让模态对话框后面的页面变暗。渲染一个 div。
DialogContent
container?DocumentFragment | Element | null- Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
initialFocus?DialogInitialFocus- Where focus goes when the dialog opens. Opening with touch focuses the dialog itself, so no on-screen keyboard appears, unless this is set to something other than
"auto". finalFocus?PopupFocusTarget- Where focus goes when the dialog closes while focus is inside it.
keepMounted?boolean- Whether the dialog stays in the page, hidden, while closed. Its content keeps its state between opens.
inline?boolean- Renders the dialog and its backdrop where they are in the page instead of above it, so it can stay inside a frame, like an app preview. Pair it with
modal="trap-focus"to keep the rest of the page usable. Acontaineron the dialog still moves its backdrop, so leave it off.
DialogTitle
为对话框命名。渲染一个 h2。
DialogDescription
在渲染期间描述对话框。渲染一个 p。
DialogClose
它的 action 接收事件和 { source },即部件是如何被按压的,Button 对此有说明。
value?string- Reported as
returnValueinonOpenChangeand by the controller'sopen().createConfirm()resolvestruefor"confirm". action?((event: Event | undefined, details: ActionDetails) => unknown)- Runs when the part is pressed, before the dialog closes. A returned Promise keeps the dialog open while it runs: the part gets
data-pending,aria-busyandaria-disabled, screen readers hear the dialog'spendingAnnouncementafter a second, and nothing but the controller closes the dialog. It closes with reason"action"once the Promise resolves. A rejection keeps it open and puts the reason in the part'serrorstate until the next press, or until the dialog opens again.details.sourcesays how the part was pressed, for changes made after anawait.
DialogShortcut
shortcut?string- The keys to show. Inside a trigger, its
shortcut.
状态
每个部件的 render 和 children 片段收到什么。
DialogTrigger:
openboolean- Whether the dialog is open from this trigger.
disabledboolean- Set by the trigger's
disabledprop, which stops it opening the dialog.
DialogBackdrop:
openboolean- Whether the dialog is open. False while it animates out.
nestedboolean- Whether the dialog was opened from inside another dialog.
nestedOpenboolean- Whether a dialog opened from inside this one is open.
DialogContent:
openboolean- Whether the dialog is open. False while it animates out.
modalboolean | "trap-focus"- The
modalsetting. Always true for an alert dialog. nestedboolean- Whether the dialog was opened from inside another dialog.
nestedOpenboolean- Whether a dialog opened from inside this one is open.
stacknumber- How many dialogs are open above this one, nested inside it.
payloadPayload | undefined- The payload of the last open, from the trigger that opened it or a controller, typed as the controller's
Payload. pendingboolean- Whether a Close part's action is running.
presentation"dialog" | "sheet"- How it presents this time it's open.
DialogClose:
pendingboolean- Whether this part's action is running.
errorunknown- Why this part's last action failed, until it's pressed again or the dialog opens again.
DialogShortcut:
textstring- The shortcut formatted for this platform:
⌘Kon Apple platforms andCtrl+Kelsewhere. Empty without one.
原因
details.reason 说明对话框为什么打开或关闭。
trigger-pressMouseEvent | KeyboardEvent | TouchEvent- Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its
touchend. close-pressMouseEvent | KeyboardEvent | SubmitEvent- A Close part was pressed, or a form with
method="dialog"was submitted. outside-pressMouseEvent- A press outside the layer.
escape-keyKeyboardEvent- Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
parent-closenone- The parent layer closed.
backEvent- Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
actionMouseEvent | KeyboardEvent- A Close part's
actionfinished. shortcutKeyboardEvent- A keyboard shortcut, like a trigger's
shortcut. swipeTouchEvent | PointerEvent- A swipe gesture: a finger, mouse or pen dragged it.
imperativenone- A controller or
apicall.
对于 payload 变更,它说明是什么打开了对话框或接管了它。
trigger-pressMouseEvent | KeyboardEvent | TouchEvent- Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its
touchend. shortcutKeyboardEvent- A keyboard shortcut, like a trigger's
shortcut. imperativenone- A controller or
apicall.
dismissible 可以拒绝的关闭操作:
outside-pressMouseEvent- A press outside the layer.
escape-keyKeyboardEvent- Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
backEvent- Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
swipeTouchEvent | PointerEvent- A swipe gesture: a finger, mouse or pen dragged it.
控制器
用 createDialogController<Payload, Result>() 创建一个,并把它作为 controller 传给对话框以及对话框之外的任何触发器。
每个写方法都接受可选的 { reason, event },并传给 onOpenChange。用控制器关闭总是有效,即使对话框不可关闭,或者有动作正在运行。
isOpen()() => boolean- Whether it's open. False as soon as it starts closing, while it still animates out.
setOpen(open, options?)(open: boolean, options?: PopupChangeOptions<DialogOpenChangeReason> | undefined) => boolean- Opens or closes it. Returns false when the change was canceled or it was already open or closed.
open(options?)(options?: (PopupChangeOptions<DialogPayloadChangeReason> & { payload?: Payload | undefined; anchor?: Anchor | undefined; signal?: AbortSignal | undefined; }) | undefined) => Promise<...>- Opens it, and resolves once it closes, with why, how and any return value. Resolves exactly once and never rejects: on the next close from any source, when
signalaborts, or with reason"unmount"when the component leaves the page. close(options?)(options?: (PopupChangeOptions<DialogOpenChangeReason> & { returnValue?: Result | undefined; }) | undefined) => boolean- Closes it.
returnValueis passed to the promiseopen()returned. Returns false when the close was canceled or it was already closed. toggle(options?)(options?: PopupChangeOptions<DialogOpenChangeReason> | undefined) => boolean- Opens it when it's closed, and closes it when it's open. Returns false when the change was canceled.
getPayload()() => Payload | undefined- The payload of the last open, from a controller or the trigger that opened it.
focus()() => void- Moves focus to the trigger that opened it last, or the first trigger.
事件
回调先收到新状态,再收到详情。只有 onOpenChange 没有被取消时,绑定的 open 才会更新。
| 属性 | 所属 | 收到 |
|---|---|---|
bind:open | Dialog | 对话框是否打开 |
onOpenChange | Dialog | (open, details): 新状态、原因以及任何 returnValue |
onOpenChangeComplete | Dialog | (open), 在动画之后 |
onPayloadChange | Dialog | (payload, details): 内容的新 payload,以及原因 |
onDismissAttempt | Dialog | ({ reason, event }), 当一次关闭被拒绝时 |
无障碍
触发器是一个打开对话框的按钮,对话框遵循 WAI-ARIA 模态对话框模式:模态时带有 aria-modal,由标题提供名称,只有在描述被渲染时才由描述说明。下面每一行都是一个自动化测试。
键盘
| 按键 | 作用 |
|---|---|
| Enter, Space | 在触发器上打开对话框 |
| Tab, Shift+Tab | 在对话框的控件之间移动,模态时保持在内部 |
| Escape | 关闭最上层的对话框,并把焦点还给它的触发器 |
| 触发器的快捷键 | 从页面上的任何位置打开它的对话框 |
经过测试的行为
- Advertises a dialog.
- Click opens the dialog.
- Enter opens the dialog.
- Space opens the dialog.
- Opening moves focus to the first focusable element.
- Each time focus moves in, the dialog is named by its title and described by its description.
- Tab moves through the dialog in order.
- Tab from the last element wraps to the first.
- Tab keeps focus inside where the browser's Tab skips the buttons.
- Shift+Tab from the first element wraps to the last.
- … from inside an iframe that is the … element wraps around the dialog.
- Shift+Tab from the first element wraps to the checked radio of a group outside a form.
- Tab reaches radios whose group's checked radio is behind the dialog.
- Tab visits a positive tabindex first, like the browser.
- A positive tabindex keeps Tab inside a dialog that leaves the page usable.
- A positive tabindex slotted into a custom element keeps its host's place.
- With a positive tabindex in the dialog, Tab still moves through a shadow root and slots.
- With a positive tabindex in the dialog, Tab from a focused element outside the tab order goes to the next stop.
- Tab from a custom element with a positive tabindex enters its shadow root.
- Tab from a last control inside a shadow root wraps to the first, and Shift+Tab comes back to it.
- Tab wraps past a shadow root that Tab skips, under an inert or tabindex -1 host.
- Tab wraps from the last stop of a shadow root that orders a positive tabindex first.
- Opening focuses the first field even when a later one has a positive tabindex.
- Escape closes the dialog and returns focus to the trigger.
- An ancestor hears Escape already handled.
- Escape after a click returns focus to the trigger.
- The close button closes the dialog and returns focus to the trigger.
- A virtual click from a screen reader moves focus into the dialog.
- A touch press focuses the dialog itself, so no on-screen keyboard appears.
- A touch press focuses the element initialFocus names.
- Pressing a button inside keeps the dialog open.
- Pressing the backdrop closes the dialog.
- Pressing the backdrop returns focus to the trigger.
- After pressing the backdrop, Space on the trigger opens it again.
- Clicking inside the dialog keeps it open.
- An outside press doesn't reach the page.
- Selecting text in a field and releasing over the backdrop keeps the dialog open.
- Pressing the backdrop and releasing inside the dialog keeps it open.
- A right click on the backdrop keeps the dialog open.
- A dialog styled only with ::backdrop closes when the backdrop is pressed.
- With closeOnOutsidePress false, pressing the backdrop keeps the dialog open.
- Pressing a nested dialog's backdrop closes only the nested dialog.
- While a dialog a backdrop press closed animates out, the next press there doesn't reach the page.
- While a dialog closed with Escape animates out, a press on its backdrop reaches the page.
- Escape right after opening a nested dialog closes only the nested one.
- Tab never leaves the dialog.
- The page doesn't scroll while the dialog is open.
- The rest of the page is hidden from assistive technology.
- With modal false, the page stays usable.
- Escape closes only the nested dialog and returns focus to its trigger.
- The nested dialog's close button closes only it.
- The outer dialog's open change hears only the outer dialog.
- Tab stays inside the nested dialog.
- A second Escape closes the outer dialog.
运行于 React、Vue 和 web components。
其他行为:
- Escape while an input method is composing text keeps the dialog open.
- Escape closes a non-modal dialog only while focus is inside it.
- Closing returns focus to the trigger before the exit animation finishes.
- Closing after the trigger is gone moves focus to the element after where it was.
- Closing after the trigger is gone skips past a later positive tabindex.
- A dialog open from the start moves focus inside.
- With initial focus on the content, the dialog itself takes focus.
- The page outside is inert while open and restored exactly after.
- A live region outside the dialog keeps announcing while it's open.
- Tab leaves a non-modal dialog and the dialog stays open.
- A non-modal dialog stays open when the page is clicked.
- A dialog opened inside a dialog marks both, for styling.
- Closing the parent closes the nested dialog with reason parent-close.
- A controller opens the dialog, moves focus in, and resolves with how it closed.
- Aborting the signal closes the dialog, and the promise resolves once.
- A pending open() resolves with reason unmount when the dialog leaves the page. 仅在 Web components 运行。
- A form with method dialog closes the dialog and reports the submitter's value.
- A confirm helper resolves true for the action and false otherwise.
- A confirm opened from inside a modal dialog takes focus and stays usable.
- A confirm opened over a modal dialog with nothing focused stays usable.
- A confirm opened as a modal dialog shows, before the page freezes, stays usable.
- Closing reports why, for every way a dialog closes.
- A trigger connected through a controller shows its shortcut in a Shortcut part, and binds it.
- The open property and attribute open and close the dialog. 仅在 Web components 运行。
运行于 React、Vue 和 web components。
- Choosing the item closes the menu and moves focus into the dialog.
- Choosing the item with the keyboard moves focus into the dialog.
- The page around the dialog is inert, the menu's trigger included.
- Closing the dialog returns focus to the menu's trigger.
- A dialog the item opens through its open prop returns focus to the menu's trigger. 仅在 React 和 Vue 运行。
- A trigger's shortcut opens the dialog.
- The trigger advertises its shortcut, and shows it to sighted users only.
- A modal dialog pauses the page's shortcuts and keeps its own.
- A dialog's own shortcut doesn't run while the dialog is closed.
- Menu and popover triggers take shortcuts too.
- Plain keys typed in a text field are text, and modifier shortcuts still run.
- A plain-key shortcut runs outside text fields.
- Refuses Escape and outside presses, and reports each attempt.
- A clean form closes on Escape.
- Stay usable while a modal dialog is open, and pressing them keeps it open.
- Keep the alert dialog open and pending, then close with reason action.
- A failed action keeps the alert dialog open and stops pending.
- A menu and a dialog inside it render into the popover's container.
- Closes the topmost dialog with reason back.
运行于 React、Vue 和 web components。
在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器记录:
- Announcements while using the dialog with a keyboard.
- Announcements while using the alert dialog with a keyboard.
运行于 React、Vue 和 web components。