| 1 | // A tiny store for toasts. Anything may call toast(), and <Toasts> |
| 2 | // reads them with useSyncExternalStore. |
| 3 | type Toast = { id: number; text: string } |
| 4 | |
| 5 | let toasts: Toast[] = [] |
| 6 | let last = 0 |
| 7 | const listeners = new Set<() => void>() |
| 8 | |
| 9 | function set(next: Toast[]) { |
| 10 | toasts = next |
| 11 | listeners.forEach((listener) => listener()) |
| 12 | } |
| 13 | |
| 14 | export function toast(text: string) { |
| 15 | if (toasts.some((t) => t.text === text)) return // once is enough |
| 16 | const id = ++last |
| 17 | set([...toasts, { id, text }].slice(-3)) |
| 18 | setTimeout(() => set(toasts.filter((t) => t.id !== id)), 4000) |
| 19 | } |
| 20 | |
| 21 | export const getToasts = () => toasts |
| 22 | export function subscribe(listener: () => void) { |
| 23 | listeners.add(listener) |
| 24 | return () => listeners.delete(listener) |
| 25 | } |