flnxi-Wu/app/admin/_hooks/useToast.ts
WuYongJie e4dcb6260a
Some checks failed
CI Check / check (push) Has been cancelled
feat: Admin页面重构 & UI三层架构系统
- 创建统一UI三层架构系统(基础层、颜色层、组合层)
- 拆分Admin页面为独立Tab组件(MonitorTab、UsersTab、DepartmentsTab等)
- 提取公共逻辑到Hooks(useToast、useDataFetch、useUserOperations等)
- 提取工具函数(validators、formatters、api等)
- 创建统一弹窗组件(Modal)和useModal Hook
- 添加错误边界和统一状态组件
- 完善类型定义和可访问性支持
- 更新文档(优化记录、优化计划、更新日志)
2025-11-22 15:17:10 +08:00

66 lines
1.3 KiB
TypeScript

'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
export type ToastType = 'success' | 'error'
export interface ToastState {
id: number
message: string
type: ToastType
}
interface UseToastOptions {
duration?: number
}
export function useToast(options: UseToastOptions = {}) {
const { duration = 3000 } = options
const [toast, setToast] = useState<ToastState | null>(null)
const timerRef = useRef<NodeJS.Timeout | null>(null)
const idRef = useRef(0)
const dismissToast = useCallback(() => {
if (timerRef.current) {
clearTimeout(timerRef.current)
timerRef.current = null
}
setToast(null)
}, [])
useEffect(() => {
if (!toast) return undefined
if (timerRef.current) {
clearTimeout(timerRef.current)
}
timerRef.current = setTimeout(() => {
setToast(null)
timerRef.current = null
}, duration)
return () => {
if (timerRef.current) {
clearTimeout(timerRef.current)
timerRef.current = null
}
}
}, [toast, duration])
const showToast = useCallback((message: string, type: ToastType = 'success') => {
idRef.current += 1
setToast({
id: idRef.current,
message,
type,
})
}, [])
return {
toast,
showToast,
dismissToast,
}
}
export type UseToastReturn = ReturnType<typeof useToast>