Skip to content

Message ​

A neo-brutalist functional message notification system (useMessage). Built with singleton container dynamic mounting on demand and TransitionGroup stacking animations — no component declaration needed in templates. For modal dialog containers, please refer to Dialog. For confirmation / prompt feedback dialogs, please refer to MessageBox.

Demo ​

Preview

四种消息类型

高级配置

Installation ​

pnpm dlx brutx-vue@latest add message

Usage ​

Basics ​

Use the info, success, warning, and error shortcut methods to display different types of messages.

vue
<script setup>
import { useMessage } from 'brutx-ui-vue'

const { info, success, warning, error } = useMessage()
</script>

<template>
    <button @click="info('Info', 'This is an informational message')">Info</button>
    <button @click="success('Success', 'Operation completed successfully')">Success</button>
    <button @click="warning('Warning', 'Please review your input')">Warning</button>
    <button @click="error('Error', 'Operation failed, please try again')">Error</button>
</template>

Custom Configuration ​

Use the show method with a full options object to customize duration, closability, and more.

vue
<script setup>
import { useMessage } from 'brutx-ui-vue'

const { show } = useMessage()

function showCustom() {
    show({
        type: 'warning',
        title: 'Session Expiring',
        description: 'Your session will expire in 5 minutes. Please save your work.',
        duration: 8000,
        closable: true,
    })
}

function showPersistent() {
    show({
        type: 'error',
        title: 'Network Disconnected',
        description: 'Please check your network settings and try again.',
        duration: 0,
    })
}
</script>

<template>
    <button @click="showCustom">Custom Duration (8s)</button>
    <button @click="showPersistent">No Auto-close</button>
</template>

Manual Close ​

Every method returns a close function. Call it to manually dismiss the corresponding message.

vue
<script setup>
import { useMessage } from 'brutx-ui-vue'
import { ref } from 'vue'

const { info } = useMessage()
const closeFn = ref(null)

function open() {
    closeFn.value = info('Loading', 'Processing your request, please wait...')
}

function close() {
    closeFn.value?.()
}
</script>

<template>
    <button @click="open">Open Message</button>
    <button @click="close">Close Manually</button>
</template>

Long Text Wrapping ​

Titles and descriptions wrap within the available message width, including long words without spaces. The full text remains available, and the close button stays usable.

API Reference ​

MessageContainer is a publicly exported message host with no configurable component props. The entry for message operations is useMessage(), whose shortcuts, show(options), and full MessageOptions definition are documented below.

Data Types ​

MessageType ​

ts
type MessageType = 'info' | 'success' | 'warning' | 'error'

MessageOptions ​

ts
interface MessageOptions {
    type?: 'info' | 'success' | 'warning' | 'error'
    title?: string
    description?: string
    duration?: number
    closable?: boolean
}
FieldTypeDefaultDescription
type'info' | 'success' | 'warning' | 'error''info'Message type
titlestring''Title text
descriptionstring—Description text
durationnumber3000Auto-close duration in milliseconds; set to 0 to disable auto-close
closablebooleantrueWhether to show the close button

MessageItem ​

ts
interface MessageItem {
    id: string
    type: MessageType
    title: string
    description?: string
    duration: number
    closable: boolean
}

ShowDialogOptions ​

The ShowDialogOptions<T> type is exported from brutx-ui-vue/dialog. See showDialog for the options and examples.

Application context for imperative overlays ​

For a custom non-modal overlay, import mountOverlay from brutx-ui-vue and call mountOverlay(Notice, props, { modal: false }).

mountOverlay(), showDialog(), and showMessageBox() use an explicit appContext first, followed by the innermost app.runWithContext() for an app that has installed BrutxUIPlugin. Calls from components can inherit their app and the locale provided by their ancestors. useDialog() and useMessageBox() capture their creation context for use after leaving it. Calls without a caller context use the most recently installed app that is still live. Unmounting an app cleans up overlays scoped to that app.

With the plugin installed, mountOverlay() returns its handle inside the synchronous runWithContext() callback. Calling close() or destroy() there can settle an overlay before it mounts. After the outermost callback finishes and Vue exits the app context, the overlay mounts synchronously before runWithContext() returns. Its props factory first reads state at that point.

An error that Vue would throw during the initial mount cleans up the failed overlay and rejects any still-pending handle promise with the first error. An error raised before runWithContext() returns also propagates synchronously. If both the callback and mounting throw, the synchronous error is the callback's error. If Vue schedules an initial mount hook after the call returns, the failed overlay reports the error through its handle. Custom application error handlers continue to follow Vue's error handling flow.

These context and mounting guarantees apply to runWithContext() call stacks on apps with the plugin installed. An app without the plugin can specify ownership by passing appContext explicitly outside its runWithContext() callback. An asynchronous callback leaves Vue's app context when it resumes after its first await.

MessageBoxOptions ​

The MessageBoxOptions type is exported from brutx-ui-vue/message-box. The MessageBox page documents component props and imperative helpers.

Composables ​

useMessage ​

ts
import { useMessage } from 'brutx-ui-vue'

const {
    info,      // (title: string, description?: string) => () => void
    success,   // (title: string, description?: string) => () => void
    warning,   // (title: string, description?: string) => () => void
    error,     // (title: string, description?: string) => () => void
    show,      // (options: MessageOptions) => () => void
} = useMessage()
MethodParametersReturnDescription
info(title: string, description?: string)() => voidShow an info message; returns a close function
success(title: string, description?: string)() => voidShow a success message; returns a close function
warning(title: string, description?: string)() => voidShow a warning message; returns a close function
error(title: string, description?: string)() => voidShow an error message; returns a close function
show(options: MessageOptions)() => voidShow a custom message; returns a close function

Key features:

  • Singleton pattern: Automatically mounts MessageContainer to body on first call — no manual declaration needed
  • Stacked animations: Multiple messages stack vertically via TransitionGroup with smooth reordering
  • Auto-close: Closes automatically after 3 seconds by default; customize with duration, set to 0 to disable
  • Manual close: Each method returns a close function — call it to dismiss the message immediately
  • Active message guard & Lazy GC: Equipped with dual component refCount and active message guards; active messages are never killed abruptly on unmount. Triggers a 3000ms lazy GC once all messages clear and refCount reaches 0
  • Explicit cleanup. Import destroyMessageFallback from brutx-ui-vue or destroyFallback from brutx-ui-vue/useMessage. To clean up all BrutxUI fallbacks and imperative overlays, call destroyBrutxUI().
  • SSR safe: Uses an internal isClient guard; no side effects or errors in server-side rendering

useDialog ​

ts
import { useDialog } from 'brutx-ui-vue'

const {
    show,      // (options?: ShowDialogOptions) => DialogInstance
} = useDialog()
MethodParametersReturnDescription
show(options?: ShowDialogOptions)DialogInstanceOpen a dialog

Return values:

PropertyTypeDescription
close() => voidManually close the dialog
promisePromise<DialogResult | undefined>Resolves with the dialog result. SSR and global cleanup of a pending dialog resolve with undefined.

useMessageBox ​

ts
import { useMessageBox } from 'brutx-ui-vue'

const {
    show,      // (options?: MessageBoxOptions) => MessageBoxInstance
} = useMessageBox()
MethodParametersReturnDescription
show(options?: MessageBoxOptions)MessageBoxInstanceOpen a confirm/input prompt

Return values:

PropertyTypeDescription
close() => voidManually close the message box
promisePromise<MessageBoxResult>Always resolves { action, value? }: action='confirm' on confirm (value is the input when showInput); action='cancel' on cancel/close button/ESC/overlay; action='destroy' on manual destroy

Accessibility ​

  • Keyboard: Dialogs support Escape to close
  • ARIA Attributes: Messages use role="status" and aria-live="polite" to notify screen readers; the close button includes a localized aria-label for screen reader support
  • Focus Management: useDialog and useMessageBox are built on reka-ui's DialogRoot, trapping focus on open and restoring it on close
  • Reduced Motion: Respects the prefers-reduced-motion system setting and automatically simplifies transition animations

FAQ ​

Q: What is the difference between useMessage and useToast?

A: useMessage is a lightweight top-center notification, ideal for brief operation feedback. useToast offers richer features including configurable positions, stacking options, Promise tracking, and hover-to-pause — better suited for complex notification scenarios.

Q: Will message notifications cause errors in SSR?

A: No. useMessage uses an internal isClient guard, so calling it in a server-side rendering environment produces no side effects and no errors.

Q: How do I perform async validation before closing a dialog?

A: Use the beforeClose hook, which supports both callback and Promise modes:

vue
<script setup>
import { useDialog } from 'brutx-ui-vue'

const { show } = useDialog()

function openWithValidation() {
    show({
        title: 'Edit Profile',
        content: 'Form content...',
        beforeClose: async () => {
            const isValid = await validateForm()
            return isValid
        },
    })
}
</script>

Q: How do I read the result from useMessageBox?

A: Await useMessageBox().show(options).promise and check result.action === 'confirm'. Calling close() without a result and rendering in SSR both yield cancel. Calling destroy() without a result and running global cleanup both yield destroy. See the MessageBox Promise contract.

Brute force builds.