import { setDebug } from "../../lib/debug"; import { DEFAULT_DURATION, TIME_BEFORE_UNMOUNT } from "./constants"; import type { ExternalToast, PromiseData, ToastContent, ToastT } from "./types"; let toastsCounter = 1; let listeners: Array<(toasts: Array) => void> = []; let toasts: Array = []; let toastsEnabled = true; let mounted = false; const removalTimers = new Map>(); function notify() { listeners.forEach(listener => listener([...toasts])); } function upsertToast(nextToast: ToastT) { const index = toasts.findIndex(toast => toast.id === nextToast.id); if (index === -1) { toasts = [nextToast, ...toasts]; } else { toasts = [...toasts.slice(0, index), { ...toasts[index], ...nextToast }, ...toasts.slice(index + 1)]; } notify(); } function finalizeRemoval(id: number | string) { toasts = toasts.filter(toast => toast.id !== id); removalTimers.delete(id); notify(); } function scheduleRemoval(id: number | string) { if (removalTimers.has(id)) return; const toastToRemove = toasts.find(toast => toast.id === id); toasts = toasts.map(toast => toast.id === id ? { ...toast, delete: true } : toast); toastToRemove?.onDismiss?.(toastToRemove); notify(); const timer = setTimeout(() => finalizeRemoval(id), TIME_BEFORE_UNMOUNT); removalTimers.set(id, timer); } function createToast(data: ExternalToast & { message?: ToastContent; }) { if (!toastsEnabled) return undefined; const { message, dismissible, duration, ...rest } = data; const id = data.id ?? toastsCounter++; const nextToast: ToastT = { ...rest, id, title: message, type: rest.type ?? "default", dismissible: dismissible ?? true, duration: duration ?? DEFAULT_DURATION }; upsertToast(nextToast); return id; } async function resolvePromiseValue(value: PromiseData["success"] | PromiseData["error"], data: T) { if (typeof value === "function") { const result = value(data); return result instanceof Promise ? await result : result; } return value; } async function resolveDescription(value: PromiseData["description"], data: T) { const resolved = await resolvePromiseValue(value, data); if (resolved && typeof resolved === "object" && "message" in resolved) { return resolved.description; } return resolved; } async function handlePromiseResult(value: PromiseData["success"] | PromiseData["error"], data: T) { const resolved = await resolvePromiseValue(value, data); if (resolved && typeof resolved === "object" && "message" in resolved) { return resolved; } if (resolved !== undefined) { return { message: resolved }; } return null; } function dismiss(id?: number | string) { if (!toastsEnabled) return id; if (id !== undefined) { scheduleRemoval(id); return id; } toasts.forEach(toast => scheduleRemoval(toast.id)); return undefined; } function create(message: ToastContent, data?: ExternalToast) { if (!toastsEnabled) return undefined; if (!mounted) mounted = true; return createToast({ ...data, message }); } function error(message: ToastContent, data?: ExternalToast) { return createToast({ ...data, message, type: "error" }); } function success(message: ToastContent, data?: ExternalToast) { return createToast({ ...data, message, type: "success" }); } function info(message: ToastContent, data?: ExternalToast) { return createToast({ ...data, message, type: "info" }); } function warning(message: ToastContent, data?: ExternalToast) { return createToast({ ...data, message, type: "warning" }); } function loading(message: ToastContent, data?: ExternalToast) { return createToast({ ...data, message, type: "loading", duration: Infinity }); } function promise(promiseValue: Promise | (() => Promise), data?: PromiseData) { if (!data) return; const { loading, success: successValue, error: errorValue, description, finally: finallyFn, ...rest } = data; let id: number | string | undefined = undefined; if (loading !== undefined) { id = createToast({ ...rest, message: loading, type: "loading", duration: Infinity, description: typeof description === "function" ? undefined : description }); } const promiseResult = Promise.resolve(promiseValue instanceof Function ? promiseValue() : promiseValue); promiseResult.then(async response => { if (successValue !== undefined) { const result = await handlePromiseResult(successValue, response); const resolvedDescription = await resolveDescription(description, response); if (result) { const { message, description: resultDescription, type } = result as { message: ToastContent; description?: ToastContent; type?: ToastT["type"]; }; createToast({ ...rest, id, message, description: resultDescription ?? resolvedDescription, type: type ?? "success" }); } } else if (id !== undefined) { dismiss(id); } }).catch(async errorValueResponse => { if (errorValue !== undefined) { const result = await handlePromiseResult(errorValue, errorValueResponse); const resolvedDescription = await resolveDescription(description, errorValueResponse); if (result) { const { message, description: resultDescription, type } = result as { message: ToastContent; description?: ToastContent; type?: ToastT["type"]; }; createToast({ ...rest, id, message, description: resultDescription ?? resolvedDescription, type: type ?? "error" }); } } else if (id !== undefined) { dismiss(id); } }).finally(() => { finallyFn?.(); }); const unwrap = () => new Promise((resolve, reject) => { promiseResult.then(resolve).catch(reject); }); if (id !== undefined) { return Object.assign(id, { unwrap }); } return { unwrap }; } export const toast = Object.assign(create, { success, info, warning, error, loading, promise, dismiss, getHistory: () => toasts, getToasts: () => toasts.filter(toast => !toast.delete) }); export function subscribe(fn: (toasts: Array) => void) { listeners.push(fn); fn([...toasts]); return () => { listeners = listeners.filter(listener => listener !== fn); }; } export function setToastsEnabled(enabled: boolean) { toastsEnabled = enabled; if (!enabled) { toasts = []; removalTimers.forEach(timer => clearTimeout(timer)); removalTimers.clear(); notify(); } } setDebug("toast", { ...toast, subscribe, setToastsEnabled })