'use client'; import { cn } from '@/lib/utils'; import React, { createContext, useCallback, useContext, useState } from 'react'; import { Icon } from './Icon'; export type ToastType = 'success' | 'error' | 'warning' | 'info'; export interface ToastMessage { id: string; type: ToastType; title: string; message?: string; duration?: number; } interface ToastContextType { toast: (options: Omit) => void; success: (title: string, message?: string) => void; error: (title: string, message?: string) => void; warning: (title: string, message?: string) => void; info: (title: string, message?: string) => void; } const ToastContext = createContext(undefined); export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [toasts, setToasts] = useState([]); const removeToast = useCallback((id: string) => { setToasts((prev) => prev.filter((t) => t.id !== id)); }, []); const addToast = useCallback( ({ type = 'info', title, message, duration = 3500 }: Omit) => { const id = `${Date.now()}-${Math.random().toString(36).substring(2, 7)}`; setToasts((prev) => [...prev, { id, type, title, message, duration }]); if (duration > 0) { setTimeout(() => { removeToast(id); }, duration); } }, [removeToast] ); const success = useCallback((title: string, message?: string) => addToast({ type: 'success', title, message }), [addToast]); const error = useCallback((title: string, message?: string) => addToast({ type: 'error', title, message }), [addToast]); const warning = useCallback((title: string, message?: string) => addToast({ type: 'warning', title, message }), [addToast]); const info = useCallback((title: string, message?: string) => addToast({ type: 'info', title, message }), [addToast]); return ( {children}
{toasts.map((t) => { const typeBorder = { success: 'border-l-[3px] border-l-[var(--success)]', error: 'border-l-[3px] border-l-[var(--danger)]', warning: 'border-l-[3px] border-l-[var(--warning)]', info: 'border-l-[3px] border-l-[var(--accent)]', }[t.type]; const typeIcon = { success: 'CheckCircle2', error: 'AlertCircle', warning: 'AlertTriangle', info: 'Info', }[t.type]; const iconColor = { success: 'var(--success)', error: 'var(--danger)', warning: 'var(--warning)', info: 'var(--accent)', }[t.type]; return (
{t.title}
{t.message && (
{t.message}
)}
); })}
); }; export const useToast = () => { const context = useContext(ToastContext); if (!context) { throw new Error('useToast must be used within a ToastProvider'); } return context; }; export default ToastProvider;