All files / src/components Toasts.tsx

100% Statements 30/30
100% Branches 10/10
100% Functions 2/2
100% Lines 30/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 481x                       1x   1x 23x 23x 23x   23x 6x 6x 6x 1x 6x 6x 23x   23x   23x 23x 23x 23x 23x 7x 7x 7x 23x 23x 23x   23x   1x 84x 84x  
import { createContext, useCallback, useContext, useMemo, useRef, useState, type ReactNode } from "react";
 
export type ToastTone = "success" | "danger";
 
interface Toast {
  id: number;
  text: string;
  tone: ToastTone;
}
 
type Notify = (text: string, tone?: ToastTone) => void;
 
const ToastContext = createContext<Notify>(() => undefined);
 
export function ToastProvider({ children }: { children: ReactNode }) {
  const [items, setItems] = useState<Toast[]>([]);
  const nextId = useRef(1);
  const timers = useRef<number[]>([]);
 
  const notify = useCallback<Notify>((text, tone = "success") => {
    const id = nextId.current++;
    setItems((current) => [...current, { id, text, tone }]);
    const timer = window.setTimeout(() => {
      setItems((current) => current.filter((item) => item.id !== id));
    }, 4000);
    timers.current.push(timer);
  }, []);
 
  useMemo(() => () => timers.current.forEach((timer) => window.clearTimeout(timer)), []);
 
  return (
    <ToastContext.Provider value={notify}>
      {children}
      <div className="toasts" aria-live="polite" aria-atomic="false">
        {items.map((item) => (
          <div key={item.id} className={`toast toast--${item.tone}`} role="status">
            {item.text}
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
}
 
export function useToast(): Notify {
  return useContext(ToastContext);
}