xonecas.io
8058
Ir

irvc / files

irvc / web / src / lib / toast.ts

790 bytes
1import { useSyncExternalStore } from "react";
2
3export type Toast = { id: number; text: string };
4
5// How long a toast lives, matching the fade-out in index.css (.toast).
6const life = 5000;
7
8let toasts: Toast[] = [];
9let nextId = 1;
10const subs = new Set<() => void>();
11
12function publish() {
13  subs.forEach((fn) => fn());
14}
15
16// toast surfaces a transient error and lets it fade away on its own.
17export function toast(text: string) {
18  const t = { id: nextId++, text };
19  toasts = [...toasts, t];
20  publish();
21  setTimeout(() => {
22    toasts = toasts.filter((x) => x.id !== t.id);
23    publish();
24  }, life);
25}
26
27export function useToasts() {
28  return useSyncExternalStore(
29    (fn) => {
30      subs.add(fn);
31      return () => {
32        subs.delete(fn);
33      };
34    },
35    () => toasts,
36  );
37}