Files
2026-09-30 15:44:32 +02:00

228 lines
8.5 KiB
JavaScript

/* Toasts: the one place on screen for messages to the user.
*
* Adapted from health's `webapp/static/toasts.js`, which is where the
* behaviour was worked out. Two sources, one look:
*
* server notices from the log (app/notices.py), delivered by live.js as
* `app:notice`. A problem (warning, error) interrupts the first
* time; a repeat within five minutes only bumps the count of a
* toast already on screen, since it is already in the log. An
* outcome (good, info) is news every time. On page load, notices
* raised since the last visit are shown too, so one raised while
* no tab was open is not lost.
* pages `toast.error(text)`, `toast.good(text)`, ... for the outcome of
* something the user just did. These are not logged: the user is
* looking at the result.
*
* Errors stay until dismissed; everything else fades. Progress of work in
* flight is not a toast -- that is what the job's progress bar is for.
*/
(function () {
"use strict";
const FADE_MS = { info: 5000, good: 5000, warning: 10000, error: 0 };
const SEEN_KEY = "app.notices.seen";
const MAX_ON_LOAD = 3;
let stack = null;
const byCode = new Map(); // "code|key" -> toast element, for server notices
/* Escaping, once for the page. This file needs one and loads first, so it
is the one that exports it: every other script here builds a little HTML
out of server strings, and a notice's detail is raw error text that has
already been through somebody else's parser once. Two copies of an
escaper is one of them being the one that gets fixed. */
function esc(s) {
return String(s === null || s === undefined ? "" : s).replace(/[&<>"']/g, (c) => ({
"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
})[c]);
}
window.esc = esc;
/* The stack is a manual popover, so it lives in the browser's top layer and
shows above a modal <dialog>. The top layer is ordered by opening, so it
is reopened on every new toast to stay above whatever opened since. */
const POPOVER = typeof HTMLElement.prototype.showPopover === "function";
function container() {
if (!stack) {
stack = document.createElement("div");
stack.className = "toasts";
stack.setAttribute("aria-live", "polite");
if (POPOVER) stack.setAttribute("popover", "manual");
document.body.appendChild(stack);
}
return stack;
}
/* A modal dialog makes the rest of the document inert, a popover opened
after it included: the toast would be visible but its buttons dead. So
while a modal is open the stack lives inside it, and goes back to the body
when the modal closes. */
function raise() {
const modal = document.querySelector("dialog:modal");
const home = modal || document.body;
if (stack.parentElement !== home) {
home.appendChild(stack);
if (modal) {
modal.addEventListener("close", () => {
if (stack.parentElement !== modal) return;
document.body.appendChild(stack);
if (stack.children.length) reopen();
}, { once: true });
}
}
reopen();
}
function reopen() {
if (!POPOVER) return;
if (stack.matches(":popover-open")) stack.hidePopover();
stack.showPopover();
}
/* opts: level (info|good|warning|error), text, detail, fix, count, sticky,
action {label, run}, link {label, href}, id (dedupe key) */
function show(opts) {
const o = typeof opts === "string" ? { text: opts } : opts;
const level = o.level || "info";
if (o.id && byCode.has(o.id)) {
const existing = byCode.get(o.id);
if (existing.isConnected) {
update(existing, o);
return existing;
}
byCode.delete(o.id);
}
const t = document.createElement("div");
t.className = `toast ${level}`;
t.setAttribute("role", level === "error" ? "alert" : "status");
t.innerHTML = `
<div class="toast-body">
<div class="toast-text"></div>
${o.fix ? `<div class="toast-fix small">${esc(o.fix)}</div>` : ""}
${o.detail ? `<details class="toast-detail small"><summary>details</summary>
<pre>${esc(o.detail)}</pre></details>` : ""}
<div class="toast-actions">
${o.action ? `<button type="button" data-act="action">${esc(o.action.label)}</button>` : ""}
${o.link ? `<a href="${esc(o.link.href)}">${esc(o.link.label)}</a>` : ""}
</div>
</div>
<button type="button" class="toast-close" data-act="close" aria-label="dismiss">x</button>`;
update(t, o);
t.addEventListener("click", (e) => {
const act = e.target.dataset && e.target.dataset.act;
if (act === "close") dismiss(t);
else if (act === "action" && o.action) {
o.action.run();
dismiss(t);
}
});
container().appendChild(t);
raise();
if (o.id) byCode.set(o.id, t);
const fade = o.sticky ? 0 : FADE_MS[level];
if (fade) {
let timer = setTimeout(() => dismiss(t), fade);
// Reading it keeps it: a toast does not fade from under the cursor.
t.addEventListener("mouseenter", () => clearTimeout(timer));
t.addEventListener("mouseleave", () => { timer = setTimeout(() => dismiss(t), fade); });
}
return t;
}
function update(t, o) {
const count = o.count > 1 ? ` <span class="toast-count">x${o.count}</span>` : "";
t.querySelector(".toast-text").innerHTML = esc(o.text) + count;
}
function dismiss(t) {
t.classList.add("out");
setTimeout(() => {
t.remove();
if (POPOVER && stack && !stack.children.length && stack.matches(":popover-open")) {
stack.hidePopover();
}
}, 180);
}
const toast = {
show,
info: (text, o) => show({ ...o, level: "info", text }),
good: (text, o) => show({ ...o, level: "good", text }),
warning: (text, o) => show({ ...o, level: "warning", text }),
error: (text, o) => show({ ...o, level: "error", text }),
};
window.toast = toast;
/* -- server notices ---------------------------------------------------- */
function seen() {
try { return localStorage.getItem(SEEN_KEY) || ""; } catch (e) { return ""; }
}
function markSeen(at) {
try { if (at > seen()) localStorage.setItem(SEEN_KEY, at); } catch (e) { /* convenience */ }
}
const PROBLEM = new Set(["warning", "error"]);
function fromNotice(n) {
const t = {
id: `${n.code}|${n.key || ""}`,
level: n.level,
text: n.text,
fix: n.fix,
detail: n.detail,
link: { label: "all messages", href: "/settings/sources#messages" },
};
if (PROBLEM.has(n.level)) t.count = n.count;
if (n.level === "good") t.action = { label: "reload", run: () => location.reload() };
return t;
}
/* When this page last showed each problem. A repeat within QUIET_MS only
bumps a count, so a burst -- a job retried in a loop -- is one toast; a
repeat after that, such as a retry the user just pressed, is shown again. */
const QUIET_MS = 5 * 60 * 1000;
const shownAt = new Map();
function onNotice(n) {
const id = `${n.code}|${n.key || ""}`;
const onScreen = byCode.get(id);
markSeen(n.last_at || "");
if (PROBLEM.has(n.level) && n.count > 1 && !(onScreen && onScreen.isConnected)
&& Date.now() - (shownAt.get(id) || 0) < QUIET_MS) return;
shownAt.set(id, Date.now());
show(fromNotice(n));
}
async function missed() {
// A browser that has never been here shows the last day's messages, not
// the whole fortnight the log keeps.
const since = seen() || new Date(Date.now() - 86400000).toISOString();
let list;
try {
const r = await fetch("/api/notices", { headers: { Accept: "application/json" } });
if (!r.ok) return;
list = await r.json();
} catch (e) { return; }
const fresh = list.filter((n) => n.last_at > since);
fresh.slice(0, MAX_ON_LOAD).forEach((n) => show(fromNotice(n)));
if (fresh.length > MAX_ON_LOAD) {
toast.info(`${fresh.length - MAX_ON_LOAD} more messages since your last visit.`,
{ link: { label: "all messages", href: "/settings/sources#messages" } });
}
if (fresh.length) markSeen(fresh[0].last_at);
}
document.addEventListener("app:notice", (e) => onNotice(e.detail));
document.addEventListener("DOMContentLoaded", () => {
// Not on Sources: the messages table is right there, in full, already.
// `/messages` itself only redirects now, so the browser never lands there.
if (location.pathname !== "/login" && location.pathname !== "/settings/sources") missed();
});
})();