# Dialog

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

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

```ts title="basic.ts"
import "@ui-sdk/web/dialog"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"
import { createElement, X } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-dialog>
      <ui-dialog-trigger>
        <button>Share</button>
      </ui-dialog-trigger>
      <ui-dialog-backdrop hidden></ui-dialog-backdrop>
      <ui-dialog-content hidden>
        <div data-slot="stack">
          <ui-dialog-title>Share link</ui-dialog-title>
          <ui-dialog-description>Anyone who has this link will be able to view this.</ui-dialog-description>
        </div>
        <ui-field>
          <ui-field-label>Link</ui-field-label>
          <ui-input>
            <input value="https://example.com/project" readonly />
          </ui-input>
        </ui-field>
        <div data-slot="row">
          <ui-dialog-close>
            <button data-variant="solid">Done</button>
          </ui-dialog-close>
        </div>
        <ui-dialog-close>
          <button aria-label="Close">${createElement(X, { "aria-hidden": "true" }).outerHTML}</button>
        </ui-dialog-close>
      </ui-dialog-content>
    </ui-dialog>
  `
}

export { mount }
```

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

## 安装
```bash
npm install @ui-sdk/web @ui-sdk/core
```

导入组件以注册它的元素。这个导入在服务端是安全的。

```ts
import "@ui-sdk/web/dialog"
```

## 组合
用下面的组合构建一个 `ui-dialog`：

```text
ui-dialog
├── ui-dialog-trigger
│   └── button
├── ui-dialog-backdrop
└── ui-dialog-content
    ├── ui-dialog-title
    ├── ui-dialog-description
    └── ui-dialog-close
        └── button
```

标题为对话框命名，描述给它上下文。一个对话框可以有多个 Close 部件，每个包着自己的原生按钮。给只有图标的关闭按钮一个无障碍名称，就像第一个示例那样。给内容和背景部件加上 `hidden`，让它们在元素升级之前保持隐藏。

`backdrop` 部件是可选的。没有它时，为内容的 `::backdrop` 设置样式。如果一个问题需要用户明确作答，改用 [Alert Dialog](/docs/web-components/components/alert-dialog)。

## 用法
导入各个部件并把它们组合起来：

```html
<script type="module">
  import "@ui-sdk/web/dialog"
</script>

<ui-dialog>
  <ui-dialog-trigger><button>Open</button></ui-dialog-trigger>
  <ui-dialog-backdrop hidden></ui-dialog-backdrop>
  <ui-dialog-content hidden>
    <ui-dialog-title>Project details</ui-dialog-title>
    <ui-dialog-description
      >Review the details before continuing.</ui-dialog-description
    >
    <ui-dialog-close><button>Close</button></ui-dialog-close>
  </ui-dialog-content>
</ui-dialog>
```

## 自己构建
`@ui-sdk/web/dialog` 自带现成的 `ui-dialog` 元素。如果你想用自己的元素名构建自己的版本，从 `@ui-sdk/core` 里的 `dialog` 原语（primitive）开始：

```ts title="share-elements.ts"
import { dialog } from "@ui-sdk/core/dialog"
import { createParts, wrappedButton } from "@ui-sdk/web"

createParts(dialog, {
  root: "share-dialog",
  trigger: { tag: "share-trigger", target: wrappedButton, display: "contents" },
  backdrop: "share-backdrop",
  content: "share-panel",
  title: "share-title",
  description: "share-description",
  close: { tag: "share-close", target: wrappedButton, display: "contents" },
})
```

```html
<share-dialog>
  <share-trigger><button>Share</button></share-trigger>
  <share-backdrop hidden></share-backdrop>
  <share-panel hidden>
    <share-title>Share this page</share-title>
    <share-description>Anyone with the link can view it.</share-description>
    <share-close><button>Done</button></share-close>
  </share-panel>
</share-dialog>
```

每个元素都保留其现成对应元素的行为、状态和数据属性：内容在顶层（top layer）打开，把焦点困在内部，并让页面不可交互（inert）。更多内容见[渲染](/docs/web-components/rendering)和[自定义部件](/docs/web-components/custom-parts)。

## 可滚动内容
把标题和操作按钮留在滚动区域之外。限制视口高度、让中间的网格行收缩，再加上 `overflow-y: auto`，长内容就仍然可用。`initial-focus="content"` 把焦点放在对话框本身，这样阅读从顶部开始。

```ts title="scrollable.ts"
import "@ui-sdk/web/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 mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-dialog>
      <ui-dialog-trigger>
        <button>Scrollable Content</button>
      </ui-dialog-trigger>
      <ui-dialog-backdrop hidden></ui-dialog-backdrop>
      <ui-dialog-content initial-focus="content" hidden>
        <div data-slot="stack">
          <ui-dialog-title>Terms of service</ui-dialog-title>
          <ui-dialog-description>Please read before you continue.</ui-dialog-description>
        </div>
        <div data-slot="scroll">
          ${paragraphs.map((paragraph) => `<p>${paragraph}</p>`).join("")}
        </div>
        <div data-slot="row">
          <ui-dialog-close>
            <button>Decline</button>
          </ui-dialog-close>
          <ui-dialog-close value="accept">
            <button data-variant="solid">Accept</button>
          </ui-dialog-close>
        </div>
      </ui-dialog-content>
    </ui-dialog>
  `
}

export { mount }
```

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

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

```ts title="form.ts"
import "@ui-sdk/web/dialog"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-dialog>
      <ui-dialog-trigger>
        <button>New Article</button>
      </ui-dialog-trigger>
      <ui-dialog-backdrop hidden></ui-dialog-backdrop>
      <ui-dialog-content hidden>
        <div data-slot="stack">
          <ui-dialog-title>New article</ui-dialog-title>
          <ui-dialog-description>Save it as a draft or publish it now.</ui-dialog-description>
        </div>
        <form data-slot="stack" method="dialog">
          <ui-field>
            <ui-field-label>Title</ui-field-label>
            <ui-input>
              <input required value="Shipping updates for spring" />
            </ui-input>
          </ui-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>
      </ui-dialog-content>
    </ui-dialog>
  `
  root.querySelector("ui-dialog")!.addEventListener("openchange", (event) => {
    const { value, reason, returnValue } = event.detail
    if (!value) {
      log(root, returnValue ? `Saved as ${returnValue}` : `Closed (${reason})`)
    }
  })
}

export { mount }
```

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

## 焦点
用 `initial-focus` 选择焦点从哪里开始，用 `final-focus` 选择关闭后焦点去哪里。两者都接受一个选择器。默认回到触发器，或者回到在控制器打开对话框之前聚焦的元素。共用的焦点规则见[浮层焦点](https://ui-sdk.cn/docs/web-components/popups#focus)。

```html
<ui-dialog-content
  initial-focus="#invite-email"
  final-focus="#next-step"
  hidden
></ui-dialog-content>
```

## 受控
设置元素的 `open` property，并监听 `openchange`，让另一个控件保持同步。用 `event.preventDefault()` 取消一次提议的变更。`openchangecomplete` 报告打开或关闭何时完成；通用的变更约定见[状态与事件](/docs/web-components/state-and-events)。

```ts title="controlled.ts"
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/dialog"
import { Check, createElement } from "lucide"
import { log } from "./log"

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

const check = createElement(Check, { "aria-hidden": "true" }).outerHTML

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <ui-checkbox>
            <ui-checkbox-indicator>${check}</ui-checkbox-indicator>
          </ui-checkbox>
          Open
        </label>
      </div>
      <ui-dialog>
        <ui-dialog-trigger>
          <button>Notification Settings</button>
        </ui-dialog-trigger>
        <ui-dialog-backdrop hidden></ui-dialog-backdrop>
        <ui-dialog-content hidden>
          <div data-slot="stack">
            <ui-dialog-title>Notification settings</ui-dialog-title>
            <ui-dialog-description>Choose what we email you about.</ui-dialog-description>
          </div>
          <div data-slot="stack">
            ${topics
              .map(
                (topic) => `
                  <label data-slot="label">
                    <ui-checkbox${topic.checked ? " default-checked" : ""}>
                      <ui-checkbox-indicator>${check}</ui-checkbox-indicator>
                    </ui-checkbox>
                    ${topic.label}
                  </label>
                `
              )
              .join("")}
          </div>
          <div data-slot="row">
            <ui-dialog-close>
              <button data-variant="solid">Done</button>
            </ui-dialog-close>
          </div>
        </ui-dialog-content>
      </ui-dialog>
    </div>
  `
  const toggle = root.querySelector("ui-checkbox")!
  const dialog = root.querySelector("ui-dialog")!
  toggle.addEventListener("checkedchange", (event) => {
    dialog.open = event.detail.value === true
  })
  dialog.addEventListener("openchange", (event) => {
    const { value, reason } = event.detail
    toggle.checked = value
    log(root, `${value ? "Opened" : "Closed"} (${reason})`)
  })
  dialog.addEventListener("openchangecomplete", (event) => {
    log(root, event.detail.value ? "Finished opening" : "Finished closing")
  })
}

export { mount }
```

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

## 键盘快捷键
触发器的 `shortcut` 让它能从键盘打开。`mod+j` 在 Apple 平台上表示 Command+J，在其他平台表示 Control+J。触发器按钮内部的 `ui-dialog-shortcut` 显示对应的按键，触发器暴露 `aria-keyshortcuts`。

```ts title="shortcut.ts"
import "@ui-sdk/web/dialog"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"
import { createElement, Plus } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-dialog>
      <ui-dialog-trigger shortcut="mod+j">
        <button>
          ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
          New Contact
          <ui-dialog-shortcut></ui-dialog-shortcut>
        </button>
      </ui-dialog-trigger>
      <ui-dialog-backdrop hidden></ui-dialog-backdrop>
      <ui-dialog-content hidden>
        <div data-slot="stack">
          <ui-dialog-title>New contact</ui-dialog-title>
          <ui-dialog-description>Add someone to your address book.</ui-dialog-description>
        </div>
        <form data-slot="stack" method="dialog">
          <ui-field>
            <ui-field-label>Name</ui-field-label>
            <ui-input>
              <input name="name" required placeholder="Kofi Mensah" />
            </ui-input>
          </ui-field>
          <ui-field>
            <ui-field-label>Email</ui-field-label>
            <ui-input>
              <input name="email" type="email" required placeholder="kofi@example.com" />
            </ui-input>
          </ui-field>
          <div data-slot="row">
            <ui-dialog-close>
              <button type="button">Cancel</button>
            </ui-dialog-close>
            <button data-variant="solid" type="submit" value="save">Save Contact</button>
          </div>
        </form>
      </ui-dialog-content>
    </ui-dialog>
  `
}

export { mount }
```

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

## 动画
内容和 `backdrop` 部件在打开期间带有 `data-starting-style`，关闭期间带有 `data-ending-style`。从这些状态做过渡，对话框会保持挂载，直到退场结束。`openchangecomplete` 在过渡之后触发，`keep-mounted` 让内容在关闭期间留在页面里。

```css
[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;
  }
}
```

```ts title="animation.ts"
import "@ui-sdk/web/dialog"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-dialog>
      <ui-dialog-trigger>
        <button>Slide In</button>
      </ui-dialog-trigger>
      <ui-dialog-backdrop hidden></ui-dialog-backdrop>
      <ui-dialog-content keep-mounted hidden>
        <div data-slot="stack">
          <ui-dialog-title>Slide and fade</ui-dialog-title>
          <ui-dialog-description>300ms in and out. Focus returns as soon as it starts closing.</ui-dialog-description>
        </div>
        <div data-slot="row">
          <ui-dialog-close>
            <button data-variant="solid">Close</button>
          </ui-dialog-close>
        </div>
      </ui-dialog-content>
    </ui-dialog>
  `
  root
    .querySelector("ui-dialog")!
    .addEventListener("openchangecomplete", (event) => {
      log(root, event.detail.value ? "Finished opening" : "Finished closing")
    })
}

export { mount }
```

打开对话框再关闭它。控制台会记录每个动画何时结束；关闭一开始，焦点就会返回。

## 模态
`modal` 控制对话框如何与页面共享空间：

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

如果想在模态对话框打开时让页面的一小块区域保持可用，比如聊天启动器，就把它列进 `persistent-elements`：一个用逗号分隔的选择器列表。给 `persistentElements` property 赋一个元素数组，或者在对话框打开时返回元素的函数。这些元素本身不会改变堆叠顺序。

对话框渲染在你放置它们的位置，并使用浏览器的顶层。如果它们的 DOM 需要放在别处，比如影子根（shadow root），就把 `container` 设为选择器。[浮层指南](https://ui-sdk.cn/docs/web-components/popups#hidden-content-and-containers)涵盖容器和 iframe。

```ts title="modal.ts"
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/dialog"
import "@ui-sdk/web/select"
import { Check, ChevronDown, createElement } from "lucide"

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

const check = createElement(Check, { "aria-hidden": "true" }).outerHTML

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <ui-select default-value="false">
          <ui-select-label>Modal</ui-select-label>
          <ui-select-trigger>
            <button>
              <ui-select-value></ui-select-value>
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-select-trigger>
          <ui-select-content hidden>
            ${modes
              .map(
                (option) => `
                  <ui-select-item value="${option.value}">
                    ${option.label}
                    <ui-select-item-indicator>${check}</ui-select-item-indicator>
                  </ui-select-item>
                `
              )
              .join("")}
          </ui-select-content>
        </ui-select>
        <label data-slot="label">
          <ui-checkbox>
            <ui-checkbox-indicator>${check}</ui-checkbox-indicator>
          </ui-checkbox>
          Close on outside press
        </label>
      </div>
      <ui-dialog modal="false">
        <ui-dialog-trigger>
          <button>Open Notes</button>
        </ui-dialog-trigger>
        <ui-dialog-content hidden>
          <div data-slot="stack">
            <ui-dialog-title>Notes</ui-dialog-title>
            <ui-dialog-description>${notes.false}</ui-dialog-description>
          </div>
          <textarea aria-label="Notes">Call the printer about the proofs.</textarea>
          <div data-slot="row">
            <ui-dialog-close>
              <button data-variant="solid">Done</button>
            </ui-dialog-close>
          </div>
        </ui-dialog-content>
      </ui-dialog>
    </div>
  `
  const dialog = root.querySelector("ui-dialog")!
  const trigger = root.querySelector("ui-dialog-trigger")!
  const description = root.querySelector("ui-dialog-description")!
  const backdrop = document.createElement("ui-dialog-backdrop")
  root.querySelector("ui-select")!.addEventListener("valuechange", (event) => {
    const mode = event.detail.value as Mode | null
    if (!mode) {
      return
    }
    dialog.setAttribute("modal", mode)
    if (mode === "true") {
      trigger.after(backdrop)
    } else {
      backdrop.remove()
    }
    description.textContent = notes[mode]
  })
  root
    .querySelector("ui-checkbox")!
    .addEventListener("checkedchange", (event) => {
      dialog.setAttribute(
        "close-on-outside-press",
        String(event.detail.value === true)
      )
    })
}

export { mount }
```

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

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

```ts title="inline.ts"
import "@ui-sdk/web/dialog"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="dialog-frame">
      <ui-dialog modal="trap-focus" close-on-outside-press="false">
        <ui-dialog-trigger>
          <button>Delete Draft</button>
        </ui-dialog-trigger>
        <ui-dialog-backdrop hidden></ui-dialog-backdrop>
        <ui-dialog-content inline hidden>
          <div data-slot="stack">
            <ui-dialog-title>Delete this draft?</ui-dialog-title>
            <ui-dialog-description>The preview keeps its dialog inside the frame.</ui-dialog-description>
          </div>
          <div data-slot="row">
            <ui-dialog-close>
              <button>Cancel</button>
            </ui-dialog-close>
            <ui-dialog-close>
              <button data-variant="destructive">Delete</button>
            </ui-dialog-close>
          </div>
        </ui-dialog-content>
      </ui-dialog>
    </div>
  `
}

export { mount }
```

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

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

```ts title="dirty-form.ts"
import "@ui-sdk/web/dialog"
import "@ui-sdk/web/field"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-dialog>
      <ui-dialog-trigger>
        <button>Write a Post</button>
      </ui-dialog-trigger>
      <ui-dialog-backdrop hidden></ui-dialog-backdrop>
      <ui-dialog-content hidden>
        <div data-slot="stack">
          <ui-dialog-title>New post</ui-dialog-title>
          <ui-dialog-description>Share an update with your team.</ui-dialog-description>
        </div>
        <ui-field>
          <ui-field-label>Post</ui-field-label>
          <textarea placeholder="What's new?"></textarea>
        </ui-field>
        <div data-slot="row" role="alert" hidden>
          Discard your changes?
          <div data-slot="row">
            <button type="button">Keep Editing</button>
            <button data-variant="solid" type="button">Discard</button>
          </div>
        </div>
        <div data-slot="row">
          <ui-dialog-close value="post">
            <button data-variant="solid">Post</button>
          </ui-dialog-close>
        </div>
      </ui-dialog-content>
    </ui-dialog>
  `
  const dialog = root.querySelector("ui-dialog")!
  const post = root.querySelector("textarea")!
  const alert = root.querySelector<HTMLElement>('[role="alert"]')!
  const actions = root.querySelector<HTMLElement>(
    'ui-dialog-content > [data-slot="row"]:not([role])'
  )!
  const [keep, discard] = alert.querySelectorAll("button")
  const ask = (asking: boolean) => {
    alert.hidden = !asking
    actions.hidden = asking
  }
  post.addEventListener("input", () => {
    if (post.value) {
      dialog.setAttribute("dismissible", "false")
    } else {
      dialog.removeAttribute("dismissible")
    }
  })
  dialog.addEventListener("dismissattempt", () => ask(true))
  keep.addEventListener("click", () => {
    ask(false)
    post.focus()
  })
  discard.addEventListener("click", () => (dialog.open = false))
  dialog.addEventListener("openchange", (event) => {
    if (event.detail.value) {
      return
    }
    ask(false)
    post.value = ""
    dialog.removeAttribute("dismissible")
  })
}

export { mount }
```

输入一篇文章，然后按 Escape 或点击外部。Keep editing 回到输入框；Discard 关闭对话框并清空草稿。

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

```ts title="nested.ts"
import "@ui-sdk/web/dialog"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-dialog>
      <ui-dialog-trigger>
        <button>Account</button>
      </ui-dialog-trigger>
      <ui-dialog-backdrop hidden></ui-dialog-backdrop>
      <ui-dialog-content hidden>
        <div data-slot="stack">
          <ui-dialog-title>Account</ui-dialog-title>
          <ui-dialog-description>Manage how you sign in.</ui-dialog-description>
        </div>
        <div data-slot="card">
          <div data-slot="stack">
            <span>Password</span>
            <span data-slot="hint">Last changed 3 months ago</span>
          </div>
          <ui-dialog>
            <ui-dialog-trigger>
              <button>Change Password</button>
            </ui-dialog-trigger>
            <ui-dialog-backdrop hidden></ui-dialog-backdrop>
            <ui-dialog-content hidden>
              <div data-slot="stack">
                <ui-dialog-title>Change password</ui-dialog-title>
                <ui-dialog-description>Use at least 12 characters.</ui-dialog-description>
              </div>
              <ui-field>
                <ui-field-label>New password</ui-field-label>
                <ui-input>
                  <input type="password" />
                </ui-input>
              </ui-field>
              <div data-slot="row">
                <ui-dialog-close>
                  <button>Cancel</button>
                </ui-dialog-close>
                <ui-dialog-close>
                  <button data-variant="solid">Update</button>
                </ui-dialog-close>
              </div>
            </ui-dialog-content>
          </ui-dialog>
        </div>
        <div data-slot="row">
          <ui-dialog-close>
            <button data-variant="solid">Done</button>
          </ui-dialog-close>
        </div>
      </ui-dialog-content>
    </ui-dialog>
  `
}

export { mount }
```

打开 Account，然后打开 Change Password。按一次 Escape 回到 Account，再按一次关闭它。

## 从菜单项打开
把对话框渲染在菜单之外，用它的 `api.open()` 打开它。当菜单项消失时，菜单的触发器就成为焦点返回的位置。

```ts title="from-menu.ts"
import "@ui-sdk/web/dialog"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"
import "@ui-sdk/web/menu"
import { Copy, createElement, Ellipsis, Pencil } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-menu>
      <ui-menu-trigger>
        <button aria-label="File actions">${createElement(Ellipsis, { "aria-hidden": "true" }).outerHTML}</button>
      </ui-menu-trigger>
      <ui-menu-content hidden>
        <ui-menu-item value="rename">
          ${createElement(Pencil, { "aria-hidden": "true" }).outerHTML}
          Rename…
        </ui-menu-item>
        <ui-menu-item value="duplicate">
          ${createElement(Copy, { "aria-hidden": "true" }).outerHTML}
          Duplicate
        </ui-menu-item>
      </ui-menu-content>
    </ui-menu>
    <ui-dialog>
      <ui-dialog-backdrop hidden></ui-dialog-backdrop>
      <ui-dialog-content hidden>
        <div data-slot="stack">
          <ui-dialog-title>Rename file</ui-dialog-title>
          <ui-dialog-description>Names must be unique in a folder.</ui-dialog-description>
        </div>
        <ui-field>
          <ui-field-label>Name</ui-field-label>
          <ui-input>
            <input value="report.pdf" />
          </ui-input>
        </ui-field>
        <div data-slot="row">
          <ui-dialog-close>
            <button>Cancel</button>
          </ui-dialog-close>
          <ui-dialog-close value="rename">
            <button data-variant="solid">Rename</button>
          </ui-dialog-close>
        </div>
      </ui-dialog-content>
    </ui-dialog>
  `
  const dialog = root.querySelector("ui-dialog")!
  root.querySelector("ui-menu")!.addEventListener("action", (event) => {
    if (event.detail.value === "rename") {
      dialog.api.open()
    }
  })
}

export { mount }
```

打开 File Actions，选择 Rename。关闭对话框，焦点会回到 File Actions 按钮。

## 从任意位置打开
用 `for="dialog-id"` 连接对话框之外的触发器，并给每个触发器一个 `payload` property。对话框的 `payloadchange` 事件在 `event.detail.value` 里携带它。对话框的 `api.open({ payload })` 从代码打开它，返回一个在关闭时兑现的 promise，带着原因和可选的 `returnValue`。每个触发器仍然是它打开的那个对话框的焦点返回目标。共用的控制器模式见[控制器](/docs/web-components/controllers)。

```ts title="payload.ts"
import "@ui-sdk/web/dialog"
import type { UiDialogElement } from "@ui-sdk/web/dialog"
import { log } 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 mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button">Open from Code</button>
      </div>
      <ul data-slot="list"></ul>
      <ui-dialog id="invoice-reminder">
        <ui-dialog-backdrop hidden></ui-dialog-backdrop>
        <ui-dialog-content hidden>
          <div data-slot="stack">
            <ui-dialog-title></ui-dialog-title>
            <ui-dialog-description></ui-dialog-description>
          </div>
          <div data-slot="row">
            <ui-dialog-close>
              <button>Cancel</button>
            </ui-dialog-close>
            <ui-dialog-close value="send">
              <button data-variant="solid">Send reminder</button>
            </ui-dialog-close>
          </div>
        </ui-dialog-content>
      </ui-dialog>
    </div>
  `
  const list = root.querySelector("ul")!
  const dialog = root.querySelector<UiDialogElement<Invoice>>("ui-dialog")!
  for (const invoice of invoices) {
    const row = document.createElement("li")
    row.dataset.slot = "row"
    row.innerHTML = `${invoice.customer}<span data-slot="hint">${invoice.amount} · ${invoice.status}</span>`
    const trigger = Object.assign(document.createElement("ui-dialog-trigger"), {
      payload: invoice,
    })
    trigger.setAttribute("for", "invoice-reminder")
    if (invoice.status === "Paid") {
      trigger.setAttribute("disabled", "")
    }
    trigger.innerHTML = `<button aria-label="Remind ${invoice.customer}">Remind</button>`
    row.append(trigger)
    list.append(row)
  }
  dialog.addEventListener("payloadchange", (event) => {
    const invoice = event.detail.value
    root.querySelector("ui-dialog-title")!.textContent =
      `Remind ${invoice?.customer}`
    root.querySelector("ui-dialog-description")!.textContent =
      `${invoice?.id} for ${invoice?.amount} is due. We'll email the billing contact.`
  })
  dialog.addEventListener("openchange", (event) => {
    if (!event.detail.value && event.detail.returnValue === "send") {
      log(root, "Reminder sent")
    }
  })
  root
    .querySelector("[data-slot=controls] button")!
    .addEventListener("click", async () => {
      const { reason, returnValue } = await dialog.api.open({
        payload: invoices[2],
      })
      log(
        root,
        returnValue === "send"
          ? "Reminder sent from code"
          : `Closed (${reason})`
      )
    })
}

export { mount }
```

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

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

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

```ts title="presentation.ts"
import "@ui-sdk/web/dialog"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-dialog presentation="sheet">
      <ui-dialog-trigger>
        <button>Edit Profile</button>
      </ui-dialog-trigger>
      <ui-dialog-content hidden>
        <div data-slot="stack">
          <ui-dialog-title>Edit profile</ui-dialog-title>
          <ui-dialog-description>Make changes to your profile here. Save when you're done.</ui-dialog-description>
        </div>
        <ui-field>
          <ui-field-label>Name</ui-field-label>
          <ui-input>
            <input value="Hollis Grant" />
          </ui-input>
        </ui-field>
        <ui-field>
          <ui-field-label>Username</ui-field-label>
          <ui-input>
            <input value="@hollis" />
          </ui-input>
        </ui-field>
        <div data-slot="row">
          <ui-dialog-close>
            <button>Cancel</button>
          </ui-dialog-close>
          <ui-dialog-close value="save">
            <button data-variant="solid">Save Changes</button>
          </ui-dialog-close>
        </div>
      </ui-dialog-content>
    </ui-dialog>
  `
}

export { mount }
```

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

## 自定义渲染
元素没有 render 函数。给标题加上 `as-child` 来绑定你自己的标题元素，或者在 Close 部件里放一个链接来从它关闭。监听对话框的 `openchange` 事件和内容的数据属性（比如 `data-nested`）来改变里面的内容：这里触发器的标签和描述就跟随它们变化。

```ts title="custom-rendering.ts"
import "@ui-sdk/web/dialog"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-dialog>
      <ui-dialog-trigger shortcut="mod+i">
        <button><span>View Details</span><ui-dialog-shortcut></ui-dialog-shortcut></button>
      </ui-dialog-trigger>
      <ui-dialog-backdrop hidden></ui-dialog-backdrop>
      <ui-dialog-content hidden>
        <div data-slot="stack">
          <ui-dialog-title as-child><h3>Details</h3></ui-dialog-title>
          <ui-dialog-description>Quarterly report, updated today.</ui-dialog-description>
        </div>
        <div data-slot="row">
          <ui-dialog-close>
            <button>Close</button>
          </ui-dialog-close>
          <ui-dialog-close>
            <a data-variant="solid" href="https://example.com/details">Open the Full Page</a>
          </ui-dialog-close>
        </div>
      </ui-dialog-content>
    </ui-dialog>
  `
  const label = root.querySelector("ui-dialog-trigger span")!
  const content = root.querySelector("ui-dialog-content")!
  const description = root.querySelector("ui-dialog-description")!
  root.querySelector("ui-dialog")!.addEventListener("openchange", (event) => {
    label.textContent = event.detail.value ? "Viewing" : "View Details"
    description.textContent = content.hasAttribute("data-nested")
      ? "Opened from another dialog."
      : "Quarterly report, updated today."
  })
}

export { mount }
```

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

## 样式
每个元素都有一个 `data-slot`，比如 `dialog-content`，并通过[数据属性](https://ui-sdk.cn/docs/web-components/components/dialog#data-attributes)下列出的属性展示状态。用 `data-open` 和 `data-closed` 表示每种状态，用 `data-starting-style` 和 `data-ending-style` 表示过渡。

### `<ui-dialog-content>`
- `--dialog-stack`: How many dialogs are open above this one, nested inside it. 0 for the topmost.
- `--keyboard-inset`: Unless it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one.
- `--visual-viewport-width`: Unless it presents as a sheet: the width of the part of the page you can see.
- `--visual-viewport-height`: Unless it presents as a sheet: the height of the part of the page you can see, above the keyboard.
- `--visual-viewport-top`: Unless it presents as a sheet: how far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up.
- `--drawer-progress`: While it presents as a sheet: how far open the sheet is, from 0 closed to 1 at its largest snap point. Never past 1.
- `--drawer-dim`: While it presents as a sheet: how dim the page behind is, from 0 to 1. The backdrop's opacity follows it.
- `--drawer-expand`: While it presents as a sheet: 0 at the second-largest snap point and below, 1 at the largest. With one snap point, the whole travel.
- `--drawer-stack`: While it presents as a sheet: how many sheets opened from inside this one are open above it, rising smoothly as each one opens. Push it back with it.
- `--sheet-backdrop`: Set it yourself: the color the page dims to while it presents as a sheet. Black at 0.2 by default.

### `<ui-dialog-viewport>`
- `--keyboard-inset`: While it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one.
- `--visual-viewport-width`: While it presents as a sheet: the width of the part of the page you can see.
- `--visual-viewport-height`: While it presents as a sheet: the height of the part of the page you can see, above the keyboard.
- `--visual-viewport-top`: While it presents as a sheet: how far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up.

## 数据属性
### `<ui-dialog-trigger>`
`[data-slot="dialog-trigger"]`

- `data-closed`: Present while the dialog is closed, including while it animates out.
- `data-disabled`: Present when the trigger is disabled.
- `data-open`: Present while the dialog is open. On a trigger, while it's open from that trigger.

### `<ui-dialog-backdrop>`
`[data-slot="dialog-backdrop"]`

- `data-closed`: Present while the dialog is closed, including while it animates out.
- `data-open`: Present while the dialog is open. On a trigger, while it's open from that trigger.
- `data-starting-style`: Present for the first frame. Style the state you animate from.
- `data-ending-style`: Present while the dialog animates out. Style the state you animate to.

### `<ui-dialog-content>`
`[data-slot="dialog-content"]`

- `data-closed`: Present while the dialog is closed, including while it animates out.
- `data-presentation` (`dialog`, `sheet`): How the dialog presents this time it's open.
- `data-open`: Present while the dialog is open. On a trigger, while it's open from that trigger.
- `data-starting-style`: Present for the first frame. Style the state you animate from.
- `data-ending-style`: Present while the dialog animates out. Style the state you animate to.
- `data-keyboard`: Present while the on-screen keyboard covers part of the page.

### `<ui-dialog-close>`
`[data-slot="dialog-close"]`

- `data-disabled`
- `data-pending`: Present on a Close part while its action runs.

## API 参考
属性（props）用 kebab 命名，比如 `close-on-outside-press`：`"false"` 表示 false。`container` 接受一个 CSS 选择器，`persistent-elements` 接受一个用逗号分隔的选择器列表。回调是 DOM 事件。

### 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.
- `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 `false` while a form has unsaved changes, and ask in `dismissattempt`.
- `dismissattempt event`: 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.
- `openchange event`: Runs when the dialog wants to open or close. `details.reason` says why, `details.cancel()` stops it, and `details.returnValue` carries what closed it.
- `payloadchange event`: 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 `openchange`, 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
对话框之外的触发器用 `for="dialog-id"` 指定对话框，并接受 `payload` property，或者用 `payload` 属性传字符串。property 优先。

- `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
让模态对话框后面的页面变暗。`<ui-dialog-backdrop>` 没有自己的属性。

### 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
为对话框命名。`<ui-dialog-title>` 渲染一个二级标题。

### DialogDescription
在渲染期间描述对话框。`<ui-dialog-description>` 是一个段落。

### DialogClose
使用 `action` 属性时，它的 `action` 事件的 `detail.source` 说明部件是如何被按压的，[Button](https://ui-sdk.cn/docs/web-components/components/button#changes-after-an-await) 对此有说明。

- `value?` (`string`): Reported as `returnValue` in `openchange` 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`.

### 状态
同样的状态会以数据属性的形式显示在每个元素上。

`DialogTrigger`:

- `open` (`boolean`): Whether the dialog is open from this trigger.
- `disabled` (`boolean`): Set by the trigger's `disabled` prop, which stops it opening the dialog.

`DialogBackdrop`:

- `open` (`boolean`): Whether the dialog is open. False while it animates out.
- `nested` (`boolean`): Whether the dialog was opened from inside another dialog.
- `nestedOpen` (`boolean`): Whether a dialog opened from inside this one is open.

`DialogContent`:

- `open` (`boolean`): Whether the dialog is open. False while it animates out.
- `modal` (`boolean | "trap-focus"`): The `modal` setting. Always true for an alert dialog.
- `nested` (`boolean`): Whether the dialog was opened from inside another dialog.
- `nestedOpen` (`boolean`): Whether a dialog opened from inside this one is open.
- `stack` (`number`): How many dialogs are open above this one, nested inside it.
- `payload` (`Payload | undefined`): The payload of the last open, from the trigger that opened it or a controller, typed as the controller's `Payload`.
- `pending` (`boolean`): Whether a Close part's action is running.
- `presentation` (`"dialog" | "sheet"`): How it presents this time it's open.

`DialogClose`:

- `pending` (`boolean`): Whether this part's action is running.
- `error` (`unknown`): Why this part's last action failed, until it's pressed again or the dialog opens again.

`DialogShortcut`:

- `text` (`string`): The shortcut formatted for this platform: `⌘K` on Apple platforms and `Ctrl+K` elsewhere. Empty without one.

### 原因
`event.detail.reason` 说明对话框为什么打开或关闭。

- `trigger-press` (`MouseEvent | 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-press` (`MouseEvent | KeyboardEvent | SubmitEvent`): A Close part was pressed, or a form with `method="dialog"` was submitted.
- `outside-press` (`MouseEvent`): A press outside the layer.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `parent-close` (`none`): The parent layer closed.
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `action` (`MouseEvent | KeyboardEvent`): A Close part's `action` finished.
- `shortcut` (`KeyboardEvent`): A keyboard shortcut, like a trigger's `shortcut`.
- `swipe` (`PointerEvent | TouchEvent`): A swipe gesture: a finger, mouse or pen dragged it.
- `imperative` (`none`): A controller or `api` call.

对于 payload 变更，它说明是什么打开了对话框或接管了它。

- `trigger-press` (`MouseEvent | 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`.
- `shortcut` (`KeyboardEvent`): A keyboard shortcut, like a trigger's `shortcut`.
- `imperative` (`none`): A controller or `api` call.

`dismissible` 可以拒绝的关闭操作：

- `outside-press` (`MouseEvent`): A press outside the layer.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `swipe` (`PointerEvent | TouchEvent`): A swipe gesture: a finger, mouse or pen dragged it.

### 控制器
从 `@ui-sdk/web/dialog` 用 `createDialogController<Payload, Result>()` 创建一个控制器，赋给根元素的 `controller` property。根元素的 `api` property 有同样的方法，它的 `open` property 读取和设置对话框是否打开。

每个写方法都接受可选的 `{ reason, event }`，并传给 `openchange`。用控制器关闭总是有效，即使对话框不可关闭，或者有动作正在运行。

- `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.

### 事件
事件在自己的元素上触发，不冒泡。在 `openchange` 上调用 `preventDefault()` 会取消这次变更。

| 成员                      | 所属                | 说明                                                                         |
| ------------------------- | ------------------- | ---------------------------------------------------------------------------- |
| `open` property、属性     | `ui-dialog`         | 对话框是否打开。属性设置它的起始值，并保持实时                               |
| `api` property            | `ui-dialog`         | [控制器](https://ui-sdk.cn/docs/web-components/components/dialog#controller)                                                        |
| `controller` property     | `ui-dialog`         | 一个由 `createDialogController()` 创建的控制器，用来从代码驱动它             |
| `openchange` 事件         | `ui-dialog`         | `detail: { value: open, reason, event, returnValue }`                        |
| `openchangecomplete` 事件 | `ui-dialog`         | `detail: { value: open }`，在动画之后                                        |
| `payloadchange` 事件      | `ui-dialog`         | `detail: { value: payload, reason, event, source }`，当内容的 payload 变化时 |
| `dismissattempt` 事件     | `ui-dialog`         | `detail: { reason, event }`，当一次关闭被拒绝时                              |
| `payload` property        | `ui-dialog-trigger` | 给内容的数据，在触发器连接时读取                                             |
| `for` 属性                | `ui-dialog-trigger` | 触发器从对话框之外打开的那个对话框的 `id`                                    |

## 无障碍
触发器是一个打开对话框的按钮，对话框遵循 [WAI-ARIA 模态对话框模式](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/)：模态时带有 `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.

Runs in 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 only.
- 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 only.

Runs in 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 only.

**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.

Runs in React、Vue 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器记录：

- Announcements while using the dialog with a keyboard.
- Announcements while using the alert dialog with a keyboard.

Runs in React、Vue 和 web components.
