| 1 | import { create } from 'zustand' |
| 2 | import { toast } from 'sonner' |
| 3 | import type { ReactNode } from 'react' |
| 4 | |
| 5 | export type ToastId = string | number |
| 6 | |
| 7 | interface ToastOptions { |
| 8 | id?: ToastId |
| 9 | description?: ReactNode |
| 10 | duration?: number |
| 11 | action?: { |
| 12 | label: string |
| 13 | onClick: () => void |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | interface ToastState { |
| 18 | success: (message: ReactNode, options?: ToastOptions) => ToastId |
| 19 | error: (message: ReactNode, options?: ToastOptions) => ToastId |
| 20 | info: (message: ReactNode, options?: ToastOptions) => ToastId |
| 21 | warning: (message: ReactNode, options?: ToastOptions) => ToastId |
| 22 | loading: (message: ReactNode, options?: ToastOptions) => ToastId |
| 23 | promise: <T>( |
| 24 | input: Promise<T>, |
| 25 | messages: { |
| 26 | loading: string |
| 27 | success: string | ((data: T) => string) |
| 28 | error: string | ((error: Error) => string) |
| 29 | } |
| 30 | ) => Promise<T> |
| 31 | dismiss: (toastId?: ToastId) => void |
| 32 | } |
| 33 | |
| 34 | export const useToastStore = create<ToastState>(() => ({ |
| 35 | success: (message, options) => toast.success(message, options), |
| 36 | error: (message, options) => toast.error(message, options), |
| 37 | info: (message, options) => toast(message, options), |
| 38 | warning: (message, options) => toast.warning(message, options), |
| 39 | loading: (message, options) => toast.loading(message, options), |
| 40 | promise: (input, messages) => { |
| 41 | toast.promise(input, messages) |
| 42 | return input |
| 43 | }, |
| 44 | dismiss: (toastId) => { |
| 45 | if (toastId) { |
| 46 | toast.dismiss(toastId) |
| 47 | return |
| 48 | } |
| 49 | toast.dismiss() |
| 50 | } |
| 51 | })) |
| 52 |