| 1 | const DEFAULT_DURATION_MS = 3500; |
| 2 | const LEAVE_MS = 280; |
| 3 | |
| 4 | /** |
| 5 | * Temporary top-of-screen toast messages (play HUD). |
| 6 | */ |
| 7 | export function initToasts () |
| 8 | { |
| 9 | const root = document.getElementById("toast-stack"); |
| 10 | if (!root) |
| 11 | { |
| 12 | return { |
| 13 | show () |
| 14 | {} |
| 15 | }; |
| 16 | } |
| 17 | |
| 18 | function show (message, options = {}) |
| 19 | { |
| 20 | const text = String(message ?? "").trim(); |
| 21 | if (!text) |
| 22 | { return; } |
| 23 | const durationMs = Math.max(800, options.durationMs ?? DEFAULT_DURATION_MS); |
| 24 | const onClick = typeof options.onClick === "function" ? options.onClick : null; |
| 25 | const el = document.createElement("div"); |
| 26 | el.className = "toast"; |
| 27 | el.setAttribute("role", "status"); |
| 28 | el.textContent = text; |
| 29 | let dismissed = false; |
| 30 | const dismiss = () => |
| 31 | { |
| 32 | if (dismissed) |
| 33 | { return; } |
| 34 | dismissed = true; |
| 35 | el.classList.remove("toast-visible"); |
| 36 | el.classList.add("toast-leaving"); |
| 37 | window.setTimeout(() => el.remove(), LEAVE_MS); |
| 38 | }; |
| 39 | if (onClick) |
| 40 | { |
| 41 | el.classList.add("toast-clickable"); |
| 42 | el.style.cursor = "pointer"; |
| 43 | el.addEventListener("click", () => |
| 44 | { |
| 45 | onClick(); |
| 46 | dismiss(); |
| 47 | }); |
| 48 | } |
| 49 | root.appendChild(el); |
| 50 | requestAnimationFrame(() => |
| 51 | { |
| 52 | el.classList.add("toast-visible"); |
| 53 | }); |
| 54 | window.setTimeout(dismiss, durationMs); |
| 55 | } |
| 56 | |
| 57 | return { show }; |
| 58 | } |