| 57 | const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>() |
| 58 | |
| 59 | const reducer = (state: State, action: Action): State => { |
| 60 | switch (action.type) { |
| 61 | case "ADD_TOAST": |
| 62 | return { |
| 63 | ...state, |
| 64 | toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT), |
| 65 | } |
| 66 | |
| 67 | case "UPDATE_TOAST": |
| 68 | return { |
| 69 | ...state, |
| 70 | toasts: state.toasts.map((t) => (t.id === action.toast.id ? { ...t, ...action.toast } : t)), |
| 71 | } |
| 72 | |
| 73 | case "DISMISS_TOAST": { |
| 74 | const { toastId } = action |
| 75 | |
| 76 | if (toastId) { |
| 77 | toastTimeouts.set( |
| 78 | toastId, |
| 79 | setTimeout(() => { |
| 80 | toastTimeouts.delete(toastId) |
| 81 | dispatch({ |
| 82 | type: "REMOVE_TOAST", |
| 83 | toastId, |
| 84 | }) |
| 85 | }, TOAST_REMOVE_DELAY), |
| 86 | ) |
| 87 | } |
| 88 | |
| 89 | return { |
| 90 | ...state, |
| 91 | toasts: state.toasts.map((t) => |
| 92 | t.id === toastId || toastId === undefined |
| 93 | ? { |
| 94 | ...t, |
| 95 | open: false, |
| 96 | } |
| 97 | : t, |
| 98 | ), |
| 99 | } |
| 100 | } |
| 101 | case "REMOVE_TOAST": |
| 102 | if (action.toastId === undefined) { |
| 103 | return { |
| 104 | ...state, |
| 105 | toasts: [], |
| 106 | } |
| 107 | } |
| 108 | return { |
| 109 | ...state, |
| 110 | toasts: state.toasts.filter((t) => t.id !== action.toastId), |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | const listeners: Array<(state: State) => void> = [] |
| 116 | |