# 对话框

## 使用方法

`Dialog`（模态对话框）会在当前页面之上浮起一个独立的小窗口，并把背景内容锁住，用来让用户集中精力完成某个具体任务，比如填写表单、配置选项或编辑资料。

它基于浏览器原生的 `<dialog>` 元素构建，打开时会自动锁定网页背景、把光标焦点限制在窗口内部，关闭后还会贴心地把焦点还给刚才点开它的那个按钮。搭配 `DialogHeader` 一起使用，可以自带标题、副标题以及右上角的关闭叉号：

```vue
<script setup lang="ts">
import { Button } from '@astryx-vue/core/Button'
import { Dialog, DialogHeader } from '@astryx-vue/core/Dialog'
import { ref } from 'vue'

const isOpen = ref(false)
</script>

<template>
  <Button label="分享项目" variant="secondary" @click="isOpen = true" />
  <Dialog :is-open="isOpen" @open-change="isOpen = $event">
    <DialogHeader title="分享项目" has-close-button @open-change="isOpen = $event" />
    <p>复制链接并发送给团队成员。</p>
  </Dialog>
</template>
```

**什么时候用：**
- 需要打断用户当前操作，让他们专注完成一步独立任务（如输入资料、配置参数）时。

**什么时候不要用：**
- 如果只是为了在删除、覆盖或撤销授权等不可逆操作前确认一下，请改用专门的 [AlertDialog](/components/alert-dialog)。
- 如果只是一句轻量的成功反馈（如“保存成功”），不要弹对话框打断用户，请改用轻提示 [useToast](/components/use-toast)。
- 如果流程很长很复杂、需要来回切换多个页面，请直接做成独立的新页面，不要在一个小弹窗里硬塞太多东西。
- 不要在一个对话框里再弹出一个新的对话框。如有分步需求，请在同一个弹窗内部切换步骤。

### 结构

- **页眉**: 标题、可选副标题和关闭按钮。打开时焦点落到标题上，标题通过 aria-labelledby 标出对话框。
- **正文**: 主要内容：文字、表单、列表或任意布局。
- **页脚**: 保存、取消或接受、拒绝这类操作按钮，靠尾部对齐。
- **遮罩**: 对话框后面的半透明层，挡住页面交互。

## 最佳实践

| 指引 | 实践 |
| --- | --- |
| 推荐 | 选择正确的用途：info 用于可关闭的内容，form 用于防止误点遮罩关闭，required 用于必须由用户作出响应的场景。 |
| 推荐 | 在头部添加清晰的标题，让用户立即了解对话框要他们做什么。 |
| 推荐 | 含有输入内容的对话框使用 purpose="form"。这样用户不会因误点遮罩而丢失数据。 |
| 推荐 | 对话框只处理单一任务。内容超出可容纳范围时，考虑改用整页。 |
| 避免 | 用对话框展示简单消息。这类消息可以内联显示，或使用 Toast 通知。 |
| 避免 | 在对话框中嵌套对话框。应把流程拆成单个对话框内的多个步骤。 |
| 避免 | 为简单确认使用 fullscreen 变体。它适用于编辑器或长表单等复杂内容。 |

## 示例

### 自适应呈现

默认仍是对话框。触屏且宽度不超过 lg 时，同一份资料表单改为底部弹层。

```vue
<script setup lang="ts">
import type { BottomSheetHeight, BottomSheetPurpose } from '@astryx-vue/core/BottomSheet'
import type { DialogPurpose } from '@astryx-vue/core/Dialog'
import { useMediaQuery } from '@astryx-vue/core'
import { BottomSheet } from '@astryx-vue/core/BottomSheet'
import { Button } from '@astryx-vue/core/Button'
import { Dialog, DialogHeader } from '@astryx-vue/core/Dialog'
import { Heading } from '@astryx-vue/core/Heading'
import { Layout, LayoutContent, LayoutFooter } from '@astryx-vue/core/Layout'
import { HStack, VStack } from '@astryx-vue/core/Stack'
import { Text } from '@astryx-vue/core/Text'
import { TextArea } from '@astryx-vue/core/TextArea'
import { TextInput } from '@astryx-vue/core/TextInput'
import { ref } from 'vue'

const TOUCH_ORIENTED_LG_QUERY = '(max-width: 1024px) and (pointer: coarse) and (hover: none)'

type AdaptivePresentation = 'dialog' | 'fullscreen' | 'bottom-sheet'

const isOpen = ref(false)
const name = ref('Ruby Cheung')
const email = ref('ruby@example.com')
const notes = ref('')
const isTouchOriented = useMediaQuery(TOUCH_ORIENTED_LG_QUERY)

const purpose: DialogPurpose = 'form'
const touchPresentation: AdaptivePresentation = 'bottom-sheet'
const bottomSheetHeight: BottomSheetHeight = 'tall'

function resolvedPresentation(): AdaptivePresentation {
  return isTouchOriented.value ? touchPresentation : 'dialog'
}
</script>

<template>
  <Button label="Edit profile" @click="isOpen = true" />
  <BottomSheet
    v-if="resolvedPresentation() === 'bottom-sheet'"
    v-model:is-open="isOpen"
    :height="bottomSheetHeight"
    label="Edit profile"
    :purpose="purpose as BottomSheetPurpose"
  >
    <VStack :gap="4">
      <Heading :level="3">
        Edit profile
      </Heading>
      <Text type="supporting" color="secondary">
        Dialog remains the default presentation. This example explicitly opts into a Bottom Sheet only at lg and below when the device has a coarse pointer and no hover. Pass the presentation prop to make tests or unusual environments deterministic.
      </Text>
      <Text type="supporting" color="secondary">
        In Bottom Sheet presentation, purpose="form" blocks scrim clicks and swipe dismissal while preserving Escape. Use this opt-in only when that contract is acceptable; keep AlertDialog/destructive confirmations on Dialog unless a product deliberately chooses otherwise.
      </Text>
      <TextInput v-model="name" label="Name" />
      <TextInput v-model="email" label="Email" type="email" />
      <TextArea v-model="notes" label="Notes" :rows="6" />
      <HStack :gap="2" h-align="end" wrap="wrap">
        <Button label="Cancel" variant="secondary" @click="isOpen = false" />
        <Button label="Save profile" variant="primary" @click="isOpen = false" />
      </HStack>
    </VStack>
  </BottomSheet>
  <Dialog
    v-else
    :is-open="isOpen"
    max-height="75dvh"
    :purpose="purpose"
    :variant="resolvedPresentation() === 'fullscreen' ? 'fullscreen' : 'standard'"
    :width="480"
    @open-change="isOpen = $event"
  >
    <Layout>
      <template #header>
        <DialogHeader title="Edit profile" @open-change="isOpen = $event" />
      </template>
      <LayoutContent>
        <VStack :gap="4">
          <Text type="supporting" color="secondary">
            Dialog remains the default presentation. This example explicitly opts into a Bottom Sheet only at lg and below when the device has a coarse pointer and no hover. Pass the presentation prop to make tests or unusual environments deterministic.
          </Text>
          <Text type="supporting" color="secondary">
            In Bottom Sheet presentation, purpose="form" blocks scrim clicks and swipe dismissal while preserving Escape. Use this opt-in only when that contract is acceptable; keep AlertDialog/destructive confirmations on Dialog unless a product deliberately chooses otherwise.
          </Text>
          <TextInput v-model="name" label="Name" />
          <TextInput v-model="email" label="Email" type="email" />
          <TextArea v-model="notes" label="Notes" :rows="6" />
        </VStack>
      </LayoutContent>
      <template #footer>
        <LayoutFooter>
          <HStack :gap="2" h-align="end" wrap="wrap">
            <Button label="Cancel" variant="secondary" @click="isOpen = false" />
            <Button label="Save profile" variant="primary" @click="isOpen = false" />
          </HStack>
        </LayoutFooter>
      </template>
    </Layout>
  </Dialog>
</template>
```

### 确认

破坏性操作前先确认。页面上的预览一直留着，点按钮才会打开真正的对话框。

```vue
<script setup lang="ts">
import { Dialog, useImperativeDialog } from '@astryx-vue/core/Dialog'
import { h } from 'vue'
import ConfirmBody from './confirm-body.vue'

const dialog = useImperativeDialog({ width: 400, purpose: 'form' })

function openDialog() {
  dialog.show(() => h(ConfirmBody, { requestClose: () => dialog.hide() }))
}
</script>

<template>
  <Dialog is-open is-inline :width="400" purpose="form">
    <ConfirmBody :request-close="openDialog" />
  </Dialog>
  <component :is="dialog.Host" />
</template>
```

### 表单

不离开当前页面就能改名字和简介。purpose 为 form 时保留 Escape，并忽略点击遮罩。

```vue
<script setup lang="ts">
import { Dialog, useImperativeDialog } from '@astryx-vue/core/Dialog'
import { h } from 'vue'
import FormBody from './form-body.vue'

const dialog = useImperativeDialog({ purpose: 'form', width: 480 })

function openDialog() {
  dialog.show(() => h(FormBody, { requestClose: () => dialog.hide() }))
}
</script>

<template>
  <Dialog is-open is-inline purpose="form" :width="480">
    <FormBody :request-close="openDialog" />
  </Dialog>
  <component :is="dialog.Host" />
</template>
```

### 全屏

variant 为 fullscreen 时占满视口，适合文档这类长内容。

```vue
<script setup lang="ts">
import { Button } from '@astryx-vue/core/Button'
import { Card } from '@astryx-vue/core/Card'
import { Dialog, DialogHeader } from '@astryx-vue/core/Dialog'
import { Layout, LayoutContent, LayoutFooter } from '@astryx-vue/core/Layout'
import { HStack, VStack } from '@astryx-vue/core/Stack'
import { Text } from '@astryx-vue/core/Text'
import { ref } from 'vue'

const isOpen = ref(false)

const sections = [
  { title: 'Getting started', body: 'Create your first project by clicking New Project in the sidebar. Choose a template or start from scratch.' },
  { title: 'Team members', body: 'Invite collaborators from Settings > Team. Each member can have Admin, Editor, or Viewer permissions.' },
  { title: 'Billing', body: 'Free plans include up to 3 projects. Upgrade to Pro for unlimited projects and priority support.' },
  { title: 'API access', body: 'Generate API keys from Settings > Developer. Rate limits are 1,000 requests per minute on free plans.' },
  { title: 'Data export', body: 'Export your data anytime from Settings > Data. Exports are available as CSV or JSON within 24 hours.' },
]
</script>

<template>
  <Card>
    <VStack :gap="3">
      <VStack :gap="1">
        <Text type="body" weight="bold">
          Help &amp; Documentation
        </Text>
        <Text type="supporting" color="secondary">
          5 articles · Last updated Apr 2026
        </Text>
      </VStack>
      <Button label="Open documentation" variant="secondary" @click="isOpen = true" />
    </VStack>
  </Card>
  <Dialog :is-open="isOpen" variant="fullscreen" @open-change="isOpen = $event">
    <Layout>
      <template #header>
        <DialogHeader
          title="Documentation"
          subtitle="Everything you need to get started"
          has-close-button
          @open-change="isOpen = $event"
        />
      </template>
      <LayoutContent>
        <VStack :gap="4">
          <VStack v-for="section in sections" :key="section.title" :gap="1">
            <Text type="body" weight="bold">
              {{ section.title }}
            </Text>
            <Text type="body">
              {{ section.body }}
            </Text>
          </VStack>
        </VStack>
      </LayoutContent>
      <template #footer>
        <LayoutFooter>
          <HStack h-align="end">
            <Button label="Close" variant="primary" @click="isOpen = false" />
          </HStack>
        </LayoutFooter>
      </template>
    </Layout>
  </Dialog>
</template>
```

### 可滚动

maxHeight 把对话框压短，条款在内部滚动。

```vue
<script setup lang="ts">
import { Dialog, useImperativeDialog } from '@astryx-vue/core/Dialog'
import { h } from 'vue'
import ScrollBody from './scroll-body.vue'

const dialog = useImperativeDialog({ maxHeight: '50dvh' })

function openDialog() {
  dialog.show(() => h(ScrollBody, { requestClose: () => dialog.hide() }))
}
</script>

<template>
  <Dialog is-open is-inline :max-height="360">
    <ScrollBody :request-close="openDialog" />
  </Dialog>
  <component :is="dialog.Host" />
</template>
```

### 必须响应

purpose 为 required 时，Escape 和遮罩都不能关掉。用户必须选择取消或转让。

```vue
<script setup lang="ts">
import { Dialog, useImperativeDialog } from '@astryx-vue/core/Dialog'
import { h } from 'vue'
import RequiredBody from './required-body.vue'

const dialog = useImperativeDialog({ purpose: 'required' })

function openDialog() {
  dialog.show(() => h(RequiredBody, { requestClose: () => dialog.hide() }))
}
</script>

<template>
  <Dialog is-open is-inline purpose="required">
    <RequiredBody :request-close="openDialog" />
  </Dialog>
  <component :is="dialog.Host" />
</template>
```

## 无障碍

`Dialog` 基于原生 `<dialog>` 元素构建，模态行为、焦点限制和关闭后的焦点归还都由浏览器提供，因此不需要额外配置就能获得正确的无障碍表现。

对话框通过 `showModal()` 打开，打开期间页面其余部分不可交互。打开后，初始焦点落在第一个带有 `data-autofocus` 的元素上；如果没有元素带这个属性，焦点落在 `DialogHeader` 的标题上。

对话框的名称默认取自 `DialogHeader` 的标题，组件会把标题与对话框通过 `aria-labelledby` 关联起来。如果显式设置了 `aria-label` 或 `aria-labelledby`，则以你提供的名称为准。

Escape 与点击遮罩不会直接关闭对话框，它们只发出 `openChange(false)`，由父组件决定是否关闭。关闭后，如果打开对话框之前的那个元素仍在页面中，焦点会回到它身上。

## 限制

下面两点决定了你能在对话框里放什么内容，在组合 Tooltip、Popover 或多步流程之前需要先了解。

- Tooltip 与 Popover 会渲染到 `body`。在打开的 `Dialog` 内使用时，它们位于模态顶层之下，因此既看不到也无法操作；在它们获得对话框自身的层级之前，请不要把它们嵌套进对话框。
- 对话框不可嵌套。需要多步流程时，请把流程拆分为同一个对话框内的步骤。

## 布局

标准变体通过 `width` 与 `maxHeight` 定尺寸，在窄屏上以间距令牌为边距夹取到视口内。`position` 设置静态偏移；逻辑属性 `start` 与 `end` 在 RTL 下自动镜像。

## 属性

| 属性 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `isOpen` | `boolean` | — | 对话框是否打开。该属性必填。 |
| `isInline` | `boolean` | `false` | 以普通文档流渲染内容，不使用 `<dialog>`、遮罩与模态行为，仅用于文档预览。 |
| `width` | `number \| string` | `400` | 首选宽度，数字单位为像素，字符串原样使用。窄屏时夹取到视口内，全屏变体忽略此项。 |
| `maxHeight` | `number \| string` | `'75vh'` | 最大高度，数字单位为像素，字符串原样使用。全屏变体忽略此项。 |
| `position` | `DialogPosition` | 居中 | 对话框的静态偏移，支持 `top`、`bottom`、`start`、`end`，未设置时居中。逻辑属性 `start` 与 `end` 在 RTL 下自动镜像，全屏变体忽略此项。 |
| `variant` | `'standard' \| 'fullscreen'` | `'standard'` | 对话框变体：standard 为标准对话框，fullscreen 占满整个视口。 |
| `purpose` | `'required' \| 'form' \| 'info'` | `'info'` | 允许的关闭方式：`required` 禁用 Escape 与点击遮罩，必须由用户响应；`form` 仅允许 Escape；`info` 两者都允许。 |
| `padding` | `0 \| 0.5 \| 1 \| 1.5 \| 2 \| 3 \| 4 \| 5 \| 6 \| 8 \| 10` | 主题默认值（16px） | 对话框内边距，取值对应 `--astryx-spacing-*` 令牌。 |

## 事件

- `openChange(isOpen: boolean)`：用户通过 Escape 或点击遮罩请求关闭时以 `false` 触发，是否触发取决于 `purpose`。父组件通过设置 `isOpen` 来关闭。

## 插槽

- `default`：对话框内容。通常为 `DialogHeader`，之后是正文与操作区。

## DialogHeader 属性

| 属性 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `title` | `string` | — | 对话框标题。打开时获得默认焦点，并为对话框命名。必填。 |
| `subtitle` | `string` | — | 标题下方的次要文字。为空且没有 `subtitle` 插槽时不渲染。 |
| `hasCloseButton` | `boolean` | `false` | 显示关闭按钮，点击时发出 `openChange(false)`。 |
| `endContentEdgeCompensation` | `'inline' \| 'block' \| 'all'` | 有关闭按钮时为 `all` | 后置槽补偿哪几条边。不传时，有关闭按钮就补上下和行末。 |
| `closeButtonLabel` | `string` | 跟界面语言 | 关闭按钮的无障碍名称。不传时英文 Close、中文「关闭」。 |
| `hasDivider` | `boolean` | `false` | 底部画一条主题分隔线，颜色取 `--astryx-color-border`。 |

## DialogHeader 事件与插槽

- `openChange(isOpen: boolean)`：点击关闭按钮时以 `false` 触发。
- `title`：替换标题文字的行内内容。
- `subtitle`：副标题的行内内容。
- `startContent`：标题之前的内容，例如返回按钮。
- `endContent`：标题之后、关闭按钮之前的内容。

## useImperativeDialog

- `show(content, options?)`：以给定内容打开对话框。选项与传给 Hook 的默认选项合并。
- `hide()`：关闭对话框。
- `isOpen`：只读的打开状态。
- `Host`：在模板中渲染一次的组件。

## 主题

```css
.my-dialog {
  --astryx-dialog-background: #fff;
  --astryx-dialog-foreground: #000;
}
```

- `--astryx-dialog-background`：表面颜色。
- `--astryx-dialog-foreground`：文字颜色。
- `--astryx-dialog-overlay`：遮罩颜色。
- `--astryx-dialog-shadow`：表面阴影。
- `--astryx-dialog-padding`：未设置 `padding` 属性时的默认内边距。
- `--astryx-dialog-title-color`：标题颜色。
