Files
cinch/src/lib/stores/toast.svelte.ts

35 lines
692 B
TypeScript

import type { Toast, ToastType } from '$lib/types';
const defaultDurations: Record<ToastType, number> = {
success: 4000,
info: 4000,
warning: 6000,
error: 0
};
let nextId = 0;
class ToastStore {
items: Toast[] = $state([]);
add(type: ToastType, message: string, duration?: number): string {
const id = String(nextId++);
const dur = duration ?? defaultDurations[type];
this.items.push({ id, type, message, duration: dur });
if (dur > 0) {
setTimeout(() => this.remove(id), dur);
}
return id;
}
remove(id: string) {
const idx = this.items.findIndex((t) => t.id === id);
if (idx !== -1) this.items.splice(idx, 1);
}
}
export const toasts = new ToastStore();