"use client"; import { createContext, useCallback, useContext, useRef, useState, } from "react"; import { cn } from "@/lib/utils"; type ToastKind = "success" | "error" | "info"; interface Toast { id: number; kind: ToastKind; message: string; } interface ToastApi { push: (message: string, kind?: ToastKind) => void; success: (message: string) => void; error: (message: string) => void; } const ToastContext = createContext(null); export function ToastProvider({ children }: { children: React.ReactNode }) { const [toasts, setToasts] = useState([]); const idRef = useRef(0); const push = useCallback((message: string, kind: ToastKind = "info") => { const id = ++idRef.current; setToasts((prev) => [...prev, { id, kind, message }]); setTimeout(() => { setToasts((prev) => prev.filter((t) => t.id !== id)); }, 4000); }, []); const api: ToastApi = { push, success: (m) => push(m, "success"), error: (m) => push(m, "error"), }; return ( {children}
{toasts.map((t) => (
{t.message}
))}
); } export function useToast(): ToastApi { const ctx = useContext(ToastContext); if (!ctx) throw new Error("useToast must be used within "); return ctx; }