﻿# 对话框 {#confirm}

定制确认对话框，支持异步加载、取消／确认回调、Promise 和 Chalk／OEM 主题。

默认导出为组件插件，具名 `Confirm` 为可调用服务。安装总包或 `app.use(NfConfirm)` 后可使用 `this.$openConfirm`。setup 中推荐 `useConfirm()` 继承 provider 注入和语言，并在组件卸载时清理弹窗；`createConfirm(appContext)` 创建应用专属服务。直接 Confirm 不隐式绑定最后安装的应用，可用第二参数传入 appContext。

## 基础用法 {#basic}

### 基础用法
```vue
<script setup>
import { useConfirm } from '@94ai-plus/common-ui'
const confirm = useConfirm()
function open() {
  confirm({ title: 'Confirm', message: 'Confirm content', onConfirm: done => done() }).catch(() => {})
}
</script>

<template>
  <nf-button @click="open">Open confirm</nf-button>
</template>
```

## 不同状态 {#variants}

### 不同状态
```vue
<script setup>
import { useConfirm } from '@94ai-plus/common-ui'
const confirm = useConfirm()
const types = ['success', 'warning', 'info', 'error']
function open(type) {
  confirm({ title: type, message: 'Confirm content', type, onConfirm: done => done() }).catch(() => {})
}
</script>

<template>
  <nf-button v-for="type in types" :key="type" @click="open(type)">{{ type }}</nf-button>
</template>
```

## Promise 与异步关闭 {#promise}

### Promise 与异步关闭
```vue
<script setup>
import { ref, onBeforeUnmount } from 'vue'
import { useConfirm } from '@94ai-plus/common-ui'
const confirm = useConfirm()
const result = ref('')
let timer
function open() {
  confirm({ title: 'Async confirm', message: 'Confirm, then wait one second' })
    .then(done => { result.value = 'confirmed'; timer = setTimeout(() => { done(); result.value = 'closed' }, 1000) })
    .catch(() => { result.value = 'cancelled' })
}
onBeforeUnmount(() => clearTimeout(timer))
</script>

<template>
  <nf-button @click="open">Promise</nf-button>
  <output>{{ result }}</output>
</template>
```

## 回调与重试 {#callbacks}

### 回调与重试
```vue
<script setup>
import { ref } from 'vue'
import { useConfirm } from '@94ai-plus/common-ui'
const confirm = useConfirm()
const result = ref('')
function open() {
  let attempt = 0
  confirm({
    title: 'Retry', message: 'First confirm: done(false). Second confirm: done().',
    onConfirm: done => { attempt++; result.value = 'attempt: ' + attempt; done(attempt > 1) },
    onCancel: done => done(),
  }).then(() => { result.value += ' / confirmed' }).catch(() => { result.value = 'cancelled' })
}
</script>

<template>
  <nf-button @click="open">Retry</nf-button>
  <output>{{ result }}</output>
</template>
```

## 文本、HTML、VNode 与组件 {#content}

### 文本、HTML、VNode 与组件
```vue
<script setup>
import { h, ref } from 'vue'
import { useConfirm } from '@94ai-plus/common-ui'
const confirm = useConfirm()
const visible = ref(false)
function open(message, html = false) {
  confirm({ title: 'Content', message, dangerouslyUseHTMLString: html, onConfirm: done => done() }).catch(() => {})
}
</script>

<template>
  <nf-button @click="open('<b>Escaped text</b>')">Text</nf-button>
  <nf-button @click="open('<b>Trusted HTML</b>', true)">HTML</nf-button>
  <nf-button @click="open(h('strong', 'VNode content'))">VNode</nf-button>
  <nf-button @click="visible = true">Slot</nf-button>
  <nf-confirm v-model="visible" title="Slot"><strong>Default slot content</strong></nf-confirm>
</template>
```

## 交互体验 {#interactive}


See expanded example example-6 (ConfirmExamples).


## 按需引入 {#installation}

```ts
import NfConfirm, { Confirm, useConfirm, createConfirm } from '@94ai-plus/nf-confirm'
import 'element-plus/dist/index.css'
import '@94ai-plus/nf-theme-chalk/nf-confirm.css'

app.use(NfConfirm)
Confirm({ title: 'Confirm', message: 'Continue?' }).then(done => done()).catch(() => {})
// setup(): const confirm = useConfirm()
const confirm = createConfirm(app._context)
```

## 属性 {#props}

| 参数 | 说明 | 类型 | 可选值 | 默认值 |
| --- | --- | --- | --- | --- |
| title | 标题 | string | — | `''` |
| message | 说明文字 | string / VNode | — | `''` |
| dangerouslyUseHTMLString | 是否将 message 属性作为 HTML 片段处理，仅用于可信内容 | boolean | — | false |
| width | Confirm 的宽度，单位 px | number | — | 400 |
| type | 主题样式，如果不在可选值内将被忽略 | string | success / warning / info / error | `''` |
| iconClass | 自定义图标的类名。若设置了有效的 type，则 iconClass 会被覆盖 | string | — | `''` |
| customClass | 自定义类名 | string | — | `''` |
| cancelButtonText | 取消按钮的文本内容 | string | — | 跟随当前语言包 |
| confirmButtonText | 确定按钮的文本内容 | string | — | 跟随当前语言包 |
| onCancel | 点击取消按钮时的回调函数，done() 关闭 Confirm，done(false) 仅结束加载 | `(done: ConfirmDone) => void \| Promise<void>` | — | — |
| onConfirm | 点击确定按钮时的回调函数，done() 关闭 Confirm，done(false) 仅结束加载 | `(done: ConfirmDone) => void \| Promise<void>` | — | — |
| modelValue | 是否显示，支持 v-model；与 visible 同时设置时以 modelValue 为准 | boolean | — | false |
| visible | 是否显示，支持 v-model:visible | boolean | — | false |

## 事件 {#events}

| 事件名称 | 说明 | 回调参数 |
| --- | --- | --- |
| cancel | 点击取消按钮时的回调函数，done() 关闭 Confirm，done(false) 仅结束加载 | done: ConfirmDone |
| confirm | 点击确定按钮时的回调函数，done() 关闭 Confirm，done(false) 仅结束加载 | done: ConfirmDone |
| update:modelValue | 显示状态变化时触发 | value: boolean |
| update:visible | 显示状态变化时触发 | value: boolean |
| close | 关闭时触发 | — |
| destroy | 离场动画结束后触发 | — |

## 插槽 {#slots}

| Slot | 说明 | 回调参数 |
| --- | --- | --- |
| default | 正文内容，优先于 message | — |

## 方法与实例 {#methods}

| API | Description |
| --- | --- |
| Confirm(options?, appContext?) | `Promise<ConfirmDone>` |
| done() / done(true) | Clear loading and close |
| done(false) | Clear loading, keep dialog open |
| Confirm.closeAll() | Cancel all Confirm instances on the page |
| createConfirm(appContext) / useConfirm() | Scoped service; closeAll only cancels owned instances |
| component ref.close(close?) | Close or clear loading |

## 迁移说明 {#migration}

保留默认 400px、顶部 35vh、四种状态、默认双按钮和异步 loading；不显示右上角关闭按钮，点击遮罩不关闭。Escape 按取消处理，执行 onCancel，并在实际关闭后 reject(undefined)，修复旧版 Escape 关闭后 Promise 悬空的问题。默认按钮文案跟随八语言，显式文案不被覆盖。有效 type 图标优先于 iconClass；未指定 type 时支持自定义图标。普通标题／字符串转义，HTML 模式仅用于可信内容；VNode 正文修复为真实渲染。

无自定义 onConfirm 时，确认会 resolve(done)，不自动关闭；业务需调用 done()。done(false) 只结束 loading，已 resolve 的 Promise 不会重新执行 then，需重试时使用 onConfirm 回调。自定义回调控制关闭：done(false) 保持待定，done() 后按当前确认／取消操作结算 Promise；这修复了旧版带自定义回调时 Promise 永不结算的问题。同步异常／异步拒绝清除 loading 并 reject(error)，不自动关闭。内部仅观察未处理的拒绝，显式 catch 仍可收到取消或错误。

修复全局 currentMsg 导致的多实例 Promise 串线。每次操作有独立标识，取消后、重试后或重新打开后，旧 done 不会影响新状态；重复确认被 loading 阻止。支持声明式 v-model／v-model:visible、默认插槽、类型化 close()；无操作监听器时声明式组件默认关闭。默认插槽是新增能力，旧版没有可用插槽。

基于 Element Plus Dialog 保留焦点管理、滚动锁定和层级。应用／provider 服务仅清理所属弹窗，直接 Confirm.closeAll() 处理页面所有 Confirm，不影响 Message／Notification。关闭和卸载释放 Vue 树及监听器；SSR 返回 resolve(空操作 done) 的 Promise，不访问 DOM。弹窗挂到 body，组件主题跟随根 data-nf-theme。旧文档重复的 /3 锚点映射到基础用法；误写到 notification 的 Options 锚点不会覆盖通知文档路由。

## Expanded component examples

### ConfirmExamples

Source: docs/.vitepress/theme/components/ConfirmExamples.vue

```vue
<script setup lang="ts">
import { h, ref } from 'vue'
import { useConfirm, type ConfirmDone, type ConfirmType } from '@94ai-plus/common-ui'
import { useDocsLanguage } from '../locale'

const { english } = useDocsLanguage()
const confirm = useConfirm()
const type = ref<ConfirmType>('info')
const width = ref(400)
const customLabels = ref(false)
const retry = ref(false)
const result = ref('')
let pending: ConfirmDone | undefined
function open() {
  let attempts = 0
  pending = undefined
  result.value = ''
  confirm({
    title: english.value ? 'Confirmation' : '对话框',
    message: h('div', [h('p', 'Confirm content'), h('button', { type: 'button', class: 'nf-button', 'data-testid': 'confirm-done', onClick: () => pending?.() }, 'done()')]),
    type: type.value, width: width.value,
    customClass: 'confirm-demo', cancelButtonText: customLabels.value ? 'Back' : undefined,
    confirmButtonText: customLabels.value ? 'Continue' : undefined,
    onConfirm: retry.value ? done => { attempts++; result.value = `attempt: ${attempts}`; if (attempts === 1) done(false); else done() } : undefined,
  }).then(done => { pending = done; result.value += ' confirmed' }).catch(error => { result.value = error instanceof Error ? error.message : 'cancelled' })
}
</script>

<template>
  <section class="confirm-examples">
    <div class="confirm-controls">
      <label>type <select v-model="type" data-testid="confirm-type"><option value="">—</option><option>info</option><option>success</option><option>warning</option><option>error</option></select></label>
      <label>width <input v-model.number="width" type="number" min="180" data-testid="confirm-width"></label>
      <label><input v-model="customLabels" type="checkbox" data-testid="confirm-labels">{{ english ? 'Custom labels' : '自定义文案' }}</label>
      <label><input v-model="retry" type="checkbox" data-testid="confirm-retry">done(false) → done()</label>
    </div>
    <div class="confirm-actions">
      <button type="button" data-testid="confirm-open" @click="open">{{ english ? 'Open confirm' : '打开对话框' }}</button>
      <button type="button" data-testid="confirm-close-all" @click="confirm.closeAll()">closeAll()</button>
    </div>
    <p>{{ english ? 'Without retry, confirm resolves the Promise and waits for done(). Press Escape to cancel.' : '未选重试时，确认后 Promise 已完成，但需调用 done() 关闭。Escape 可取消。' }}</p>
    <output data-testid="confirm-result">{{ result }}</output>
  </section>
</template>

<style scoped>
.confirm-controls, .confirm-actions { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; }
.confirm-controls label { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; }
.confirm-controls input[type='number'] { width: 80px; }
.confirm-controls input, .confirm-controls select, .confirm-actions button { border: 1px solid var(--site-border); border-radius: 4px; padding: 4px 8px; background: var(--site-background); color: var(--site-text); }
.confirm-actions button { cursor: pointer; }
.confirm-examples p, .confirm-examples output { font-size: 12px; overflow-wrap: anywhere; }
</style>
```

Source: docs/.vitepress/theme/locale.ts

```ts
import { computed, inject, type InjectionKey, type Ref } from 'vue'
import { withBase } from 'vitepress'
import { localizePath, type LocaleName } from '../../../packages/common-locale/src/languages'
import { additionalMessages } from '../locales/ui'
export { languageDefinitions, localeFromPath, isLocaleName } from '../../../packages/common-locale/src/languages'

export type DocsLanguage = LocaleName
export const languageStorageKey = 'common-ui-plus:docs-language'
export const docsLanguageKey: InjectionKey<Ref<DocsLanguage>> = Symbol('docs-language')

const zh = {
  brand: '94智能通用组件库', home: '94智能公共组件库首页', skip: '跳至正文',
  toggleSidebar: '切换侧边导航', closeNav: '关闭导航', navigation: '顶部导航', sidebar: '文档导航', outline: '当前页面目录',
  guide: '指南', packages: '分包集合', theme: '主题', language: '语言', links: '边缘库',
  chalk: 'Chalk 默认主题', oem: 'OEM 定制主题', playground: '演练场',
  dark: '切换为暗色模式', light: '切换为亮色模式',
  search: '搜索文档', searchPlaceholder: '搜索文档，索引至标题，定位至组件', noResults: '没有匹配结果',
  example: '示例', loadingDemo: '正在加载示例…', preview: '实时预览', actions: '示例操作',
  edit: '在线编辑', editTitle: '在演练场中编辑', copy: '复制代码', copied: '代码已复制',
  expand: '展开代码', collapse: '收起代码', switchJs: '切换为 JS', switchTs: '切换为 TS',
  editor: '示例代码编辑器', switchFailed: '语言切换失败，代码未更改：',
  manualCopy: '请展开代码后手动复制。', copyFailed: '无法访问剪贴板，请在展开的编辑器中手动复制。',
}
const en: typeof zh = {
  brand: '94AI Common UI', home: '94AI Common UI home', skip: 'Skip to content',
  toggleSidebar: 'Toggle sidebar', closeNav: 'Close navigation', navigation: 'Top navigation', sidebar: 'Documentation navigation', outline: 'On this page',
  guide: 'Guide', packages: 'Packages', theme: 'Theme', language: 'Language', links: 'Links',
  chalk: 'Chalk default theme', oem: 'OEM custom theme', playground: 'Playground',
  dark: 'Switch to dark mode', light: 'Switch to light mode',
  search: 'Search docs', searchPlaceholder: 'Search docs, headings and components', noResults: 'No matching results',
  example: 'Example', loadingDemo: 'Loading example…', preview: ' live preview', actions: 'Example actions',
  edit: 'Edit online', editTitle: 'Edit in playground', copy: 'Copy code', copied: 'Code copied',
  expand: 'Expand code', collapse: 'Collapse code', switchJs: 'Switch to JS', switchTs: 'Switch to TS',
  editor: 'Example code editor', switchFailed: 'Language switch failed; code unchanged: ',
  manualCopy: 'Expand the code and copy it manually.', copyFailed: 'Clipboard unavailable. Copy the code manually from the editor.',
}
export const docsMessages: Record<DocsLanguage, typeof zh> = { 'zh-CN': zh, 'en-US': en, ...additionalMessages }

export function localizedPath(path: string, locale: DocsLanguage): string {
  return localizePath(path, locale)
}

export function useDocsLanguage() {
  const locale = inject(docsLanguageKey)!
  const english = computed(() => locale.value !== 'zh-CN')
  const ui = computed(() => docsMessages[locale.value])
  const docLink = (path: string) => withBase(localizedPath(path, locale.value))
  return { locale, english, ui, docLink }
}
```
