this repo has no description
1export type ToastType = "success" | "error" | "warning" | "info";
2
3export interface Toast {
4 id: number;
5 type: ToastType;
6 message: string;
7 duration: number;
8 dismissing?: boolean;
9}
10
11let nextId = 0;
12let toasts = $state<Toast[]>([]);
13
14export function getToasts(): readonly Toast[] {
15 return toasts;
16}
17
18export function showToast(
19 type: ToastType,
20 message: string,
21 duration = 5000,
22): number {
23 const id = nextId++;
24 toasts = [...toasts, { id, type, message, duration }];
25
26 if (duration > 0) {
27 setTimeout(() => {
28 dismissToast(id);
29 }, duration);
30 }
31
32 return id;
33}
34
35export function dismissToast(id: number): void {
36 const toast = toasts.find((t) => t.id === id);
37 if (!toast || toast.dismissing) return;
38
39 toasts = toasts.map((t) => t.id === id ? { ...t, dismissing: true } : t);
40
41 setTimeout(() => {
42 toasts = toasts.filter((t) => t.id !== id);
43 }, 150);
44}
45
46export function clearAllToasts(): void {
47 toasts = [];
48}
49
50export function success(message: string, duration?: number): number {
51 return showToast("success", message, duration);
52}
53
54export function error(message: string, duration?: number): number {
55 return showToast("error", message, duration);
56}
57
58export function warning(message: string, duration?: number): number {
59 return showToast("warning", message, duration);
60}
61
62export function info(message: string, duration?: number): number {
63 return showToast("info", message, duration);
64}
65
66export const toast = {
67 show: showToast,
68 success,
69 error,
70 warning,
71 info,
72 dismiss: dismissToast,
73 clear: clearAllToasts,
74};