﻿# Confirm {#confirm}

Custom confirmation dialogs with async loading, callbacks, promises and Chalk/OEM themes.

The default export is a component plugin; the named `Confirm` export is the callable service. CommonUI or `app.use(NfConfirm)` installs `this.$openConfirm`. In setup, `useConfirm()` inherits provider injections and locale and cleans up on unmount. `createConfirm(appContext)` creates an app-scoped service. Direct Confirm does not implicitly bind the last installed app; pass appContext as its second argument when needed.

## Basic usage {#basic}

### Basic usage
```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>
```

## Status types {#variants}

### Status types
```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>
```

## Promises and asynchronous close {#promise}

### Promises and asynchronous close
```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 and retry {#callbacks}

### Callbacks and retry
```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>
```

## Text, HTML, VNode and component {#content}

### Text, HTML, VNode and component
```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 example {#interactive}


See expanded example example-6 (ConfirmExamples).


## Installation {#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)
```

## Options {#props}

| Attribute | Description | Type | Accepted values | Default |
| --- | --- | --- | --- | --- |
| title | Title | string | — | `''` |
| message | Description text | string / VNode | — | `''` |
| dangerouslyUseHTMLString | Whether to render message as HTML; trusted content only | boolean | — | false |
| width | Confirm width in px | number | — | 400 |
| type | Theme style; unsupported values are ignored | string | success / warning / info / error | `''` |
| iconClass | Custom icon class; a valid type takes precedence | string | — | `''` |
| customClass | Custom class name | string | — | `''` |
| cancelButtonText | Cancel button text | string | — | Current locale |
| confirmButtonText | Confirm button text | string | — | Current locale |
| onCancel | Cancel callback; done() closes Confirm, done(false) only stops loading | `(done: ConfirmDone) => void \| Promise<void>` | — | — |
| onConfirm | Confirm callback; done() closes Confirm, done(false) only stops loading | `(done: ConfirmDone) => void \| Promise<void>` | — | — |
| modelValue | Visibility with v-model; takes precedence over visible | boolean | — | false |
| visible | Visibility with v-model:visible | boolean | — | false |

## Events {#events}

| Event | Description | Payload |
| --- | --- | --- |
| cancel | Cancel callback; done() closes Confirm, done(false) only stops loading | done: ConfirmDone |
| confirm | Confirm callback; done() closes Confirm, done(false) only stops loading | done: ConfirmDone |
| update:modelValue | Emitted when visibility changes | value: boolean |
| update:visible | Emitted when visibility changes | value: boolean |
| close | Emitted on close | — |
| destroy | Emitted after the leave transition | — |

## Slots {#slots}

| Slot | Description | Payload |
| --- | --- | --- |
| default | Body content; takes precedence over message | — |

## Methods and instance {#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 notes {#migration}

Preserves 400px width, 35vh top, four types, both buttons and async loading. No close icon; backdrop clicks do not close. Escape is treated as cancellation, invokes onCancel and rejects with undefined after closing, fixing the legacy unresolved Promise. Default labels follow eight languages; explicit labels win. Recognized type icons take priority over iconClass. Titles/strings are escaped; HTML mode is only for trusted content. VNode content now renders correctly.

Without a custom onConfirm, confirmation resolves with done and does not close automatically. Call done() to close. done(false) only clears loading; a resolved Promise does not run then again. Use onConfirm for retryable operations. With custom callbacks, done(false) keeps the Promise pending; done() settles according to the current action. This fixes promises that never settled with legacy callbacks. Synchronous errors/async rejections clear loading and reject(error), without auto-closing. An internal rejection observer prevents ignored callback-style returns from becoming unhandled; explicit catch still receives cancellations/errors.

Each dialog owns its Promise, fixing the global currentMsg cross-instance bug. Attempt-scoped done functions cannot affect later retries, cancellation or reopened dialogs. Loading blocks repeated confirmation. Adds declarative v-model/v-model:visible, default slot and typed close(); declarative components without action listeners close normally. The default slot is new; the legacy component had no usable slot.

Element Plus Dialog provides focus, scroll locking and layering. App/provider services only clean up owned dialogs; direct Confirm.closeAll() cancels all Confirm instances without touching Message/Notification. Closing/unmount releases the Vue tree; SSR returns a resolved no-op done Promise without DOM access. Dialogs mount into body and follow root data-nf-theme. The duplicate legacy /3 anchor maps to basic usage; its incorrectly named notification Options anchor does not override notification routes.

## 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 }
}
```
