﻿# 通知 {#notification}

四角通知，支持自动关闭、独立堆叠、操作按钮和 Chalk／OEM 主题。

默认导出是组件插件，具名 `Notification` 是可调用服务。安装总包或 `app.use(NfNotification)` 后可使用 `this.$openNotify`。setup 中推荐 `useNotification()`，继承当前 provider 的注入和语言，并在组件卸载时清理通知；也可用 `createNotification(appContext)` 创建应用专属服务。直接 Notification 不隐式绑定最后安装的应用，可用第二参数显式传入 appContext。

## 基础用法与四角定位 {#basic}

### 基础用法与四角定位
```vue
<script setup>
import { Notification } from '@94ai-plus/common-ui'
const positions = ['top-right', 'top-left', 'bottom-right', 'bottom-left']
</script>

<template>
  <nf-button v-for="position in positions" :key="position" @click="Notification({ title: position, message: 'Notification content', position, duration: 0 })">{{ position }}</nf-button>
  <nf-button @click="Notification.closeAll()">closeAll()</nf-button>
</template>
```

## 通知类型 {#variants}

### 通知类型
```vue
<script setup>
import { Notification } from '@94ai-plus/common-ui'
const types = ['success', 'warning', 'info', 'error']
</script>

<template>
  <nf-button v-for="type in types" :key="type" @click="Notification[type]({ title: type, message: 'Notification content' })">{{ type }}</nf-button>
</template>
```

## 取消与确认 {#actions}

### 取消与确认
```vue
<script setup>
import { ref } from 'vue'
import { Notification } from '@94ai-plus/common-ui'
const result = ref('')
let current
function open() {
  const handler = Notification({
    title: 'Review', message: 'Actions do not auto-close', duration: 0,
    cancelButtonText: 'Cancel', confirmButtonText: 'Confirm',
    onClick: () => { result.value = 'click' },
    onCancel: () => { result.value = 'cancel' },
    onConfirm: () => { result.value = 'confirm'; handler.close() },
    onClose: handler => { result.value += ' / closed: ' + handler.id },
  })
  current = handler
}
</script>

<template>
  <nf-button @click="open">Open</nf-button>
  <nf-button @click="current?.close()">close()</nf-button>
  <output>{{ result }}</output>
</template>
```

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

### 文本、HTML 与 VNode
```vue
<script setup>
import { h } from 'vue'
import { Notification } from '@94ai-plus/common-ui'
</script>

<template>
  <nf-button @click="Notification('<b>Escaped text</b>')">Text</nf-button>
  <nf-button @click="Notification({ title: 'Trusted HTML', message: '<b>Trusted HTML</b>', dangerouslyUseHTMLString: true })">HTML</nf-button>
  <nf-button @click="Notification(h('strong', 'VNode content'))">VNode</nf-button>
  <nf-button @click="Notification({ message: 'Custom icon', iconClass: 'notification-star' })">Custom icon</nf-button>
</template>

<style>
.notification-star::before { content: '★'; color: #ff882e; }
</style>
```

## 组件与默认插槽 {#slots}

### 组件与默认插槽
```vue
<script setup>
import { ref } from 'vue'
const open = ref(false)
</script>

<template>
  <nf-button @click="open = true">Slot notification</nf-button>
  <nf-notification v-if="open" title="Slot" :duration="0" position="top-left" @close="open = false"><strong>Slot-only content</strong></nf-notification>
</template>
```

## 交互体验 {#interactive}


See expanded example example-6 (NotificationExamples).


## 按需引入 {#installation}

```ts
import NfNotification, { Notification, useNotification, createNotification } from '@94ai-plus/nf-notification'
import '@94ai-plus/nf-theme-chalk/nf-notification.css'

app.use(NfNotification)
Notification.success({ title: 'Saved', message: 'Success' })
const notify = createNotification(app._context)
notify.info('App context')
// setup(): const notify = useNotification()
```

## 属性 {#props}

| 参数 | 说明 | 类型 | 可选值 | 默认值 |
| --- | --- | --- | --- | --- |
| title | 标题 | string | — | `''` |
| message | 说明文字 | string / VNode | — | `''` |
| dangerouslyUseHTMLString | 是否将 message 属性作为 HTML 片段处理，仅用于可信内容 | boolean | — | false |
| type | 主题样式，如果不在可选值内将被忽略 | string | success / warning / info / error | `''` |
| iconClass | 自定义图标的类名。若设置了有效的 type，则 iconClass 会被覆盖 | string | — | `''` |
| customClass | 自定义类名 | string | — | `''` |
| duration | 显示时间，毫秒。设为 0 则不会自动关闭 | number | — | 4500 |
| position | 自定义弹出位置 | string | top-right / top-left / bottom-right / bottom-left | top-right |
| showClose | 是否显示关闭按钮 | boolean | — | true |
| onClose | 关闭时的回调函数，参数为被关闭实例的公开 handler | `(handler: NotificationHandler) => void` | — | — |
| onClick | 点击 Notification 时的回调函数 | `() => void` | — | — |
| offset | 偏移的距离，同一时刻所有 Notification 实例应具有相同偏移量；另含 16px 窗口边距 | number | — | 0 |
| cancelButtonText | 取消按钮的文本内容 | string | — | `''` |
| confirmButtonText | 确定按钮的文本内容 | string | — | `''` |
| onCancel | 点击取消按钮时的回调函数，不自动关闭通知 | `() => void` | — | — |
| onConfirm | 点击确定按钮时的回调函数，不自动关闭通知 | `() => void` | — | — |
| zIndex | 层级，服务调用默认从 3001 起递增 | number | — | 自动递增 |

## 事件 {#events}

| 事件名称 | 说明 | 回调参数 |
| --- | --- | --- |
| click | 点击 Notification 时的回调函数 | — |
| cancel | 点击取消按钮时的回调函数，不自动关闭通知 | — |
| confirm | 点击确定按钮时的回调函数，不自动关闭通知 | — |
| close | 关闭时触发 | (handler: NotificationHandler) |
| destroy | 离场动画结束后触发 | — |

## 插槽 {#component-slots}

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

## 方法与实例 {#methods}

| API | Description |
| --- | --- |
| Notification(string / VNode / options, appContext?) | Returns NotificationHandler |
| Notification.success / warning / info / error(options?) | Type shortcuts; accept string, VNode or options |
| handler.close() | 关闭当前的 Notification，重复调用仅关闭一次 |
| Notification.close(id, onClose?) | Close by id; identical callback deduplicated |
| Notification.closeAll() | Close a snapshot of active notifications |
| createNotification(appContext) / useNotification() | Context-aware scoped service |

## 迁移说明 {#migration}

保留旧版默认 4500ms、四角独立堆叠、16px 边距和间距、悬停暂停与移出完整重新计时；Delete／Backspace 暂停，其他按键重新计时，Escape 关闭通知。修复键盘重复计时器；悬停期间不会被按键意外启动。高度变化、窗口缩放和中间通知关闭会重新布局。

取消／确认按钮仅调用回调，不自动关闭，也不触发卡片 onClick；如需关闭，请在回调中调用 handler.close()。有效 type 图标优先于 iconClass；无 type 且无 iconClass 时不显示图标。标题和普通字符串默认转义，HTML 模式仅用于可信内容。修复无 message 时默认插槽不显示的问题；业务正文与按钮文本由业务提供，关闭按钮 aria-label 支持八语言。

close() 幂等，close(id) 现在真正关闭 DOM，清理定时器、监听器和观察器。onClose 接收 NotificationHandler（id、position、el／$el／dom、visible、closed、close），不再暴露 Vue 2 私有实例；SSR 返回 closed=true 的空操作 handler。应用专属服务的 close／closeAll 只处理自身通知，直接 Notification.closeAll() 处理页面所有通知。Message 与 Notification 的记录独立。通知挂载到 body，主题跟随根 data-nf-theme；声明式组件不参与服务堆叠。

## Expanded component examples

### NotificationExamples

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

```vue
<script setup lang="ts">
import { ref } from 'vue'
import { useNotification, type NotificationHandler, type NotificationPosition, type NotificationType } from '@94ai-plus/common-ui'
import { useDocsLanguage } from '../locale'

const { english } = useDocsLanguage()
const notify = useNotification()
const position = ref<NotificationPosition>('top-right')
const type = ref<NotificationType>('info')
const duration = ref(0)
const offset = ref(80)
const clicks = ref(0)
const cancels = ref(0)
const confirms = ref(0)
const closes = ref(0)
const lastId = ref('')
let last: NotificationHandler | undefined
function open() {
  last = notify({
    title: english.value ? 'Notification' : '通知', message: 'Notification content',
    position: position.value, type: type.value, duration: duration.value, offset: offset.value,
    customClass: 'notification-demo', cancelButtonText: english.value ? 'Cancel' : '取消',
    confirmButtonText: english.value ? 'Confirm' : '确认',
    onClick: () => { clicks.value++ }, onCancel: () => { cancels.value++ },
    onConfirm: () => { confirms.value++ }, onClose: () => { closes.value++ },
  })
  lastId.value = last.id
}
</script>

<template>
  <section class="notification-examples">
    <div class="notification-controls">
      <label>position <select v-model="position" data-testid="notification-position"><option>top-right</option><option>top-left</option><option>bottom-right</option><option>bottom-left</option></select></label>
      <label>type <select v-model="type" data-testid="notification-type"><option value="">—</option><option>info</option><option>success</option><option>warning</option><option>error</option></select></label>
      <label>duration <input v-model.number="duration" type="number" min="0" data-testid="notification-duration"></label>
      <label>offset <input v-model.number="offset" type="number" min="0" data-testid="notification-offset"></label>
    </div>
    <div class="notification-actions">
      <button type="button" data-testid="notification-open" @click="open">{{ english ? 'Open notification' : '显示通知' }}</button>
      <button type="button" data-testid="notification-stack" @click="open(); open(); open()">{{ english ? 'Stack three' : '堆叠三条' }}</button>
      <button type="button" @click="last?.close()">close()</button>
      <button type="button" data-testid="notification-close-id" @click="notify.close(lastId)">close(id)</button>
      <button type="button" data-testid="notification-close-all" @click="notify.closeAll()">closeAll()</button>
    </div>
    <output data-testid="notification-result">click: {{ clicks }}; cancel: {{ cancels }}; confirm: {{ confirms }}; close: {{ closes }}</output>
  </section>
</template>

<style scoped>
.notification-controls, .notification-actions { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; }
.notification-controls label { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; }
.notification-controls input { width: 70px; }
.notification-controls input, .notification-controls select, .notification-actions button { border: 1px solid var(--site-border); border-radius: 4px; padding: 4px 8px; background: var(--site-background); color: var(--site-text); }
.notification-actions button { cursor: pointer; }
.notification-examples output { display: block; 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 }
}
```
