Toast Notification Component
Toast Notification Component
The Toast notification component displays temporary feedback messages with support for multiple types (success, error, warning, info) and auto-dismiss functionality. Deeply integrated with DashboardLayout for global notification capabilities.
Features
- 🎯 Four Types - Support for success, error, warning, and info message types
- ⚡ Simple API - Quick invocation through global
showToast()
function - 🔄 Auto Management - Automatic display, timed dismissal, and memory cleanup
- 🎨 Elegant Animations - Smooth slide-in and slide-out animation effects
- 📱 Responsive Design - Adapts to different screen sizes
- ♿ Accessibility - Screen reader support and ARIA compliance
- 🔧 Batch Management - Support for displaying multiple notifications and batch clearing
Basic Usage
Different tabs demonstrate various Toast usage scenarios:
重要提示
在实际应用中,请确保将 <ToastContainer />
放置在应用的根组件或布局组件中,这样 Toast 通知才能在任何页面正常工作。
展示四种不同类型的 Toast 通知:info、success、warning、error
表单保存
文件上传
系统通知
---
/**
* @component ToastTypes
* @description Toast 类型示例 - 展示不同类型的通知消息
*/
import { ToastContainer } from '@coffic/cosy-ui';
---
<div class="cosy:space-y-4">
<div class="cosy:grid cosy:grid-cols-1 sm:cosy:grid-cols-2 cosy:gap-4">
<button
class="cosy:btn cosy:btn-info cosy:btn-block"
onclick="showToast({ message: '系统信息:数据同步已完成', type: 'info' })">
信息 (Info)
</button>
<button
class="cosy:btn cosy:btn-success cosy:btn-block"
onclick="showToast({ message: '成功:文件上传完成!', type: 'success' })">
成功 (Success)
</button>
<button
class="cosy:btn cosy:btn-warning cosy:btn-block"
onclick="showToast({ message: '警告:磁盘空间不足', type: 'warning' })">
警告 (Warning)
</button>
<button
class="cosy:btn cosy:btn-error cosy:btn-block"
onclick="showToast({ message: '错误:网络连接失败', type: 'error' })">
错误 (Error)
</button>
</div>
</div>
<!-- Toast 容器 - 每个标签页独立 -->
<ToastContainer />
演示如何自定义 Toast 的显示时长,从快速提示到持久显示
表单保存
文件上传
系统通知
---
/**
* @component ToastDuration
* @description Toast 持续时间示例 - 展示不同持续时间的通知
*/
import { ToastContainer } from '@coffic/cosy-ui';
---
<div class="cosy:space-y-4">
<div class="cosy:grid cosy:grid-cols-1 sm:cosy:grid-cols-2 cosy:gap-4">
<button
class="cosy:btn cosy:btn-outline cosy:btn-block"
onclick="showToast({ message: '快速提示(1秒)', type: 'info', duration: 1000 })">
短暂显示 (1s)
</button>
<button
class="cosy:btn cosy:btn-outline cosy:btn-block"
onclick="showToast({ message: '标准提示(3秒)', type: 'success', duration: 3000 })">
标准显示 (3s)
</button>
<button
class="cosy:btn cosy:btn-outline cosy:btn-block"
onclick="showToast({ message: '重要提示(5秒)', type: 'warning', duration: 5000 })">
长时间显示 (5s)
</button>
<button
class="cosy:btn cosy:btn-outline cosy:btn-block"
onclick="showToast({ message: '需要手动关闭的通知', type: 'error', duration: 0 })">
持久显示 (手动关闭)
</button>
</div>
</div>
<!-- Toast 容器 - 每个标签页独立 -->
<ToastContainer />
展示手动控制 Toast 的各种操作:显示、关闭、批量管理
表单保存
文件上传
系统通知
---
/**
* @component ToastControl
* @description Toast 控制示例 - 展示手动控制通知的功能
*/
import { ToastContainer } from '@coffic/cosy-ui';
---
<div class="cosy:space-y-4">
<div class="cosy:space-y-3">
<div class="cosy:flex cosy:gap-3">
<button
class="cosy:btn cosy:btn-primary cosy:flex-1"
onclick="window.currentToastId = showToast({ message: '可控制的通知消息', type: 'info', duration: 0 })">
显示可控制通知
</button>
<button
class="cosy:btn cosy:btn-ghost"
onclick="if (window.currentToastId) { closeToast(window.currentToastId); window.currentToastId = null; }">
关闭
</button>
</div>
<div class="cosy:flex cosy:gap-3">
<button
class="cosy:btn cosy:btn-secondary cosy:flex-1"
onclick="
showToast({ message: '通知 1', type: 'info' });
showToast({ message: '通知 2', type: 'success' });
showToast({ message: '通知 3', type: 'warning' });
">
显示多个通知
</button>
<button class="cosy:btn cosy:btn-ghost" onclick="clearAllToasts()">
清除全部
</button>
</div>
<div class="cosy:divider cosy:my-2"></div>
<button
class="cosy:btn cosy:btn-neutral cosy:btn-block"
onclick="
const id = showToast({ message: '这条通知将在 2 秒后自动关闭', type: 'warning', duration: 0 });
setTimeout(() => closeToast(id), 2000);
">
延时自动关闭示例
</button>
</div>
</div>
<!-- Toast 容器 - 每个标签页独立 -->
<ToastContainer />
模拟真实应用场景:表单保存、文件上传、系统通知等
表单保存
文件上传
系统通知
---
/**
* @component ToastRealWorld
* @description Toast 实际应用场景示例 - 模拟真实的使用场景
*/
import { ToastContainer } from '@coffic/cosy-ui';
---
<div class="cosy:space-y-4">
<div class="cosy:space-y-3">
<!-- 表单保存场景 -->
<div class="cosy:card cosy:bg-base-100 cosy:shadow">
<div class="cosy:card-body cosy:py-4">
<h4 class="cosy:card-title cosy:text-base">表单保存</h4>
<div class="cosy:flex cosy:gap-2">
<button
class="cosy:btn cosy:btn-success cosy:btn-sm"
onclick="
showToast({ message: '用户信息保存成功!', type: 'success' });
">
保存成功
</button>
<button
class="cosy:btn cosy:btn-error cosy:btn-sm"
onclick="
showToast({ message: '保存失败:请检查必填字段', type: 'error', duration: 5000 });
">
保存失败
</button>
</div>
</div>
</div>
<!-- 文件上传场景 -->
<div class="cosy:card cosy:bg-base-100 cosy:shadow">
<div class="cosy:card-body cosy:py-4">
<h4 class="cosy:card-title cosy:text-base">文件上传</h4>
<div class="cosy:flex cosy:gap-2">
<button
class="cosy:btn cosy:btn-primary cosy:btn-sm"
onclick="
const uploadId = showToast({
message: '正在上传文件...',
type: 'info',
duration: 0
});
setTimeout(() => {
closeToast(uploadId);
showToast({ message: '文件上传完成!', type: 'success' });
}, 3000);
">
开始上传
</button>
<button
class="cosy:btn cosy:btn-warning cosy:btn-sm"
onclick="
showToast({
message: '文件大小超过限制(最大 10MB)',
type: 'warning',
duration: 4000
});
">
大小超限
</button>
</div>
</div>
</div>
<!-- 系统通知场景 -->
<div class="cosy:card cosy:bg-base-100 cosy:shadow">
<div class="cosy:card-body cosy:py-4">
<h4 class="cosy:card-title cosy:text-base">系统通知</h4>
<div class="cosy:flex cosy:gap-2">
<button
class="cosy:btn cosy:btn-info cosy:btn-sm"
onclick="
showToast({
message: '系统将在 5 分钟后进行维护',
type: 'info',
duration: 8000
});
">
维护通知
</button>
<button
class="cosy:btn cosy:btn-neutral cosy:btn-sm"
onclick="
showToast({
message: '您有 3 条新消息',
type: 'info'
});
">
新消息提醒
</button>
</div>
</div>
</div>
</div>
</div>
<!-- Toast 容器 - 每个标签页独立 -->
<ToastContainer />
Standalone Usage
Toast component can be used independently by adding ToastContainer:
---
import { ToastContainer } from '@coffic/cosy-ui';
---
<!-- Page content -->
<div>
<button onclick="showToast('Operation successful!')">
Click to show notification
</button>
</div>
<!-- Toast container -->
<ToastContainer />
API Reference
Global Functions
showToast(config)
Display a Toast notification.
// String form (simplified usage)
const id = showToast('Operation successful!');
// Object form (full configuration)
const id = showToast({
message: 'Data saved successfully',
type: 'success', // 'info' | 'success' | 'warning' | 'error'
duration: 3000, // Display duration (milliseconds), 0 means no auto-close
id: 'custom-id' // Optional custom ID
});
Parameters:
config
(string | ToastConfig) - Message content or configuration object
Returns:
string
- Unique ID of the Toast, can be used for manual closing
closeToast(id)
Close a specific Toast notification.
const toastId = showToast('Processing...');
setTimeout(() => closeToast(toastId), 2000);
Parameters:
id
(string) - Unique ID of the Toast
clearAllToasts()
Close all currently displayed Toast notifications.
clearAllToasts();
ToastConfig Interface
interface ToastConfig {
message: string; // Message content
type?: ToastType; // Message type, default 'info'
duration?: number; // Display duration (milliseconds), default 3000
id?: string; // Custom ID, auto-generated if not provided
}
type ToastType = 'info' | 'success' | 'warning' | 'error';
ToastContainer Component
Container component for standalone Toast system usage.
---
import { ToastContainer } from '@coffic/cosy-ui';
---
<!-- Page content -->
<div>
<button onclick="showToast('Hello!')">
Show notification
</button>
</div>
<!-- Toast container -->
<ToastContainer />
Note: No need to manually add ToastContainer when using DashboardLayout.
Style Customization
The Toast component uses DaisyUI’s alert style system with theme switching support:
/* Custom Toast container position */
#toast-container {
top: 1rem;
right: 1rem;
z-index: 50;
}
/* Custom animation duration */
.toast-enter, .toast-exit {
transition-duration: 300ms;
}
Best Practices
1. Use Message Types Appropriately
// ✅ Correct: Choose appropriate type based on operation result
showToast({ message: 'User created successfully', type: 'success' });
showToast({ message: 'Network connection failed', type: 'error' });
showToast({ message: 'Please pay attention to data security', type: 'warning' });
showToast({ message: 'System maintenance notification', type: 'info' });
// ❌ Wrong: Type doesn't match message content
showToast({ message: 'Operation failed', type: 'success' });
2. Set Appropriate Display Duration
// ✅ Correct: Set duration based on message importance
showToast({ message: 'Saved successfully', duration: 2000 }); // Simple confirmation
showToast({ message: 'Important warning message', duration: 5000 }); // Important reminder
showToast({ message: 'Processing...', duration: 0 }); // Requires manual closing
// ❌ Wrong: Important information displayed too briefly
showToast({ message: 'System will restart, please save data', duration: 1000 });
3. Avoid Information Overload
// ✅ Correct: Combine related messages
showToast({ message: 'Batch operation completed: 5 successful, 1 failed', type: 'warning' });
// ❌ Wrong: Too many messages in short time
for (let i = 0; i < 10; i++) {
showToast(`Processing item ${i + 1}`);
}
4. Provide Meaningful Messages
// ✅ Correct: Clear operation feedback
showToast({ message: 'User "John Doe" has been deleted', type: 'success' });
showToast({ message: 'Upload failed: File size exceeds 10MB', type: 'error' });
// ❌ Wrong: Vague messages
showToast({ message: 'Operation completed', type: 'success' });
showToast({ message: 'Something went wrong', type: 'error' });
Common Issues
Q: Why is showToast function undefined?
A: Ensure proper integration of the Toast system:
- Use DashboardLayout with
enableToast
set to true (default) - Or manually add
<ToastContainer />
to the page - Wait for page to fully load before calling
Q: How to use during server-side rendering?
A: Toast is a client-side feature, only usable in browser environment:
// ✅ Correct: Check environment
if (typeof window !== 'undefined') {
showToast('Client-side message');
}
// Or use in event handlers
function handleClick() {
showToast('Click successful'); // Event handlers always execute on client-side
}
Q: How to implement persistent notifications?
A: Set duration
to 0 and manually control closing:
const persistentToast = showToast({
message: 'Important: Please complete required fields',
type: 'warning',
duration: 0 // No auto-close
});
// Close when condition is met
if (formIsValid) {
closeToast(persistentToast);
}