继续之前,请某人确认一个操作。

有些操作在继续之前需要有人回答一个问题,比如删除一个项目,这时就用警告对话框(Alert Dialog)。

import {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@ui-sdk/solid/alert-dialog"

function Example() {
  return (
    <AlertDialog>
      <AlertDialogTrigger>Delete Project</AlertDialogTrigger>
      <AlertDialogBackdrop />
      <AlertDialogContent>
        <div data-slot="stack">
          <AlertDialogTitle>Delete this project?</AlertDialogTitle>
          <AlertDialogDescription>
            This permanently deletes the project, its files and its deployment
            history for everyone on your team.
          </AlertDialogDescription>
        </div>
        <div data-slot="row">
          <AlertDialogClose>Cancel</AlertDialogClose>
          <AlertDialogClose data-variant="solid" value="confirm">
            Delete
          </AlertDialogClose>
        </div>
      </AlertDialogContent>
    </AlertDialog>
  )
}

export { Example }
用 Enter 打开对话框,焦点从 Cancel 开始。Tab 保持在内部,点击外部不会关闭它,Escape 会关闭它并把焦点还给触发器。

安装

npm install @ui-sdk/solid @ui-sdk/core

组合

用下面的组合构建一个 AlertDialog:

AlertDialog
├── AlertDialogTrigger
├── AlertDialogBackdrop
└── AlertDialogContent
    ├── AlertDialogTitle
    ├── AlertDialogDescription
    ├── AlertDialogClose
    └── AlertDialogClose

把问题放在 AlertDialogTitle 里,在 AlertDialogDescription 里说明会发生什么,每个回答用一个 AlertDialogClose。加上 AlertDialogBackdrop 让页面变暗。

Close 部件关闭时会报告它的 value。value="confirm" 是表示同意的回答,confirm 辅助函数会识别它。

用法

导入各个部件并把它们组合起来:

import {
  AlertDialog,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@ui-sdk/solid/alert-dialog"

function Example() {
  return (
    <AlertDialog>
      <AlertDialogTrigger>Delete Project</AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogTitle>Delete this project?</AlertDialogTitle>
        <AlertDialogDescription>
          The project and its files will be deleted for everyone.
        </AlertDialogDescription>
        <AlertDialogClose>Cancel</AlertDialogClose>
        <AlertDialogClose value="confirm">Delete</AlertDialogClose>
      </AlertDialogContent>
    </AlertDialog>
  )
}

export { Example }

自己构建

@ui-sdk/solid/alert-dialog 自带一个现成的 Alert Dialog。如果你想用自己的名字构建自己的版本,从 @ui-sdk/core 里的 alertDialog 原语(primitive)开始:

confirm.ts
import { alertDialog } from "@ui-sdk/core/alert-dialog"
import { createParts } from "@ui-sdk/solid/primitive"

const {
  Root: Confirm,
  Trigger: ConfirmTrigger,
  Backdrop: ConfirmBackdrop,
  Content: ConfirmContent,
  Title: ConfirmTitle,
  Description: ConfirmDescription,
  Close: ConfirmClose,
} = createParts(alertDialog, {
  trigger: "button",
  backdrop: "div",
  content: "div",
  title: "h2",
  description: "p",
  close: "button",
})

export {
  Confirm,
  ConfirmBackdrop,
  ConfirmClose,
  ConfirmContent,
  ConfirmDescription,
  ConfirmTitle,
  ConfirmTrigger,
}
<Confirm>
  <ConfirmTrigger>Delete Project</ConfirmTrigger>
  <ConfirmBackdrop />
  <ConfirmContent>
    <ConfirmTitle>Delete this project?</ConfirmTitle>
    <ConfirmDescription>
      This permanently deletes the project.
    </ConfirmDescription>
    <ConfirmClose>Cancel</ConfirmClose>
    <ConfirmClose value="confirm">Delete</ConfirmClose>
  </ConfirmContent>
</Confirm>

每个部件都保留其现成对应部件的行为、状态和数据属性:内容在顶层(top layer)打开,把焦点困在内部,并让页面不可交互(inert)。更多内容见渲染和自定义部件。

受控

当你的应用需要读取或控制对话框是否打开时,传入 open 和 onOpenChange。状态与事件说明了受控状态和如何取消变更。

import {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@ui-sdk/solid/alert-dialog"
import { createSignal } from "solid-js"

function Example() {
  const [open, setOpen] = createSignal(false)

  return (
    <div data-slot="stack">
      <AlertDialog open={open()} onOpenChange={setOpen}>
        <AlertDialogTrigger>Review Changes</AlertDialogTrigger>
        <AlertDialogBackdrop />
        <AlertDialogContent>
          <div data-slot="stack">
            <AlertDialogTitle>Discard unsaved changes?</AlertDialogTitle>
            <AlertDialogDescription>
              Your edits will be lost if you leave without saving.
            </AlertDialogDescription>
          </div>
          <div data-slot="row">
            <AlertDialogClose>Keep Editing</AlertDialogClose>
            <AlertDialogClose data-variant="solid" value="confirm">
              Discard
            </AlertDialogClose>
          </div>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}

export { Example }
选择 Review Changes,然后选择 Keep Editing 或 Discard。

快捷键

给触发器一个 shortcut,让它能从键盘打开对话框,并在触发器里放一个 AlertDialogShortcut 来显示按键。Dialog 涵盖快捷键语法。

import {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogShortcut,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@ui-sdk/solid/alert-dialog"

function Example() {
  return (
    <AlertDialog>
      <AlertDialogTrigger shortcut="mod+shift+h">
        Clear History
        <AlertDialogShortcut />
      </AlertDialogTrigger>
      <AlertDialogBackdrop />
      <AlertDialogContent>
        <div data-slot="stack">
          <AlertDialogTitle>Clear your history?</AlertDialogTitle>
          <AlertDialogDescription>
            Recent searches and visited pages are removed from this device.
          </AlertDialogDescription>
        </div>
        <div data-slot="row">
          <AlertDialogClose>Cancel</AlertDialogClose>
          <AlertDialogClose data-variant="solid" value="confirm">
            Clear
          </AlertDialogClose>
        </div>
      </AlertDialogContent>
    </AlertDialog>
  )
}

export { Example }
按 Cmd+Shift+H(Windows 和 Linux 上是 Ctrl+Shift+H)打开对话框,无需点击。

动画

内容在打开期间带有 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 {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@ui-sdk/solid/alert-dialog"

function Example() {
  return (
    <AlertDialog>
      <AlertDialogTrigger>Leave Workspace</AlertDialogTrigger>
      <AlertDialogBackdrop />
      <AlertDialogContent>
        <div data-slot="stack">
          <AlertDialogTitle>Leave this workspace?</AlertDialogTitle>
          <AlertDialogDescription>
            You'll lose access to its projects until someone invites you again.
          </AlertDialogDescription>
        </div>
        <div data-slot="row">
          <AlertDialogClose>Cancel</AlertDialogClose>
          <AlertDialogClose data-variant="solid" value="confirm">
            Leave
          </AlertDialogClose>
        </div>
      </AlertDialogContent>
    </AlertDialog>
  )
}

export { Example }
打开对话框再关闭它。它会向上滑入并淡入,在卸载前向下滑出并淡出。

嵌套

在另一个 Alert Dialog 里打开的 Alert Dialog 会加入它的栈,比如在某个操作无法撤销之前再确认一次。Escape 关闭最上层的对话框,并把焦点还给它的触发器。下面的对话框会带上 data-nested-open,让你可以显示哪一层处于活动状态。要在最后一个问题回答完后把两者都关闭,就控制外层对话框,并在内层以 returnValue "confirm" 关闭时把它关掉。

import {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@ui-sdk/solid/alert-dialog"
import { createSignal } from "solid-js"

function Example() {
  const [open, setOpen] = createSignal(false)

  return (
    <AlertDialog open={open()} onOpenChange={setOpen}>
      <AlertDialogTrigger>Delete Workspace</AlertDialogTrigger>
      <AlertDialogBackdrop />
      <AlertDialogContent>
        <div data-slot="stack">
          <AlertDialogTitle>Delete this workspace?</AlertDialogTitle>
          <AlertDialogDescription>
            All 12 projects and their deployments will be deleted for everyone
            on your team.
          </AlertDialogDescription>
        </div>
        <div data-slot="row">
          <AlertDialogClose>Cancel</AlertDialogClose>
          <AlertDialog
            onOpenChange={(nested, details) => {
              if (!nested && details.returnValue === "confirm") {
                setOpen(false)
              }
            }}
          >
            <AlertDialogTrigger data-variant="solid">Delete</AlertDialogTrigger>
            <AlertDialogBackdrop />
            <AlertDialogContent>
              <div data-slot="stack">
                <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
                <AlertDialogDescription>
                  There's no way to get the workspace back.
                </AlertDialogDescription>
              </div>
              <div data-slot="row">
                <AlertDialogClose>Go Back</AlertDialogClose>
                <AlertDialogClose data-variant="solid" value="confirm">
                  Delete Workspace
                </AlertDialogClose>
              </div>
            </AlertDialogContent>
          </AlertDialog>
        </div>
      </AlertDialogContent>
    </AlertDialog>
  )
}

export { Example }
选择 Delete Workspace,然后选择 Delete。按 Escape 回到第一个问题,或者选择 Delete Workspace 把两者都关闭。

异步动作

Close 部件上的 action 在关闭对话框之前运行。返回一个 Promise,对话框会保持打开,直到工作完成。兑现的 Promise 以原因 action 关闭它;拒绝会让它保持打开,并把错误放进该部件的状态。

import {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@ui-sdk/solid/alert-dialog"

function Example() {
  let attempts = 0

  async function deleteProject() {
    await new Promise((resolve) => setTimeout(resolve, 1200))
    if (attempts++ === 0) {
      throw new Error("Couldn't delete the project.")
    }
  }

  return (
    <div data-slot="stack">
      <AlertDialog pendingAnnouncement="Deleting project">
        <AlertDialogTrigger>Delete Project</AlertDialogTrigger>
        <AlertDialogBackdrop />
        <AlertDialogContent>
          <div data-slot="stack">
            <AlertDialogTitle>Delete project?</AlertDialogTitle>
            <AlertDialogDescription>
              This permanently deletes the project, its files and its deployment
              history for everyone on your team.
            </AlertDialogDescription>
          </div>
          <AlertDialogClose
            data-variant="solid"
            value="confirm"
            action={deleteProject}
            render={(props, state) => (
              <div data-slot="stack">
                <p data-slot="hint" role="alert">
                  {state.error instanceof Error && state.error.message}
                </p>
                <div data-slot="row">
                  <AlertDialogClose>Cancel</AlertDialogClose>
                  <button {...props}>
                    {state.pending
                      ? "Deleting…"
                      : state.error
                        ? "Try Again"
                        : "Delete"}
                  </button>
                </div>
              </div>
            )}
          />
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}

export { Example }
选择 Delete Project,然后选择 Delete。第一次尝试会失败,这样你可以再试一次。显示 Deleting… 时,Cancel 和 Escape 都会让对话框保持打开。重试成功后它才会关闭。

动作运行期间,它的按钮仍然可以聚焦,并带上 data-pending、aria-busy 和 aria-disabled。其他 Close 部件带上 aria-disabled 和 data-disabled,在动作结束之前,它们和关闭操作都无法关闭对话框。onDismissAttempt 报告被拒绝的关闭;控制器仍然可以关闭它。

根组件的 pendingAnnouncement 设置等待一秒后屏幕阅读器听到的内容。错误会在下一次尝试或对话框再次打开时清除。动作在事件参数之后还会收到 { source };Button 对此有说明。

从任意位置确认

共享的 confirm() 不需要任何对话框标记就能问一个问题。在应用根部附近渲染一次来自 @ui-sdk/solid/overlays 的 OverlayHost,它会把每个问题显示为一个 Alert Dialog。有人同意时,confirm() 兑现 true。确认选项列出了可以传入的内容。

控制台
import { confirm } from "@ui-sdk/solid/alert-dialog"
import { OverlayHost } from "@ui-sdk/solid/overlays"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  async function archive() {
    const yes = await confirm({
      title: "Archive this project?",
      description: "It moves to Archived, and you can restore it anytime.",
      confirmLabel: "Archive",
    })
    log(yes ? "Archived the project" : "Kept the project")
  }

  return (
    <>
      <button type="button" onClick={archive}>
        Archive Project
      </button>
      <OverlayHost />
    </>
  )
}

export { Example }
选择 Archive Project,然后选择 Archive 或 Cancel。控制台会显示回答。

确认

用 createConfirm<Payload>() 从事件处理器里问一个问题,并等待回答。创建一次,然后把它的 controller 传给你的 Alert Dialog。内容从 state.payload 读取问题的数据。

当带 value="confirm" 的 Close 部件关闭对话框时,await confirm({ name }) 会兑现 true。Cancel、Escape 和其他回答兑现 false。这让多行可以共用一个对话框:

import {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogTitle,
  createConfirm,
} from "@ui-sdk/solid/alert-dialog"
import { createSignal, For } from "solid-js"

function Example() {
  const confirm = createConfirm<{ name: string }>()
  const [projects, setProjects] = createSignal(["Acme", "Globex", "Initech"])
  let reset: HTMLButtonElement | undefined

  async function remove(name: string, button: HTMLButtonElement) {
    if (!(await confirm({ name }))) {
      return
    }
    const row = button.closest("li")
    const next = (
      row?.nextElementSibling ?? row?.previousElementSibling
    )?.querySelector("button")
    const target = next ?? reset
    target?.focus()
    setProjects((list) => list.filter((project) => project !== name))
  }

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button
          ref={(element) => (reset = element)}
          type="button"
          onClick={() => setProjects(["Acme", "Globex", "Initech"])}
        >
          Reset Projects
        </button>
      </div>
      <ul data-slot="list" aria-label="Projects">
        <For
          each={projects()}
          fallback={<li data-slot="row">All projects deleted.</li>}
        >
          {(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>
          )}
        </For>
      </ul>
      <AlertDialog controller={confirm.controller}>
        <AlertDialogBackdrop />
        <AlertDialogContent<{
          name: string
        }>>
          {(state) => (
            <>
              <div data-slot="stack">
                <AlertDialogTitle>
                  Delete {state.payload?.name}?
                </AlertDialogTitle>
                <AlertDialogDescription>
                  The project and its files will be deleted for everyone on your
                  team.
                </AlertDialogDescription>
              </div>
              <div data-slot="row">
                <AlertDialogClose>Cancel</AlertDialogClose>
                <AlertDialogClose data-variant="solid" value="confirm">
                  Delete
                </AlertDialogClose>
              </div>
            </>
          )}
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}

export { Example }
删除一个项目。Cancel 或 Escape 会保留它;Delete 会移除它,并把焦点放到相邻一行的按钮上。Reset Projects 会把列表带回来。

当动作移除了打开对话框的按钮时,为焦点选择一个有用的去处。这个示例会聚焦相邻的一行,列表为空时聚焦 Reset Projects。

排队的问题

对同一个 confirm 函数的调用会排队等待。你可以一次问两个问题;第二个只会在第一个有了回答之后出现。

控制台
import {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogTitle,
  createConfirm,
} from "@ui-sdk/solid/alert-dialog"
import { useLog } from "./log"

function Example() {
  const confirm = createConfirm<{ name: string }>()
  const log = useLog()

  async function review() {
    const acme = confirm({ name: "Acme" })
    const globex = confirm({ name: "Globex" })
    const [first, second] = await Promise.all([acme, globex])
    log(`Acme: ${first ? "confirmed" : "canceled"}`)
    log(`Globex: ${second ? "confirmed" : "canceled"}`)
  }

  return (
    <div data-slot="stack">
      <button type="button" onClick={review}>
        Review Two Projects
      </button>
      <AlertDialog controller={confirm.controller}>
        <AlertDialogBackdrop />
        <AlertDialogContent<{
          name: string
        }>>
          {(state) => (
            <>
              <div data-slot="stack">
                <AlertDialogTitle>
                  Archive {state.payload?.name}?
                </AlertDialogTitle>
                <AlertDialogDescription>
                  Archived projects leave the active list. You can restore them
                  later.
                </AlertDialogDescription>
              </div>
              <div data-slot="row">
                <AlertDialogClose>Cancel</AlertDialogClose>
                <AlertDialogClose data-variant="solid" value="confirm">
                  Archive
                </AlertDialogClose>
              </div>
            </>
          )}
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}

export { Example }
选择 Review Two Projects。先回答 Acme 的问题,再回答 Globex 的问题。第二个回答进来后,控制台会显示两个回答。

样式

每个部件都有一个 data-slot,比如 alert-dialog-content,并通过数据属性下列出的属性展示状态。样式与动画涵盖状态属性以及入场和退场过渡。

AlertDialogContent

变量内容
--dialog-stackHow many dialogs are open above this one, nested inside it. 0 for the topmost.
--keyboard-insetHow many pixels of the page the on-screen keyboard covers, 0 without one.
--visual-viewport-widthThe width of the part of the page you can see.
--visual-viewport-heightThe height of the part of the page you can see, above the keyboard.
--visual-viewport-topHow far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up.

数据属性

AlertDialogTrigger

[data-slot="alert-dialog-trigger"]

属性含义
data-closedPresent while the dialog is closed, including while it animates out.
data-disabledPresent when the trigger is disabled.
data-openPresent while the dialog is open. On a trigger, while it's open from that trigger.

AlertDialogBackdrop

[data-slot="alert-dialog-backdrop"]

属性含义
data-closedPresent while the dialog is closed, including while it animates out.
data-openPresent while the dialog is open. On a trigger, while it's open from that trigger.
data-starting-stylePresent for the first frame. Style the state you animate from.
data-ending-stylePresent while the dialog animates out. Style the state you animate to.

AlertDialogContent

[data-slot="alert-dialog-content"]

属性含义
data-closedPresent while the dialog is closed, including while it animates out.
data-openPresent while the dialog is open. On a trigger, while it's open from that trigger.
data-starting-stylePresent for the first frame. Style the state you animate from.
data-ending-stylePresent while the dialog animates out. Style the state you animate to.
data-keyboardPresent while the on-screen keyboard covers part of the page.

AlertDialogClose

[data-slot="alert-dialog-close"]

属性含义
data-disabled
data-pendingPresent 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.
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 false while a form has unsaved changes, and ask in onDismissAttempt.
onDismissAttempt?((details: DialogDismissAttemptDetails) => void)
Runs when a dismissal was refused, because dismissible is 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<AlertDialogOpenChangeReason>) => void)
Runs when the alert dialog wants to open or close. details.reason says why, details.cancel() stops it, and details.returnValue is the value of the Close part that closed it.
onPayloadChange?((payload: unknown, details: ChangeDetails<AlertDialogPayloadChangeReason>) => void)
Runs when a trigger or a controller with another payload opens the alert dialog, before onOpenChange, or a controller's open({ 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() or createConfirm().

AlertDialogTrigger

disabled?boolean
Stops the trigger from opening the dialog. A native button can't be focused or pressed, unless focusableWhenDisabled is set.
focusableWhenDisabled?boolean
Keeps a disabled trigger in the tab order with aria-disabled instead 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". mod is Command on Apple platforms and Control elsewhere. Sets aria-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

让对话框后面的页面变暗。渲染一个 div,接受它的属性(props)和 render。

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. A container on the dialog still moves its backdrop, so leave it off.

AlertDialogTitle

问题本身。渲染一个 h2,内容把它用作无障碍名称。

AlertDialogDescription

同意后会发生什么。渲染一个 p,内容把它用作无障碍描述。

AlertDialogClose

value?string
Reported as returnValue in onOpenChange and by the controller's open(). createConfirm() resolves true for "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-busy and aria-disabled, screen readers hear the dialog's pendingAnnouncement after 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's error state until the next press, or until the dialog opens again. details.source says how the part was pressed, for changes made after an await.

AlertDialogShortcut

shortcut?string
The keys to show. Inside a trigger, its shortcut.

确认选项

OverlayHost 渲染问题时,共享的 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 modal setting. 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: ⌘K on Apple platforms and Ctrl+K elsewhere. 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 action finished.
shortcutKeyboardEvent
A keyboard shortcut, like a trigger's shortcut.
imperativenone
A controller or api call.

当对话框带着另一个 payload 打开时,onPayloadChange(payload, details) 在 onOpenChange 之前运行。对已打开的对话框调用 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 api call.

控制器

用 createAlertDialogController<Payload, Result>() 直接控制。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 signal aborts, or with reason "unmount" when the component leaves the page.
close(options?)(options?: (PopupChangeOptions<AlertDialogOpenChangeReason> & { returnValue?: Result | undefined; }) | undefined) => boolean
Closes it. returnValue is passed to the promise open() 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 放在最前面。触摸打开时改为聚焦内容,这样不会出现屏幕键盘,除非你设置了 initialFocus。Escape 会关闭对话框,但从不会因按压外部而关闭。其他初始和最终焦点目标见 Dialog。

这些行为由自动化测试覆盖:

Alert 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。