import { reactive } from 'vue'; const MAX_VISIBLE = 4; const DEFAULT_TIMEOUT = 5000; const ERROR_TIMEOUT = 8000; // Module-level state: every caller (views, ToastContainer) shares the same list const toasts = reactive([]); const timers = new Map(); // id -> { handle, startedAt, remaining } let nextId = 1; const clearTimer = (id) => { const t = timers.get(id); if (t) clearTimeout(t.handle); timers.delete(id); }; const dismiss = (id) => { clearTimer(id); const idx = toasts.findIndex((t) => t.id === id); if (idx !== -1) toasts.splice(idx, 1); }; const startTimer = (id, ms) => { clearTimer(id); timers.set(id, { handle: setTimeout(() => dismiss(id), ms), startedAt: Date.now(), remaining: ms }); }; // Stop the countdown (mouse over the toast); the progress bar is paused by CSS const pause = (id) => { const t = timers.get(id); if (!t) return; clearTimeout(t.handle); t.remaining = Math.max(0, t.remaining - (Date.now() - t.startedAt)); t.handle = null; }; const resume = (id) => { const t = timers.get(id); if (!t || t.handle !== null) return; startTimer(id, t.remaining); }; const show = (text, type = 'success', timeout) => { const kind = ['success', 'warning', 'error', 'info'].includes(type) ? type : 'info'; const duration = timeout ?? (kind === 'error' ? ERROR_TIMEOUT : DEFAULT_TIMEOUT); const id = nextId++; toasts.push({ id, text: String(text ?? ''), type: kind, timeout: duration }); while (toasts.length > MAX_VISIBLE) dismiss(toasts[0].id); if (duration > 0) startTimer(id, duration); return id; }; // Drop everything and release all timers (container unmount) const clear = () => { timers.forEach((t) => clearTimeout(t.handle)); timers.clear(); toasts.splice(0, toasts.length); }; export function useToast() { return { toasts, show, dismiss, pause, resume, clear }; }