64 lines
1.5 KiB
TypeScript
64 lines
1.5 KiB
TypeScript
import { writable } from 'svelte/store';
|
|
|
|
export interface Toast {
|
|
id: string;
|
|
message: string;
|
|
type: 'error' | 'success' | 'warning' | 'info';
|
|
duration?: number;
|
|
}
|
|
|
|
function createToastStore() {
|
|
const { subscribe, update } = writable<Toast[]>([]);
|
|
|
|
const store = {
|
|
subscribe,
|
|
|
|
// Add a new toast
|
|
add: (toast: Omit<Toast, 'id'>) => {
|
|
const id = crypto.randomUUID();
|
|
const newToast: Toast = {
|
|
id,
|
|
duration: 5000, // Default 5 seconds
|
|
...toast
|
|
};
|
|
|
|
update(toasts => [...toasts, newToast]);
|
|
return id;
|
|
},
|
|
|
|
// Remove a toast by ID
|
|
remove: (id: string) => {
|
|
update(toasts => toasts.filter(toast => toast.id !== id));
|
|
},
|
|
|
|
// Clear all toasts
|
|
clear: () => {
|
|
update(() => []);
|
|
}
|
|
};
|
|
|
|
// Add convenience methods that reference the same store instance
|
|
return {
|
|
...store,
|
|
|
|
// Convenience methods for different toast types
|
|
success: (message: string, duration?: number) => {
|
|
return store.add({ message, type: 'success', duration });
|
|
},
|
|
|
|
error: (message: string, duration?: number) => {
|
|
return store.add({ message, type: 'error', duration });
|
|
},
|
|
|
|
warning: (message: string, duration?: number) => {
|
|
return store.add({ message, type: 'warning', duration });
|
|
},
|
|
|
|
info: (message: string, duration?: number) => {
|
|
return store.add({ message, type: 'info', duration });
|
|
}
|
|
};
|
|
}
|
|
|
|
export const toast = createToastStore();
|