59 lines
1.5 KiB
TypeScript
59 lines
1.5 KiB
TypeScript
import { writable } from "svelte/store";
|
|
|
|
export interface Toast {
|
|
id: string;
|
|
message: string;
|
|
type: "success" | "error" | "info" | "warning";
|
|
duration?: number;
|
|
}
|
|
|
|
interface ToastStore {
|
|
toasts: Toast[];
|
|
}
|
|
|
|
function createToastStore() {
|
|
const { subscribe, update } = writable<ToastStore>({ toasts: [] });
|
|
|
|
return {
|
|
subscribe,
|
|
show: (message: string, type: Toast["type"] = "info", duration = 3000) => {
|
|
const id = `toast-${Date.now()}-${Math.random()}`;
|
|
const toast: Toast = { id, message, type, duration };
|
|
|
|
update((store) => ({
|
|
toasts: [...store.toasts, toast],
|
|
}));
|
|
|
|
// Auto-dismiss after duration
|
|
if (duration > 0) {
|
|
setTimeout(() => {
|
|
update((store) => ({
|
|
toasts: store.toasts.filter((t) => t.id !== id),
|
|
}));
|
|
}, duration);
|
|
}
|
|
|
|
return id;
|
|
},
|
|
dismiss: (id: string) => {
|
|
update((store) => ({
|
|
toasts: store.toasts.filter((t) => t.id !== id),
|
|
}));
|
|
},
|
|
success: (message: string, duration?: number) => {
|
|
return createToastStore().show(message, "success", duration);
|
|
},
|
|
error: (message: string, duration?: number) => {
|
|
return createToastStore().show(message, "error", duration);
|
|
},
|
|
info: (message: string, duration?: number) => {
|
|
return createToastStore().show(message, "info", duration);
|
|
},
|
|
warning: (message: string, duration?: number) => {
|
|
return createToastStore().show(message, "warning", duration);
|
|
},
|
|
};
|
|
}
|
|
|
|
export const toast = createToastStore();
|