|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { createContext, useContext, useState, ReactNode, useCallback } from 'react' |
| 4 | +import { Toast, ToastProps } from '@/components/ui/toast' |
| 5 | + |
| 6 | +interface ToastContextType { |
| 7 | + showToast: (message: string, type?: ToastProps['type'], duration?: number) => void |
| 8 | + showSuccess: (message: string, duration?: number) => void |
| 9 | + showError: (message: string, duration?: number) => void |
| 10 | + showWarning: (message: string, duration?: number) => void |
| 11 | + showInfo: (message: string, duration?: number) => void |
| 12 | +} |
| 13 | + |
| 14 | +const ToastContext = createContext<ToastContextType | null>(null) |
| 15 | + |
| 16 | +interface ToastItem extends Omit<ToastProps, 'onClose'> { |
| 17 | + id: string |
| 18 | +} |
| 19 | + |
| 20 | +export function ToastProvider({ children }: { children: ReactNode }) { |
| 21 | + const [toasts, setToasts] = useState<ToastItem[]>([]) |
| 22 | + |
| 23 | + const removeToast = useCallback((id: string) => { |
| 24 | + setToasts(prev => prev.filter(toast => toast.id !== id)) |
| 25 | + }, []) |
| 26 | + |
| 27 | + const showToast = useCallback(( |
| 28 | + message: string, |
| 29 | + type: ToastProps['type'] = 'success', |
| 30 | + duration = 3000 |
| 31 | + ) => { |
| 32 | + const id = Date.now().toString() + Math.random().toString(36).substr(2, 9) |
| 33 | + const newToast: ToastItem = { |
| 34 | + id, |
| 35 | + message, |
| 36 | + type, |
| 37 | + duration |
| 38 | + } |
| 39 | + setToasts(prev => [...prev, newToast]) |
| 40 | + }, []) |
| 41 | + |
| 42 | + const showSuccess = useCallback((message: string, duration?: number) => { |
| 43 | + showToast(message, 'success', duration) |
| 44 | + }, [showToast]) |
| 45 | + |
| 46 | + const showError = useCallback((message: string, duration?: number) => { |
| 47 | + showToast(message, 'error', duration) |
| 48 | + }, [showToast]) |
| 49 | + |
| 50 | + const showWarning = useCallback((message: string, duration?: number) => { |
| 51 | + showToast(message, 'warning', duration) |
| 52 | + }, [showToast]) |
| 53 | + |
| 54 | + const showInfo = useCallback((message: string, duration?: number) => { |
| 55 | + showToast(message, 'info', duration) |
| 56 | + }, [showToast]) |
| 57 | + |
| 58 | + return ( |
| 59 | + <ToastContext.Provider value={{ showToast, showSuccess, showError, showWarning, showInfo }}> |
| 60 | + {children} |
| 61 | + {toasts.map(toast => ( |
| 62 | + <Toast |
| 63 | + key={toast.id} |
| 64 | + {...toast} |
| 65 | + onClose={removeToast} |
| 66 | + /> |
| 67 | + ))} |
| 68 | + </ToastContext.Provider> |
| 69 | + ) |
| 70 | +} |
| 71 | + |
| 72 | +export function useToast() { |
| 73 | + const context = useContext(ToastContext) |
| 74 | + if (!context) { |
| 75 | + throw new Error('useToast must be used within a ToastProvider') |
| 76 | + } |
| 77 | + return context |
| 78 | +} |
0 commit comments