// The toast list, kept out of the component so `npm test` runs it. A toast is // a short note that needs no answer: it shows for a few seconds and goes away // by itself, and a click dismisses it sooner. Anything that shows one calls // `showToast`; `` renders the list. import type { Tone } from "@hive/shared/tone.js"; export type ToastTone = Exclude; export interface Toast { id: number; message: string; tone: ToastTone; /** How long it stays, in ms. */ duration: number; } /** An error lingers longer, since it is the one worth reading twice. */ export function toastDuration(tone: ToastTone): number { return tone === "error" ? 8000 : 4000; } /** What is left of a toast's time after it has been up `shownMs`. */ export function timeLeft(duration: number, shownMs: number): number { return Math.max(0, duration - shownMs); } /** How long a toast the pointer left has to go: its time left, but never less * than a moment, so one let go at the last second can still be read. */ export const RESUME_FLOOR_MS = 1500; export function resumeDelay(left: number): number { return Math.max(RESUME_FLOOR_MS, left); } let toasts: Toast[] = []; let nextId = 1; const listeners = new Set<() => void>(); function emit(): void { for (const l of listeners) l(); } /** Shows a toast and returns its id. */ export function showToast( message: string, tone: ToastTone = "info", duration: number = toastDuration(tone), ): number { const id = nextId++; toasts = [...toasts, { id, message, tone, duration }]; emit(); return id; } /** Removes a toast; an id that is gone already does nothing. */ export function dismissToast(id: number): void { if (!toasts.some((t) => t.id === id)) return; toasts = toasts.filter((t) => t.id !== id); emit(); } /** The toasts on screen, oldest first. */ export function currentToasts(): readonly Toast[] { return toasts; } /** Calls `fn` on every change; returns the function that stops it. */ export function subscribeToasts(fn: () => void): () => void { listeners.add(fn); return () => { listeners.delete(fn); }; }