Alert Dialog
继续之前,请某人确认一个操作。
有些操作在继续之前需要有人回答一个问题,比如删除一个项目,这时就用警告对话框(Alert Dialog)。
import "@ui-sdk/web/alert-dialog"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-alert-dialog>
<ui-alert-dialog-trigger>
<button>Delete Project</button>
</ui-alert-dialog-trigger>
<ui-alert-dialog-backdrop hidden></ui-alert-dialog-backdrop>
<ui-alert-dialog-content hidden>
<div data-slot="stack">
<ui-alert-dialog-title>Delete this project?</ui-alert-dialog-title>
<ui-alert-dialog-description>
This permanently deletes the project, its files and its deployment history for everyone on your team.
</ui-alert-dialog-description>
</div>
<div data-slot="row">
<ui-alert-dialog-close>
<button>Cancel</button>
</ui-alert-dialog-close>
<ui-alert-dialog-close value="confirm">
<button data-variant="solid">Delete</button>
</ui-alert-dialog-close>
</div>
</ui-alert-dialog-content>
</ui-alert-dialog>
`
}
export { mount }安装
npm install @ui-sdk/web @ui-sdk/core导入组件以注册它的元素。这个导入在服务端是安全的。
import "@ui-sdk/web/alert-dialog"组合
用下面的组合构建一个 ui-alert-dialog:
ui-alert-dialog
├── ui-alert-dialog-trigger
│ └── button
├── ui-alert-dialog-backdrop
└── ui-alert-dialog-content
├── ui-alert-dialog-title
├── ui-alert-dialog-description
├── ui-alert-dialog-close
│ └── button
└── ui-alert-dialog-close
└── button把问题放在 ui-alert-dialog-title 里,在 ui-alert-dialog-description 里说明会发生什么,每个回答的原生按钮包在一个 ui-alert-dialog-close 里。加上 ui-alert-dialog-backdrop 让页面变暗。给内容和背景部件加上 hidden,让它们在元素升级之前保持隐藏。
Close 部件关闭时会报告它的 value。value="confirm" 是表示同意的回答,confirm 辅助函数会识别它。
用法
导入各个部件并把它们组合起来:
<script type="module">
import "@ui-sdk/web/alert-dialog"
</script>
<ui-alert-dialog>
<ui-alert-dialog-trigger
><button>Delete Project</button></ui-alert-dialog-trigger
>
<ui-alert-dialog-content hidden>
<ui-alert-dialog-title>Delete this project?</ui-alert-dialog-title>
<ui-alert-dialog-description
>The project and its files will be deleted for
everyone.</ui-alert-dialog-description
>
<ui-alert-dialog-close><button>Cancel</button></ui-alert-dialog-close>
<ui-alert-dialog-close value="confirm"
><button>Delete</button></ui-alert-dialog-close
>
</ui-alert-dialog-content>
</ui-alert-dialog>自己构建
@ui-sdk/web/alert-dialog 自带现成的 ui-alert-dialog 元素。如果你想用自己的元素名构建自己的版本,从 @ui-sdk/core 里的 alertDialog 原语(primitive)开始:
import { alertDialog } from "@ui-sdk/core/alert-dialog"
import { createParts, wrappedButton } from "@ui-sdk/web"
createParts(alertDialog, {
root: "confirm-dialog",
trigger: {
tag: "confirm-trigger",
target: wrappedButton,
display: "contents",
},
backdrop: "confirm-backdrop",
content: "confirm-content",
title: "confirm-title",
description: "confirm-description",
close: { tag: "confirm-close", target: wrappedButton, display: "contents" },
})<confirm-dialog>
<confirm-trigger><button>Delete Project</button></confirm-trigger>
<confirm-backdrop hidden></confirm-backdrop>
<confirm-content hidden>
<confirm-title>Delete this project?</confirm-title>
<confirm-description
>This permanently deletes the project.</confirm-description
>
<confirm-close><button>Cancel</button></confirm-close>
<confirm-close value="confirm"><button>Delete</button></confirm-close>
</confirm-content>
</confirm-dialog>每个元素都保留其现成对应元素的行为、状态和数据属性:内容在顶层(top layer)打开,把焦点困在内部,并让页面不可交互(inert)。更多内容见渲染和自定义部件。
受控
在应用里设置元素的 open property 来打开或关闭它。监听 openchange,跟随部件做出的变更。状态与事件说明了受控状态和如何取消变更。
import "@ui-sdk/web/alert-dialog"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<button type="button" aria-haspopup="dialog">Review Changes</button>
<ui-alert-dialog>
<ui-alert-dialog-backdrop hidden></ui-alert-dialog-backdrop>
<ui-alert-dialog-content hidden>
<div data-slot="stack">
<ui-alert-dialog-title>Discard unsaved changes?</ui-alert-dialog-title>
<ui-alert-dialog-description>
Your edits will be lost if you leave without saving.
</ui-alert-dialog-description>
</div>
<div data-slot="row">
<ui-alert-dialog-close>
<button>Keep Editing</button>
</ui-alert-dialog-close>
<ui-alert-dialog-close value="confirm">
<button data-variant="solid">Discard</button>
</ui-alert-dialog-close>
</div>
</ui-alert-dialog-content>
</ui-alert-dialog>
</div>
`
const dialog = root.querySelector("ui-alert-dialog")!
root.querySelector("button")!.addEventListener("click", () => {
dialog.open = true
})
}
export { mount }快捷键
给触发器一个 shortcut,让它能从键盘打开对话框,并在它的按钮里放一个 ui-alert-dialog-shortcut 来显示按键。Dialog 涵盖快捷键语法。
import "@ui-sdk/web/alert-dialog"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-alert-dialog>
<ui-alert-dialog-trigger shortcut="mod+shift+h">
<button>
Clear History
<ui-alert-dialog-shortcut></ui-alert-dialog-shortcut>
</button>
</ui-alert-dialog-trigger>
<ui-alert-dialog-backdrop hidden></ui-alert-dialog-backdrop>
<ui-alert-dialog-content hidden>
<div data-slot="stack">
<ui-alert-dialog-title>Clear your history?</ui-alert-dialog-title>
<ui-alert-dialog-description>
Recent searches and visited pages are removed from this device.
</ui-alert-dialog-description>
</div>
<div data-slot="row">
<ui-alert-dialog-close>
<button>Cancel</button>
</ui-alert-dialog-close>
<ui-alert-dialog-close value="confirm">
<button data-variant="solid">Clear</button>
</ui-alert-dialog-close>
</div>
</ui-alert-dialog-content>
</ui-alert-dialog>
`
}
export { mount }动画
内容在打开期间带有 data-starting-style,关闭期间带有 data-ending-style。从这些状态做过渡,对话框会保持挂载,直到退场结束:
[data-slot="alert-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;
}
}import "@ui-sdk/web/alert-dialog"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-alert-dialog>
<ui-alert-dialog-trigger>
<button>Leave Workspace</button>
</ui-alert-dialog-trigger>
<ui-alert-dialog-backdrop hidden></ui-alert-dialog-backdrop>
<ui-alert-dialog-content hidden>
<div data-slot="stack">
<ui-alert-dialog-title>Leave this workspace?</ui-alert-dialog-title>
<ui-alert-dialog-description>
You'll lose access to its projects until someone invites you again.
</ui-alert-dialog-description>
</div>
<div data-slot="row">
<ui-alert-dialog-close>
<button>Cancel</button>
</ui-alert-dialog-close>
<ui-alert-dialog-close value="confirm">
<button data-variant="solid">Leave</button>
</ui-alert-dialog-close>
</div>
</ui-alert-dialog-content>
</ui-alert-dialog>
`
}
export { mount }嵌套
在另一个 Alert Dialog 里打开的 Alert Dialog 会加入它的栈,比如在某个操作无法撤销之前再确认一次。Escape 关闭最上层的对话框,并把焦点还给它的触发器。下面的对话框会带上 data-nested-open,让你可以显示哪一层处于活动状态。要在最后一个问题回答完后把两者都关闭,就监听内层对话框的 openchange,当 event.detail.returnValue 为 "confirm" 时把外层的 open 设为 false。
import "@ui-sdk/web/alert-dialog"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-alert-dialog>
<ui-alert-dialog-trigger>
<button>Delete Workspace</button>
</ui-alert-dialog-trigger>
<ui-alert-dialog-backdrop hidden></ui-alert-dialog-backdrop>
<ui-alert-dialog-content hidden>
<div data-slot="stack">
<ui-alert-dialog-title>Delete this workspace?</ui-alert-dialog-title>
<ui-alert-dialog-description>
All 12 projects and their deployments will be deleted for everyone on your team.
</ui-alert-dialog-description>
</div>
<div data-slot="row">
<ui-alert-dialog-close>
<button>Cancel</button>
</ui-alert-dialog-close>
<ui-alert-dialog>
<ui-alert-dialog-trigger>
<button data-variant="solid">Delete</button>
</ui-alert-dialog-trigger>
<ui-alert-dialog-backdrop hidden></ui-alert-dialog-backdrop>
<ui-alert-dialog-content hidden>
<div data-slot="stack">
<ui-alert-dialog-title>Are you absolutely sure?</ui-alert-dialog-title>
<ui-alert-dialog-description>There's no way to get the workspace back.</ui-alert-dialog-description>
</div>
<div data-slot="row">
<ui-alert-dialog-close>
<button>Go Back</button>
</ui-alert-dialog-close>
<ui-alert-dialog-close value="confirm">
<button data-variant="solid">Delete Workspace</button>
</ui-alert-dialog-close>
</div>
</ui-alert-dialog-content>
</ui-alert-dialog>
</div>
</ui-alert-dialog-content>
</ui-alert-dialog>
`
const [outer, inner] = root.querySelectorAll("ui-alert-dialog")
inner.addEventListener("openchange", (event) => {
if (!event.detail.value && event.detail.returnValue === "confirm") {
outer.open = false
}
})
}
export { mount }异步动作
给 Close 部件加上 action,并监听它的 action 事件。在该事件里把一个 Promise 传给 event.detail.waitUntil(),对话框会保持打开,直到工作完成。兑现的 Promise 以原因 action 关闭它;拒绝会让它保持打开,并把错误放进该部件的状态。
import "@ui-sdk/web/alert-dialog"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<ui-alert-dialog pending-announcement="Deleting project">
<ui-alert-dialog-trigger>
<button>Delete Project</button>
</ui-alert-dialog-trigger>
<ui-alert-dialog-backdrop hidden></ui-alert-dialog-backdrop>
<ui-alert-dialog-content hidden>
<div data-slot="stack">
<ui-alert-dialog-title>Delete project?</ui-alert-dialog-title>
<ui-alert-dialog-description>
This permanently deletes the project, its files and its deployment history for everyone on your team.
</ui-alert-dialog-description>
</div>
<div data-slot="stack">
<p data-slot="hint" role="alert"></p>
<div data-slot="row">
<ui-alert-dialog-close>
<button>Cancel</button>
</ui-alert-dialog-close>
<ui-alert-dialog-close action value="confirm">
<button data-variant="solid">Delete</button>
</ui-alert-dialog-close>
</div>
</div>
</ui-alert-dialog-content>
</ui-alert-dialog>
</div>
`
let attempts = 0
const dialog = root.querySelector("ui-alert-dialog")!
const close = root.querySelector("ui-alert-dialog-close[action]")!
const button = close.querySelector("button")!
const message = root.querySelector("p")!
async function deleteProject() {
await new Promise((resolve) => setTimeout(resolve, 1200))
if (attempts++ === 0) {
throw new Error("Couldn't delete the project.")
}
}
close.addEventListener("action", (event) => {
const { waitUntil } = (
event as CustomEvent<{ waitUntil: (promise: Promise<unknown>) => void }>
).detail
button.textContent = "Deleting…"
message.textContent = ""
const deleting = deleteProject()
waitUntil(deleting)
deleting.then(
() => {
button.textContent = "Delete"
},
(error: Error) => {
button.textContent = "Try Again"
message.textContent = error.message
}
)
})
dialog.addEventListener("openchange", (event) => {
if (!event.detail.value) {
return
}
button.textContent = "Delete"
message.textContent = ""
})
}
export { mount }动作运行期间,它的按钮仍然可以聚焦,并带上 data-pending、aria-busy 和 aria-disabled。其他 Close 部件带上 aria-disabled 和 data-disabled,在动作结束之前,它们和关闭操作都无法关闭对话框。dismissattempt 报告被拒绝的关闭;控制器仍然可以关闭它。
根元素的 pending-announcement 属性设置等待一秒后屏幕阅读器听到的内容。错误会在下一次尝试或对话框再次打开时清除。动作事件的 detail.source 描述启动它的输入;Button 对此有说明。
从任意位置确认
共享的 confirm() 不需要任何对话框标记就能问一个问题。导入 @ui-sdk/web/overlays,在页面末尾附近放一个 ui-overlay-host,它会把每个问题显示为一个 Alert Dialog。有人同意时,confirm() 兑现 true。确认选项列出了可以传入的内容。
import { confirm } from "@ui-sdk/web/alert-dialog"
import "@ui-sdk/web/overlays"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<button type="button">Archive Project</button>
<ui-overlay-host></ui-overlay-host>
`
root.querySelector("button")!.addEventListener("click", async () => {
const yes = await confirm({
title: "Archive this project?",
description: "It moves to Archived, and you can restore it anytime.",
confirmLabel: "Archive",
})
log(root, yes ? "Archived the project" : "Kept the project")
})
}
export { mount }确认
用 createConfirm<Payload>() 从事件处理器里问一个问题,并等待回答。从 @ui-sdk/web/alert-dialog 导入它,创建一次,然后把它的 controller 赋给根元素的 controller property。payloadchange 事件在 event.detail.value 里提供当前的问题。
当带 value="confirm" 的 Close 部件关闭对话框时,await confirm({ name }) 会兑现 true。Cancel、Escape 和其他回答兑现 false。这让多行可以共用一个对话框:
import {
createConfirm,
type UiAlertDialogElement,
} from "@ui-sdk/web/alert-dialog"
const names = ["Acme", "Globex", "Initech"]
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
<button type="button">Reset Projects</button>
</div>
<ul data-slot="list" aria-label="Projects"></ul>
<ui-alert-dialog>
<ui-alert-dialog-backdrop hidden></ui-alert-dialog-backdrop>
<ui-alert-dialog-content hidden>
<div data-slot="stack">
<ui-alert-dialog-title></ui-alert-dialog-title>
<ui-alert-dialog-description>
The project and its files will be deleted for everyone on your team.
</ui-alert-dialog-description>
</div>
<div data-slot="row">
<ui-alert-dialog-close>
<button>Cancel</button>
</ui-alert-dialog-close>
<ui-alert-dialog-close value="confirm">
<button data-variant="solid">Delete</button>
</ui-alert-dialog-close>
</div>
</ui-alert-dialog-content>
</ui-alert-dialog>
</div>
`
const confirm = createConfirm<{ name: string }>()
const dialog =
root.querySelector<UiAlertDialogElement<{ name: string }>>(
"ui-alert-dialog"
)!
const title = root.querySelector("ui-alert-dialog-title")!
const list = root.querySelector("ul")!
const reset = root.querySelector("button")!
dialog.controller = confirm.controller
dialog.addEventListener("payloadchange", (event) => {
title.textContent = `Delete ${event.detail.value?.name}?`
})
function resetProjects() {
list.innerHTML = names
.map(
(name) =>
`<li data-slot="row">${name}<button type="button" data-size="sm" aria-label="Delete ${name}">Delete</button></li>`
)
.join("")
for (const [index, row] of list.querySelectorAll("li").entries()) {
const name = names[index]
row.querySelector("button")!.addEventListener("click", async () => {
if (!(await confirm({ name }))) {
return
}
const next = (
row.nextElementSibling ?? row.previousElementSibling
)?.querySelector("button")
const target = next ?? reset
target.focus()
row.remove()
if (!list.children.length) {
list.innerHTML = `<li data-slot="row">All projects deleted.</li>`
}
})
}
}
reset.addEventListener("click", resetProjects)
resetProjects()
}
export { mount }当动作移除了打开对话框的按钮时,为焦点选择一个有用的去处。这个示例会聚焦相邻的一行,列表为空时聚焦 Reset Projects。
排队的问题
对同一个 confirm 函数的调用会排队等待。你可以一次问两个问题;第二个只会在第一个有了回答之后出现。
import {
createConfirm,
type UiAlertDialogElement,
} from "@ui-sdk/web/alert-dialog"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<button type="button">Review Two Projects</button>
<ui-alert-dialog>
<ui-alert-dialog-backdrop hidden></ui-alert-dialog-backdrop>
<ui-alert-dialog-content hidden>
<div data-slot="stack">
<ui-alert-dialog-title></ui-alert-dialog-title>
<ui-alert-dialog-description>
Archived projects leave the active list. You can restore them later.
</ui-alert-dialog-description>
</div>
<div data-slot="row">
<ui-alert-dialog-close>
<button>Cancel</button>
</ui-alert-dialog-close>
<ui-alert-dialog-close value="confirm">
<button data-variant="solid">Archive</button>
</ui-alert-dialog-close>
</div>
</ui-alert-dialog-content>
</ui-alert-dialog>
</div>
`
const confirm = createConfirm<{ name: string }>()
const dialog =
root.querySelector<UiAlertDialogElement<{ name: string }>>(
"ui-alert-dialog"
)!
const title = root.querySelector("ui-alert-dialog-title")!
dialog.controller = confirm.controller
dialog.addEventListener("payloadchange", (event) => {
title.textContent = `Archive ${event.detail.value?.name}?`
})
root.querySelector("button")!.addEventListener("click", async () => {
const acme = confirm({ name: "Acme" })
const globex = confirm({ name: "Globex" })
const [first, second] = await Promise.all([acme, globex])
log(root, `Acme: ${first ? "confirmed" : "canceled"}`)
log(root, `Globex: ${second ? "confirmed" : "canceled"}`)
})
}
export { mount }样式
每个元素都有一个 data-slot,比如 alert-dialog-content,并通过数据属性下列出的属性展示状态。样式与动画涵盖状态属性以及入场和退场过渡。
<ui-alert-dialog-content>
| 变量 | 内容 |
|---|---|
--dialog-stack | How many dialogs are open above this one, nested inside it. 0 for the topmost. |
--keyboard-inset | How many pixels of the page the on-screen keyboard covers, 0 without one. |
--visual-viewport-width | The width of the part of the page you can see. |
--visual-viewport-height | The height of the part of the page you can see, above the keyboard. |
--visual-viewport-top | How far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up. |
数据属性
<ui-alert-dialog-trigger>
[data-slot="alert-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. |
<ui-alert-dialog-backdrop>
[data-slot="alert-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. |
<ui-alert-dialog-content>
[data-slot="alert-dialog-content"]
| 属性 | 含义 |
|---|---|
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. |
data-keyboard | Present while the on-screen keyboard covers part of the page. |
<ui-alert-dialog-close>
[data-slot="alert-dialog-close"]
| 属性 | 含义 |
|---|---|
data-disabled | |
data-pending | Present on a Close part while its action runs. |
API 参考
Alert Dialog 共享 Dialog 的选项,除了 modal、closeOnOutsidePress 和 presentation。它始终是模态的,从不因外部按压而关闭,也不会呈现为底部面板(sheet)。
AlertDialog
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.
openchangecomplete event- 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 indismissattempt. dismissattempt event- 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.
openchange event- Runs when the alert dialog wants to open or close.
details.reasonsays why,details.cancel()stops it, anddetails.returnValueis thevalueof the Close part that closed it. payloadchange event- Runs when a trigger or a controller with another payload opens the alert dialog, before
openchange, or a controller'sopen({ payload })gives the open one another payload.details.cancel()keeps the previous payload. controller?PopupController<any, AlertDialogOpenChangeReason, {}, any, DialogPayloadChangeReason>- Opens, closes and inspects the alert dialog from anywhere. Create one with
createAlertDialogController()orcreateConfirm().
AlertDialogTrigger
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, AlertDialogOpenChangeReason, {}, any, DialogPayloadChangeReason>- Connects a trigger outside the alert dialog to the alert dialog with this controller.
AlertDialogBackdrop
让对话框后面的页面变暗。<ui-alert-dialog-backdrop> 没有自己的属性。
AlertDialogContent
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.
AlertDialogTitle
问题本身。<ui-alert-dialog-title> 渲染一个二级标题,内容把它用作无障碍名称。
AlertDialogDescription
同意后会发生什么。<ui-alert-dialog-description> 是一个段落,内容把它用作无障碍描述。
AlertDialogClose
value?string- Reported as
returnValueinopenchangeand 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.
AlertDialogShortcut
shortcut?string- The keys to show. Inside a trigger, its
shortcut.
确认选项
ui-overlay-host 渲染问题时,共享的 confirm() 函数使用这些选项。宿主设置见 Toast 与确认框。使用你自己的对话框时,createConfirm<Payload>() 改为接受你选择的 payload。
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.
状态
AlertDialogContent:
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"- Always
"dialog": an alert dialog never presents as a sheet.
AlertDialogClose:
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.
AlertDialogShortcut:
textstring- The shortcut formatted for this platform:
⌘Kon Apple platforms andCtrl+Kelsewhere. Empty without one.
原因
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. 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. imperativenone- A controller or
apicall.
当对话框带着另一个 payload 打开时,payloadchange 在 openchange 之前触发。对已打开的对话框调用 controller.open({ payload }),会以原因 imperative 更新 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.
控制器
用 @ui-sdk/web/alert-dialog 里的 createAlertDialogController<Payload, Result>() 直接控制。根元素的 api property 有相同的方法。createConfirm<Payload>() 返回一个 confirm 函数,它有自己的 controller。
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<AlertDialogOpenChangeReason> | 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<AlertDialogOpenChangeReason> & { 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<AlertDialogOpenChangeReason> | 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.
无障碍
给对话框一个标题和描述,并把破坏性最小的回答放在最前面。它遵循 WAI-ARIA 警告对话框模式。
对话框使用 alertdialog 角色,打开时让页面其余部分保持不可交互(inert)。屏幕阅读器会播报它的标题和描述。打开时焦点落在第一个 Close 部件上,所以把 Cancel 放在最前面。触摸打开时改为聚焦内容,这样不会出现屏幕键盘,除非你设置了 initial-focus。Escape 会关闭对话框,但从不会因按压外部而关闭。其他初始和最终焦点目标见 Dialog。
这些行为由自动化测试覆盖:
- Opens with focus on the least destructive action.
- Is described by its message.
- An outside press keeps it open.
- Escape closes it and returns focus to the trigger.
- Tab cycles between its actions.
- The action reports and closes.
运行于 React、Vue 和 web components。