﻿# Notification {#notification}

Corner notifications with auto-close, independent stacks, action buttons and Chalk/OEM themes.

The default export is a component plugin; the named `Notification` export is the callable service. CommonUI or `app.use(NfNotification)` installs `this.$openNotify`. In setup, `useNotification()` inherits provider injections and locale and disposes notifications on unmount. `createNotification(appContext)` creates an app-scoped service. Direct Notification never implicitly binds the last installed app; pass appContext as its second argument when needed.

## Basic usage and positions {#basic}

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

## Notification types {#variants}

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

## Cancel and confirm {#actions}

### Cancel and confirm
```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>
```

## Text, HTML and VNode {#content}

### Text, HTML and 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>
```

## Component and default slot {#slots}

### Component and default slot
```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 example {#interactive}


See expanded example example-6 (NotificationExamples).


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

## 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 |
| 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 | — | `''` |
| duration | Display duration in ms; 0 disables automatic closing | number | — | 4500 |
| position | Custom popup position | string | top-right / top-left / bottom-right / bottom-left | top-right |
| showClose | Whether to show the close button | boolean | — | true |
| onClose | Close callback, receiving the closed instance’s public handler | `(handler: NotificationHandler) => void` | — | — |
| onClick | Callback when Notification is clicked | `() => void` | — | — |
| offset | Offset shared by simultaneous Notification instances; an additional 16px viewport margin applies | number | — | 0 |
| cancelButtonText | Cancel button text | string | — | `''` |
| confirmButtonText | Confirm button text | string | — | `''` |
| onCancel | Cancel button callback; does not close the notification automatically | `() => void` | — | — |
| onConfirm | Confirm button callback; does not close the notification automatically | `() => void` | — | — |
| zIndex | Stacking level; service calls increment from 3001 | number | — | Auto-incremented |

## Events {#events}

| Event | Description | Payload |
| --- | --- | --- |
| click | Callback when Notification is clicked | — |
| cancel | Cancel button callback; does not close the notification automatically | — |
| confirm | Confirm button callback; does not close the notification automatically | — |
| close | Emitted on close | (handler: NotificationHandler) |
| destroy | Emitted after the leave transition | — |

## Slots {#component-slots}

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

## Methods and handler {#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() | Close the current Notification; repeated calls are harmless |
| 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 notes {#migration}

Preserves the 4500ms default, independent corner stacks, 16px edges/gaps, hover pause and full-duration restart on leave. Delete/Backspace pause; other keys restart; Escape closes notifications. Keyboard handling no longer creates duplicate timers or restarts while hovering. Height changes, resizing and middle-item removal trigger reflow.

Cancel/confirm only invoke callbacks, without automatically closing or triggering card onClick. Call handler.close() explicitly when needed. Recognized type icons take priority over iconClass; no type/iconClass means no icon. Titles and strings are escaped. HTML mode is only for trusted content. Slot-only content now renders without message. Business content/action labels are supplied by the caller; close aria-label supports eight languages.

close() is idempotent; close(id) really closes the DOM and releases timers/listeners/observers. onClose receives NotificationHandler (id, position, el/$el/dom, visible, closed, close), not Vue 2 private instance fields. SSR returns a closed no-op handler. Scoped close/closeAll only affect owned notifications; direct Notification.closeAll() affects all notifications on the page. Message and Notification keep separate registries. Notifications mount into body and follow root data-nf-theme; declarative components do not join service stacks.

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