打开一个悬浮在页面之上的专注任务。

对话框给任务一块自己的空间:分享链接、编辑一条记录,或者收集几项信息。它负责焦点、Escape、外部按压,以及回到你开始的地方。

import {
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import { XIcon } from "lucide-react"

function Example() {
  return (
    <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>
  )
}

export { Example }
打开 Share,然后用任意一个 Close 按钮、Escape 或外部按压关闭它。焦点会回到 Share。

安装

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

组合

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

Dialog
├── DialogTrigger
├── DialogBackdrop
└── DialogContent
    ├── DialogTitle
    ├── DialogDescription
    └── DialogClose

标题为对话框命名,描述给它上下文。一个对话框可以有多个 Close 部件。给只有图标的关闭按钮一个无障碍名称,就像第一个示例那样。

backdrop 部件是可选的。没有它时,为内容的 ::backdrop 设置样式。如果一个问题需要用户明确作答,改用 Alert Dialog。

用法

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

import {
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"

function Example() {
  return (
    <Dialog>
      <DialogTrigger>Open</DialogTrigger>
      <DialogBackdrop />
      <DialogContent>
        <DialogTitle>Project details</DialogTitle>
        <DialogDescription>
          Review the details before continuing.
        </DialogDescription>
        <DialogClose>Close</DialogClose>
      </DialogContent>
    </Dialog>
  )
}

export { Example }

自己构建

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

share.ts
"use client"

import { dialog } from "@ui-sdk/core/dialog"
import { createParts } from "@ui-sdk/react/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" 把焦点放在对话框本身,这样阅读从顶部开始。

import {
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/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.",
]

function Example() {
  return (
    <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">
          {paragraphs.map((paragraph) => (
            <p key={paragraph}>{paragraph}</p>
          ))}
        </div>
        <div data-slot="row">
          <DialogClose>Decline</DialogClose>
          <DialogClose data-variant="solid" value="accept">
            Accept
          </DialogClose>
        </div>
      </DialogContent>
    </Dialog>
  )
}

export { Example }
在矮窗口中打开 Scrollable Content。滚动条款时,标题和 Decline/Accept 按钮保持在视野内。

表单

method="dialog" 的表单在有效提交时关闭对话框。提交按钮的 value 会成为 returnValue,就像 Close 部件的 value 一样。普通表单会保持打开,直到你自己关闭对话框。

控制台
"use client"

import {
  Dialog,
  DialogBackdrop,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  return (
    <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>
  )
}

export { Example }
打开 New Article,选择 Save Draft 或 Publish。控制台会记录所提交按钮的 value。标题为空时无法提交。

焦点

用 initialFocus 选择焦点从哪里开始,用 finalFocus 选择关闭后焦点去哪里。两者都接受一个选择器、一个元素,或一个返回它们的函数。默认回到触发器,或者回到在控制器打开对话框之前聚焦的元素。共用的焦点规则见浮层焦点。

<DialogContent
  initialFocus="#invite-email"
  finalFocus={() => nextStep.current}
/>

受控

传入 open,并在 onOpenChange 里更新它。用 details.cancel() 取消一次提议的变更。onOpenChangeComplete 报告打开或关闭何时完成;通用的变更约定见状态与事件。

控制台
"use client"

import * as React from "react"
import {
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/react/checkbox"
import { CheckIcon } from "lucide-react"
import { useLog } from "./log"

const topics = [
  { label: "Product updates", checked: true },
  { label: "Security alerts", checked: true },
  { label: "Weekly digest", checked: false },
]

function Example() {
  const log = useLog()
  const [open, setOpen] = React.useState(false)
  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <Checkbox
            checked={open}
            onCheckedChange={(next) => setOpen(next === true)}
          >
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          Open
        </label>
      </div>
      <Dialog
        open={open}
        onOpenChange={(next, details) => {
          setOpen(next)
          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">
            {topics.map((topic) => (
              <label data-slot="label" key={topic.label}>
                <Checkbox defaultChecked={topic.checked}>
                  <CheckboxIndicator>
                    <CheckIcon aria-hidden="true" />
                  </CheckboxIndicator>
                </Checkbox>
                {topic.label}
              </label>
            ))}
          </div>
          <div data-slot="row">
            <DialogClose data-variant="solid">Done</DialogClose>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
}

export { Example }
勾选 Open 或按 Notification Settings,然后关闭对话框。控制台会记录每次变更、它的原因以及何时完成。

键盘快捷键

触发器的 shortcut 让它能从键盘打开。mod+j 在 Apple 平台上表示 Command+J,在其他平台表示 Control+J。Shortcut 部件显示对应的按键,触发器暴露 aria-keyshortcuts。

"use client"

import {
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogShortcut,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import { PlusIcon } from "lucide-react"

function Example() {
  return (
    <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>
  )
}

export { Example }
按 Command+J 或 Control+J 打开 New contact。按钮上会显示按键,Escape 会把焦点还给它。

动画

内容和 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;
  }
}
控制台
"use client"

import {
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  return (
    <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>
  )
}

export { Example }
打开对话框再关闭它。控制台会记录每个动画何时结束;关闭一开始,焦点就会返回。

modal 控制对话框如何与页面共享空间:

  • true 是默认值,让页面不可交互、锁定滚动,并把 Tab 保持在内部。
  • "trap-focus" 把 Tab 保持在内部,同时页面仍然可以滚动和接受点击。点击页面也会关闭对话框,除非 closeOnOutsidePress 为 false。
  • false 让对话框与页面并排,焦点可以离开它。焦点在内部时 Escape 会关闭它;只有启用 closeOnOutsidePress 时,外部按压才会关闭它。

如果想在模态对话框打开时让页面的一小块区域保持可用,比如聊天启动器,就把它传给 persistentElements:一个元素或选择器的数组,或者一个在对话框打开时返回元素的函数。这些元素本身不会改变堆叠顺序。

对话框渲染在你放置它们的位置,并使用浏览器的顶层。如果它们的 DOM 需要放在别处,比如影子根(shadow root),就设置 container。浮层指南涵盖容器和 iframe。

"use client"

import * as React from "react"
import {
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/react/select"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/react/checkbox"
import { CheckIcon, ChevronDownIcon } from "lucide-react"

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

function Example() {
  const [mode, setMode] = React.useState<Mode>("false")
  const [outside, setOutside] = React.useState(false)
  const modal = mode === "true" ? true : mode === "false" ? false : "trap-focus"
  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <Select
          items={modes}
          value={mode}
          onValueChange={(next) => next && setMode(next as Mode)}
        >
          <SelectLabel>Modal</SelectLabel>
          <SelectTrigger>
            <SelectValue />
            <ChevronDownIcon />
          </SelectTrigger>
          <SelectContent>
            {modes.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
                <SelectItemIndicator>
                  <CheckIcon />
                </SelectItemIndicator>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <label data-slot="label">
          <Checkbox
            checked={outside}
            onCheckedChange={(next) => setOutside(next === true)}
          >
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          Close on outside press
        </label>
      </div>
      <Dialog modal={modal} closeOnOutsidePress={outside}>
        <DialogTrigger>Open Notes</DialogTrigger>
        {modal === true && <DialogBackdrop />}
        <DialogContent>
          <div data-slot="stack">
            <DialogTitle>Notes</DialogTitle>
            <DialogDescription>{notes[mode]}</DialogDescription>
          </div>
          <textarea
            aria-label="Notes"
            defaultValue="Call the printer about the proofs."
          />
          <div data-slot="row">
            <DialogClose data-variant="solid">Done</DialogClose>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
}

export { Example }
选择一种模式,打开 Notes,试试 Tab 或点击页面。勾选 Close on outside press,比较不同的关闭行为。

在 frame 内

对话框会打开在整个页面上方。给内容设置 inline,让它和它的 backdrop 部件留在页面中的原位,比如应用预览内部。由你的 CSS 在 frame 中为它们设置尺寸和位置。把它和 modal="trap-focus" 搭配,frame 周围的页面仍然可用。

import {
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"

function Example() {
  return (
    <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>
  )
}

export { Example }
打开 Delete Draft。对话框和它的变暗遮罩只覆盖 frame,Tab 也保持在对话框内部。

关闭有未保存更改的表单前警告

有未保存的更改时,把 dismissible 设为 false。这时 Escape、外部按压或返回手势都会让对话框保持打开,并报告 onDismissAttempt。显式的 Close 部件和控制器调用仍然有效,所以你可以提供一条明确的退出途径。

"use client"

import * as React from "react"
import {
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"
import { Field, FieldControl, FieldLabel } from "@ui-sdk/react/field"

function Example() {
  const [open, setOpen] = React.useState(false)
  const [dirty, setDirty] = React.useState(false)
  const [asking, setAsking] = React.useState(false)
  const post = React.useRef<HTMLTextAreaElement>(null)
  const close = () => {
    setOpen(false)
    setDirty(false)
    setAsking(false)
  }
  return (
    <Dialog
      open={open}
      onOpenChange={(next) => (next ? setOpen(true) : close())}
      dismissible={!dirty}
      onDismissAttempt={() => setAsking(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
            render={<textarea ref={post} placeholder="What's new?" />}
            onChange={(event) => setDirty(event.currentTarget.value !== "")}
          />
        </Field>
        {asking ? (
          <div data-slot="row" role="alert">
            Discard your changes?
            <div data-slot="row">
              <button
                type="button"
                onClick={() => {
                  setAsking(false)
                  post.current?.focus()
                }}
              >
                Keep Editing
              </button>
              <button data-variant="solid" type="button" onClick={close}>
                Discard
              </button>
            </div>
          </div>
        ) : (
          <div data-slot="row">
            <DialogClose data-variant="solid" value="post">
              Post
            </DialogClose>
          </div>
        )}
      </DialogContent>
    </Dialog>
  )
}

export { Example }
输入一篇文章,然后按 Escape 或点击外部。Keep editing 回到输入框;Discard 关闭对话框并清空草稿。

嵌套对话框

在另一个对话框里打开的对话框会加入它的栈。Escape 关闭最上层的对话框,并把焦点还给它的触发器。关闭父级也会关闭它的子级。data-nested-open 和 --dialog-stack 让你显示哪一层处于活动状态。

import {
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"

function Example() {
  return (
    <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>
  )
}

export { Example }
打开 Account,然后打开 Change Password。按一次 Escape 回到 Account,再按一次关闭它。

从菜单项打开

把对话框渲染在菜单之外,用对话框的控制器打开它。当菜单项消失时,菜单的触发器就成为焦点返回的位置。

"use client"

import * as React from "react"
import {
  createDialogController,
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
} from "@ui-sdk/react/dialog"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import { Menu, MenuContent, MenuItem, MenuTrigger } from "@ui-sdk/react/menu"
import { CopyIcon, EllipsisIcon, PencilIcon } from "lucide-react"

function Example() {
  const [rename] = React.useState(() => createDialogController())
  return (
    <>
      <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>
    </>
  )
}

export { Example }
打开 File Actions,选择 Rename。关闭对话框,焦点会回到 File Actions 按钮。

从任意位置打开

把多个触发器连接到同一个 createDialogController<Payload, Result>()。每个触发器传一个 payload,内容从自己的状态里读取它。controller.open({ payload }) 从代码打开对话框,返回一个在关闭时兑现的 promise,带着原因和可选的 returnValue。每个触发器仍然是它打开的那个对话框的焦点返回目标。共用的控制器模式见控制器。

控制台
"use client"

import * as React from "react"
import {
  createDialogController,
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/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" },
]

function Example() {
  const [reminder] = React.useState(() =>
    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})`
    )
  }

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" onClick={remindFromCode}>
          Open from Code
        </button>
      </div>
      <ul data-slot="list">
        {invoices.map((invoice) => (
          <li data-slot="row" key={invoice.id}>
            {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>
        ))}
      </ul>
      <Dialog
        controller={reminder}
        onOpenChange={(open, details) => {
          if (!open && details.returnValue === "send") {
            log("Reminder sent")
          }
        }}
      >
        <DialogBackdrop />
        <DialogContent<Invoice>>
          {(state) => {
            const invoice = state.payload
            return (
              <>
                <div data-slot="stack">
                  <DialogTitle>Remind {invoice?.customer}</DialogTitle>
                  <DialogDescription>
                    {invoice?.id} for {invoice?.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>
              </>
            )
          }}
        </DialogContent>
      </Dialog>
    </div>
  )
}

export { Example }
从任意一张未付发票打开提醒,或者按 Open from Code。同一个对话框显示那张发票,控制台会记录它是如何关闭的。

呈现方式

presentation="sheet" 把同一个任务呈现为底部面板(sheet)。用 "auto" 会在小尺寸触摸屏上选择 sheet,其他情况下使用居中的对话框,每次打开时决定。向下滑动会关闭可关闭的 sheet;受保护的 sheet 会弹回,并报告一次关闭尝试。

设置 data-presentation 的样式来同时支持两种布局。sheet 自己管理位置和移动,所以不要给它套用居中对话框的位移。没有 Backdrop 部件时,--sheet-backdrop 为变暗的页面设置样式。

"use client"

import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"

function Example() {
  return (
    <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>
  )
}

export { Example }
以 sheet 形式打开 Edit Profile。在触摸屏上向下拖动关闭它,或者用 Cancel 或 Save Changes。

自定义渲染

每个部件都接受 render。传入一个元素,它的属性(props)会与部件的合并;或者传入一个函数,接收属性和部件的状态。

import {
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogShortcut,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"

function Example() {
  return (
    <Dialog>
      <DialogTrigger
        shortcut="mod+i"
        render={(props, state) => (
          <button {...props}>
            {state.open ? "Viewing" : "View Details"}
            <DialogShortcut>{(shortcut) => shortcut.text}</DialogShortcut>
          </button>
        )}
      />
      <DialogBackdrop />
      <DialogContent>
        {(state) => (
          <>
            <div data-slot="stack">
              <DialogTitle render={<h3 />}>Details</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"
                render={<a href="https://example.com/details" />}
              >
                Open the Full Page
              </DialogClose>
            </div>
          </>
        )}
      </DialogContent>
    </Dialog>
  )
}

export { Example }
打开 View Details。触发器的标签和描述来自它们的状态,Close 渲染为一个链接。

样式

每个部件都有一个 data-slot,比如 dialog-content,并通过数据属性下列出的属性展示状态。用 data-open 和 data-closed 表示每种状态,用 data-starting-style 和 data-ending-style 表示过渡。

DialogContent

变量内容
--dialog-stackHow many dialogs are open above this one, nested inside it. 0 for the topmost.
--keyboard-insetUnless it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one.
--visual-viewport-widthUnless it presents as a sheet: the width of the part of the page you can see.
--visual-viewport-heightUnless it presents as a sheet: the height of the part of the page you can see, above the keyboard.
--visual-viewport-topUnless 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-progressWhile 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-dimWhile it presents as a sheet: how dim the page behind is, from 0 to 1. The backdrop's opacity follows it.
--drawer-expandWhile 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-stackWhile 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-backdropSet it yourself: the color the page dims to while it presents as a sheet. Black at 0.2 by default.

Viewport

变量内容
--keyboard-insetWhile it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one.
--visual-viewport-widthWhile it presents as a sheet: the width of the part of the page you can see.
--visual-viewport-heightWhile it presents as a sheet: the height of the part of the page you can see, above the keyboard.
--visual-viewport-topWhile 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-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.

DialogBackdrop

[data-slot="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.

DialogContent

[data-slot="dialog-content"]

属性含义
data-closedPresent while the dialog is closed, including while it animates out.
data-presentationdialogsheetHow the dialog presents this time it's open.
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.

DialogClose

[data-slot="dialog-close"]

属性含义
data-disabled
data-pendingPresent on a Close part while its action runs.

API 参考

属性和回调与下面相同,都作为 React props。

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 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) => void)
Runs when the dialog wants to open or close. details.reason says why, details.cancel() stops it, and details.returnValue carries 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's open({ payload }) on the open dialog. details.cancel() keeps the previous payload.
modal?"trap-focus" | boolean
true: 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 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, 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. A container on the dialog still moves its backdrop, so leave it off.

DialogTitle

为对话框命名。渲染一个 h2。

DialogDescription

在渲染期间描述对话框。渲染一个 p。

DialogClose

它的 action 接收事件和 { source },即部件是如何被按压的,Button 对此有说明。

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.

DialogShortcut

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

状态

每个部件的 render 函数、基于状态的类名和槽位收到什么。

DialogTrigger:

openboolean
Whether the dialog is open from this trigger.
disabledboolean
Set by the trigger's disabled prop, 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 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" | "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: ⌘K on Apple platforms and Ctrl+K elsewhere. 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 action finished.
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 api call.

对于 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.

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 signal aborts, or with reason "unmount" when the component leaves the page.
close(options?)(options?: (PopupChangeOptions<DialogOpenChangeReason> & { 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<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.

事件

回调先收到新状态,再收到详情。

属性所属收到
onOpenChangeDialog(open, details): 新状态、原因以及任何 returnValue
onOpenChangeCompleteDialog(open), 在动画之后
onPayloadChangeDialog(payload, details): 内容的新 payload,以及原因
onDismissAttemptDialog({ reason, event }), 当一次关闭被拒绝时

无障碍

触发器是一个打开对话框的按钮,对话框遵循 WAI-ARIA 模态对话框模式:模态时带有 aria-modal,由标题提供名称,只有在描述被渲染时才由描述说明。下面每一行都是一个自动化测试。

键盘

按键作用
Enter, Space在触发器上打开对话框
Tab, Shift+Tab在对话框的控件之间移动,模态时保持在内部
Escape关闭最上层的对话框,并把焦点还给它的触发器
触发器的快捷键从页面上的任何位置打开它的对话框

经过测试的行为

Trigger
  • Advertises a dialog.
  • Click opens the dialog.
  • Enter opens the dialog.
  • Space opens the dialog.
Focus
  • 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.
Dismissal
  • 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.
Presses
  • 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.
Modal
  • 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.
Nested dialogs
  • 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 that closes exactly one thing
  • Escape while an input method is composing text keeps the dialog open.
  • Escape closes a non-modal dialog only while focus is inside it.
Focus that always lands somewhere useful
  • 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 outside is inert, except what must stay live
  • The page outside is inert while open and restored exactly after.
  • A live region outside the dialog keeps announcing while it's open.
Non-modal dialogs that behave like the APG
  • Tab leaves a non-modal dialog and the dialog stays open.
  • A non-modal dialog stays open when the page is clicked.
Nested and stacked
  • A dialog opened inside a dialog marks both, for styling.
  • Closing the parent closes the nested dialog with reason parent-close.
Opening from anywhere
  • 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.
Shortcuts
  • A trigger connected through a controller shows its shortcut in a Shortcut part, and binds it.
Web components
  • The open property and attribute open and close the dialog. 仅在 Web components 运行。

运行于 React、Vue 和 web components。

Opening a dialog from a menu item
  • 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 and focus around a dialog opened from a menu item
  • 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 运行。
Shortcuts
  • 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.
A dirty form
  • Refuses Escape and outside presses, and reports each attempt.
  • A clean form closes on Escape.
Persistent elements
  • Stay usable while a modal dialog is open, and pressing them keeps it open.
Async actions
  • Keep the alert dialog open and pending, then close with reason action.
  • A failed action keeps the alert dialog open and stops pending.
Popups inside a portaled popover
  • A menu and a dialog inside it render into the popover's container.
Android's back gesture
  • 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。