47 lines
1.1 KiB
TypeScript
47 lines
1.1 KiB
TypeScript
|
|
import { create } from 'zustand';
|
||
|
|
|
||
|
|
export type ToastType = 'success' | 'error' | 'warning' | 'info';
|
||
|
|
|
||
|
|
export interface Toast {
|
||
|
|
id: string;
|
||
|
|
message: string;
|
||
|
|
type: ToastType;
|
||
|
|
duration?: number;
|
||
|
|
}
|
||
|
|
|
||
|
|
interface ToastStore {
|
||
|
|
toasts: Toast[];
|
||
|
|
addToast: (message: string, type?: ToastType, duration?: number) => void;
|
||
|
|
removeToast: (id: string) => void;
|
||
|
|
clearToasts: () => void;
|
||
|
|
}
|
||
|
|
|
||
|
|
export const useToastStore = create<ToastStore>((set) => ({
|
||
|
|
toasts: [],
|
||
|
|
|
||
|
|
addToast: (message: string, type: ToastType = 'info', duration: number = 3000) => {
|
||
|
|
const id = `toast-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||
|
|
const toast: Toast = { id, message, type, duration };
|
||
|
|
|
||
|
|
set((state) => ({
|
||
|
|
toasts: [...state.toasts, toast],
|
||
|
|
}));
|
||
|
|
|
||
|
|
// Auto-remove after duration
|
||
|
|
if (duration > 0) {
|
||
|
|
setTimeout(() => {
|
||
|
|
set((state) => ({
|
||
|
|
toasts: state.toasts.filter((t) => t.id !== id),
|
||
|
|
}));
|
||
|
|
}, duration);
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
removeToast: (id: string) =>
|
||
|
|
set((state) => ({
|
||
|
|
toasts: state.toasts.filter((t) => t.id !== id),
|
||
|
|
})),
|
||
|
|
|
||
|
|
clearToasts: () => set({ toasts: [] }),
|
||
|
|
}));
|