// DOM and formatting helpers. // // Everything here builds nodes and sets textContent rather than assembling // HTML strings. A stream title, a log line and an error message all come from // outside, and node building makes it impossible for them to become markup. /** * el("div.card", {title: "x"}, child, ...) -> HTMLElement * The tag accepts a CSS-like shorthand: "span.pill.ok" or "#id.cls". */ export function el(spec, attrs, ...children) { let tag = "div"; const classes = []; let id = ""; const m = String(spec).match(/^([a-zA-Z][a-zA-Z0-9-]*)?((?:[.#][^.#]+)*)$/); if (m) { if (m[1]) tag = m[1]; for (const part of (m[2] || "").match(/[.#][^.#]+/g) || []) { if (part[0] === ".") classes.push(part.slice(1)); else id = part.slice(1); } } const node = document.createElement(tag); if (classes.length) node.className = classes.join(" "); if (id) node.id = id; if (attrs && (typeof attrs !== "object" || attrs instanceof Node || Array.isArray(attrs))) { children.unshift(attrs); attrs = null; } for (const [k, v] of Object.entries(attrs || {})) { if (v === null || v === undefined || v === false) continue; if (k === "class") node.className = v; else if (k === "text") node.textContent = v; else if (k === "html") throw new Error("el(): raw html is not allowed"); else if (k === "dataset") Object.assign(node.dataset, v); else if (k === "style" && typeof v === "object") Object.assign(node.style, v); else if (k.startsWith("on") && typeof v === "function") node.addEventListener(k.slice(2), v); else if (v === true) node.setAttribute(k, ""); else node.setAttribute(k, v); } append(node, children); return node; } export function append(node, children) { for (const c of children.flat(4)) { if (c === null || c === undefined || c === false || c === "") continue; node.append(c instanceof Node ? c : document.createTextNode(String(c))); } return node; } export function clear(node) { while (node.firstChild) node.removeChild(node.firstChild); return node; } export function $(sel, root = document) { return root.querySelector(sel); } export function $$(sel, root = document) { return Array.from(root.querySelectorAll(sel)); } /** pill("ok") -> a status chip. */ export function pill(text, extraClass) { const cls = String(text || "unknown").toLowerCase().replace(/[^a-z0-9]+/g, "-"); return el(`span.pill.${cls}${extraClass ? "." + extraClass : ""}`, { text: text || "unknown" }); } // ---------- formatting ---------- export function fmtSeconds(s) { s = Math.max(0, Math.round(Number(s) || 0)); if (s < 60) return `${s}s`; const m = Math.floor(s / 60); if (m < 60) return `${m}m ${s % 60}s`; const h = Math.floor(m / 60); if (h < 24) return `${h}h ${m % 60}m`; return `${Math.floor(h / 24)}d ${h % 24}h`; } export function fmtAge(s) { if (s === null || s === undefined || s === 0) return "—"; const n = Number(s); if (!isFinite(n)) return "—"; return n < 10 ? `${n.toFixed(1)}s` : `${Math.round(n)}s`; } export function fmtBitrate(mbps) { const n = Number(mbps) || 0; if (n <= 0) return "—"; return n < 10 ? `${n.toFixed(2)} Mb/s` : `${n.toFixed(1)} Mb/s`; } export function fmtTime(iso) { if (!iso) return "—"; const d = new Date(iso); if (isNaN(d)) return "—"; return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }); } export function fmtDateTime(iso) { if (!iso) return "—"; const d = new Date(iso); if (isNaN(d)) return "—"; return d.toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }); } /** fmtRelative("2026-01-01T...") -> "in 4m" / "6m ago" */ export function fmtRelative(iso) { if (!iso) return "—"; const d = new Date(iso); if (isNaN(d)) return "—"; const diff = d.getTime() - Date.now(); const abs = Math.abs(diff); const mins = Math.round(abs / 60000); let label; if (abs < 45000) label = "now"; else if (mins < 60) label = `${mins}m`; else if (mins < 60 * 24) label = `${Math.round(mins / 60)}h`; else label = `${Math.round(mins / 1440)}d`; if (label === "now") return "now"; return diff > 0 ? `in ${label}` : `${label} ago`; } export function absURL(path) { if (!path) return ""; try { return new URL(path, location.origin).href; } catch { return path; } } // ---------- interaction ---------- const TOAST_MAX = 3; export function toast(msg, isError) { const stack = $("#toast-stack"); if (!stack) return; const node = el(`div.toast${isError ? ".err" : ""}`, { role: isError ? "alert" : "status", text: String(msg), }); stack.append(node); while (stack.children.length > TOAST_MAX) { stack.firstElementChild.remove(); } const ms = isError ? 5200 : 2400; setTimeout(() => { node.classList.add("out"); setTimeout(() => node.remove(), 200); }, ms); } /** Mark a button busy for the duration of an async fn. */ export async function withBusy(btn, fn) { if (!btn) return fn(); const prev = btn.getAttribute("aria-busy") === "true"; if (prev) return; btn.setAttribute("aria-busy", "true"); btn.disabled = true; try { return await fn(); } finally { btn.removeAttribute("aria-busy"); btn.disabled = false; } } /** Flip a copy button label to "Copied" briefly; still toasts as fallback. */ export function markCopied(btn, ms = 1200) { if (!btn) return; const prev = btn.dataset.prevLabel || btn.textContent; btn.dataset.prevLabel = prev; btn.textContent = "Copied"; btn.classList.add("copied"); clearTimeout(Number(btn.dataset.copyTimer || 0)); btn.dataset.copyTimer = String(setTimeout(() => { btn.textContent = btn.dataset.prevLabel || "Copy"; btn.classList.remove("copied"); }, ms)); } export async function copyText(text, label = "link", btn) { if (!text) return; const ok = async () => { if (btn) markCopied(btn); else toast(`Copied ${label}`); }; try { await navigator.clipboard.writeText(text); await ok(); return; } catch { // Clipboard API needs a secure context; plain HTTP behind a proxy is a // normal deployment, so fall back rather than failing. } const ta = el("textarea", { style: { position: "fixed", left: "-9999px" } }); ta.value = text; document.body.append(ta); ta.select(); try { document.execCommand("copy"); await ok(); } catch { toast("Could not copy — select the text instead", true); } ta.remove(); } /** Open a modal built from nodes. Returns a close function. */ export function openModal(...children) { const dlg = $("#modal"); const body = $("#modal-body"); // Always rebuild body here. Do not clear on the dialog "close" event: callers // often close() then immediately openModal() again (e.g. create API key → // show secret), and an async close handler would wipe the new content. clear(body); append(body, children); const close = () => { if (dlg.open) dlg.close(); }; if (!dlg.open) dlg.showModal(); return close; } /** A yes/no dialog that resolves to a boolean. */ export function confirmDialog(title, detail, confirmLabel = "Confirm", danger = true) { return new Promise((resolve) => { let settled = false; const done = (v) => { if (settled) return; settled = true; close(); resolve(v); }; const close = openModal( el("h2", { text: title }), detail ? el("p.hint", { text: detail }) : null, el("div.row.end", { style: { marginTop: "16px" } }, el("button.ghost", { text: "Cancel", onclick: () => done(false) }), el(danger ? "button.danger" : "button", { text: confirmLabel, onclick: () => done(true) }), ), ); $("#modal").addEventListener("close", () => done(false), { once: true }); }); } /** Debounce for filter inputs. */ export function debounce(fn, ms = 180) { let t = null; return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); }; } // ---------- sparkline ---------- /** * sparkline(points, pick) -> inline SVG. * Drawn by hand rather than with a chart library: one series, no axes, and no * reason to ship a dependency for it. */ export function sparkline(points, pick, opts = {}) { const w = opts.width || 240; const h = opts.height || 44; const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svg.setAttribute("class", "spark"); svg.setAttribute("viewBox", `0 0 ${w} ${h}`); svg.setAttribute("preserveAspectRatio", "none"); svg.setAttribute("role", "img"); const vals = (points || []).map(pick).map((v) => (isFinite(v) ? Number(v) : 0)); if (vals.length < 2) { svg.setAttribute("aria-label", "not enough data yet"); const t = document.createElementNS(svg.namespaceURI, "text"); t.setAttribute("x", 4); t.setAttribute("y", h / 2 + 4); t.setAttribute("fill", "currentColor"); t.setAttribute("font-size", "10"); t.setAttribute("opacity", ".55"); t.textContent = "collecting…"; svg.append(t); return svg; } const max = Math.max(...vals, opts.min || 0.0001); const stepX = w / (vals.length - 1); const y = (v) => h - 2 - (v / max) * (h - 6); const pts = vals.map((v, i) => `${(i * stepX).toFixed(2)},${y(v).toFixed(2)}`); const area = document.createElementNS(svg.namespaceURI, "path"); area.setAttribute("class", "area"); area.setAttribute("d", `M0,${h} L${pts.join(" L")} L${w},${h} Z`); const line = document.createElementNS(svg.namespaceURI, "polyline"); line.setAttribute("class", "line"); line.setAttribute("points", pts.join(" ")); svg.append(area, line); svg.setAttribute("aria-label", `${opts.label || "series"}, latest ${vals[vals.length - 1]}, peak ${max}`); return svg; } // ---------- keyed list rendering ---------- /** * Reconcile a list of rows into a parent by key. * * The old dashboard rebuilt the whole table with innerHTML every five * seconds, which threw away focus, scroll position, text selection and any * open menu. This updates in place instead: existing rows are patched, new * ones inserted, departed ones removed. */ export function reconcile(parent, items, keyOf, create, update) { const existing = new Map(); for (const node of Array.from(parent.children)) { const k = node.dataset.key; if (k !== undefined) existing.set(k, node); else node.remove(); } let prev = null; for (const item of items) { const key = String(keyOf(item)); let node = existing.get(key); if (node) { existing.delete(key); update(node, item); } else { node = create(item); node.dataset.key = key; } // Place it after the previous row, moving it only when out of order. const want = prev ? prev.nextSibling : parent.firstChild; if (node !== want) parent.insertBefore(node, want); prev = node; } for (const node of existing.values()) node.remove(); } /** Set textContent only when it differs, so selections survive updates. */ export function setText(node, text) { const s = text === null || text === undefined ? "" : String(text); if (node.textContent !== s) node.textContent = s; }