function build(node, attrs, children) { for (const [key, value] of Object.entries(attrs)) { if (key === "on") { for (const [name, handler] of Object.entries(value)) { node.addEventListener(name, handler); } } else if (value !== null && value !== undefined && value !== false) { node.setAttribute(key, value === true ? "" : String(value)); } } for (const child of children.flat(Infinity)) { if (child !== null && child !== undefined && child !== false) { node.append(child instanceof Node ? child : String(child)); } } return node; } const h = (tag, attrs, ...children) => build(document.createElement(tag), attrs, children); const s = (tag, attrs, ...children) => build(document.createElementNS(NS, tag), attrs, children); const icon = (name, cls) => s("svg", {class: cls ? `bi ${cls}` : "bi", "aria-hidden": "true", focusable: "false"}, s("use", {href: `#${name}`})); const caret = () => icon("bi-caret-down-fill", "caret"); const named = (label, hint) => ({title: hint || label, "aria-label": label}); const iconBtn = (name, label, cls, run, hint) => h("button", {type: "button", class: `${cls} icon-only`, ...named(label, hint), on: {click: run}}, icon(name)); const boxHead = (label, cls, ...children) => h("div", {class: cls ? `box-head ${cls}` : "box-head", role: children.flat(Infinity).some((child) => child instanceof Node && child.getAttribute("role") === "toolbar") ? "group" : "toolbar", "aria-label": label}, ...children); const dash = (value) => (value === "" || value === "-" || value === null || value === undefined ? "–" : value); const targetsOf = (row) => (row.to.length ? row.to.join(", ") : "all"); const fixed = (value) => value.toFixed(1); const short = (text) => (text.length > 80 ? `${text.slice(0, 80)}…` : text); const btn = (label, cls, run) => h("button", {type: "button", class: cls, on: {click: run}}, label); const nowSeconds = () => Date.now() / 1000; const PICKED = "\n"; const OTHER_LIMIT = 1000; const shownPick = (label) => label.split(PICKED).join(", "); function ago(ts) { const diff = ts - nowSeconds(); const size = Math.abs(diff); if (size < 45) { return "just now"; } if (size < 3600) { return relative.format(Math.round(diff / 60), "minute"); } if (size < DAY) { return relative.format(Math.round(diff / 3600), "hour"); } return relative.format(Math.round(diff / DAY), "day"); } const stampOf = (ts) => new Date(ts * 1000); const when = (ts) => h("time", {"data-ts": ts, datetime: stampOf(ts).toISOString(), title: absolute.format(stampOf(ts))}, ago(ts)); const pill = (text, tone) => h("span", {class: "pill", "data-tone": tone}, text); const status = (value) => pill((STATUS[value] || [value])[0], (STATUS[value] || [value, "neutral"])[1]); const klass = (value) => pill(CLASSES[value] || value, PILLS[value] || "neutral"); const counter = (value) => h("span", {class: "count"}, String(value)); const meta = (pairs) => h("dl", {class: "meta"}, pairs.map(([label, value, title]) => h("div", {}, h("dt", {}, label), h("dd", {}, h("code", {title: title ? revealed(title) : null}, revealed(dash(value))))))); const emptyState = (title, text) => h("div", {class: "empty"}, h("div", {class: "empty-mark", "aria-hidden": "true"}), h("h2", {}, title), h("p", {}, text)); const live = () => ui.asOf === null; const alarmRows = () => state.radio.filter((row) => (row.class === "mayday" || row.class === "pan-pan") && row.ts >= state.alarm_since).reverse(); const keyOf = (item) => `${item.kind}:${item.id}`; const openInbox = () => state.inbox.filter((item) => !item.answered); const visibleInbox = () => openInbox().filter((item) => ui.snoozed || !item.until); const waitingCount = () => openInbox().filter((item) => !item.until).length; const isGreen = (item) => item.green && !item.held && !item.until && item.kind !== "operator"; const selectable = (item) => !item.held && item.kind !== "rule" && !(item.kind === "review" && item.gate !== "pass") && !(item.kind === "operator" && !item.runnable) && !(item.kind === "decision" && !item.recommended); const entryOf = (item, verb, label) => ({kind: item.kind, id: item.id, verb, label, sha256: item.sha256 || ""}); function tick() { for (const node of document.querySelectorAll("time[data-ts]")) { node.textContent = ago(Number(node.dataset.ts)); } const updated = document.getElementById("updated"); updated.classList.toggle("offline", ui.offline); updated.textContent = `${ui.offline ? "No connection · " : ""}${live() ? "Live" : "As of"} ${absolute.format(stampOf(live() ? state.now : state.until))}`; pollRates(); } const faceParts = (key) => Faces.of(key).parts.map(([tag, attrs]) => s(tag, attrs)); const speaker = () => { const now = speech.current || speech.item; return now && now.who ? now : null; }; const talking = (key) => Boolean(speaker() && speaker().who === key); const face = (who, big) => { const key = agentKey(who); return h("span", {class: `avatar${big ? " big" : ""}${talking(key) ? " speaking" : ""}`, "data-face": key, "aria-hidden": "true"}, s("svg", {class: "face-art", viewBox: `0 0 ${Faces.SIZE} ${Faces.SIZE}`, focusable: "false"}, faceParts(key))); }; const presenceOf = (key) => { const value = (state.presence || {})[key]; return Object.hasOwn(PRESENCE, value) && !look.hidden.has(value) ? value : null; }; const presenceMark = (key, labelled) => { const value = presenceOf(key); return value ? h("span", {class: value === "working" ? "presence is-working" : "presence", "data-state": value, "data-tone": PRESENCE[value][2], role: "img", ...named(PRESENCE[value][0])}, icon(PRESENCE[value][1], "glyph"), labelled ? PRESENCE[value][0] : null) : null; }; const presenceGlyph = (key, x, y, size) => { const value = presenceOf(key); return value ? s("g", {class: "presence", "data-state": value, "data-tone": PRESENCE[value][2], transform: `translate(${fixed(x)} ${fixed(y)})`}, s("title", {}, PRESENCE[value][0]), s("rect", {class: "presence-dot", x: fixed(-size * 0.65), y: fixed(-size * 0.65), width: fixed(size * 1.3), height: fixed(size * 1.3), rx: fixed(size * 0.65)}), s("g", {class: "glyph"}, s("use", {href: `#${PRESENCE[value][1]}`, x: fixed(-size / 2), y: fixed(-size / 2), width: fixed(size), height: fixed(size)}))) : null; }; const isAgent = (name) => Boolean(name) && name !== "-" && name !== "all" && name !== HUMAN; const person = (name) => (isAgent(name) ? h("button", {type: "button", class: "linkish", title: revealed(`Open ${name}`), on: {click: () => openAgent(name)}}, revealed(name)) : dash(name)); const openFrom = (name) => (event) => { event.stopPropagation(); const self = event.currentTarget; openAgent(name, () => (self.isConnected ? self : null)); }; const agentLink = (name, big, cls) => (isAgent(name) ? h("button", {type: "button", class: "linkish agent-link", title: revealed(`Open ${name}`), on: {click: openFrom(name)}}, face(name, big), h("span", {class: cls || "agent-name"}, revealed(people()[name] ? nameOf(name) : name))) : h("span", {class: "agent-link"}, face(name || "-", big), h("span", {class: cls || "agent-name"}, dash(name)))); const agentFace = (name, big) => (isAgent(name) ? h("button", {type: "button", class: "agent-face", ...named(revealed(`Open ${people()[name] ? nameOf(name) : name}`)), on: {click: openFrom(name)}}, face(name, big)) : face(name || "-", big)); const people = () => state.people || {}; const labelOf = (key) => (people()[key] || {name: String(key).replace(/^name:/, "")}).name; const nameOf = (key) => (people()[key] || {now: String(key).replace(/^name:/, "")}).now; const agentKey = (who) => (people()[who] ? who : (Object.entries(people()).find(([, entry]) => entry.now === who || entry.names.includes(who)) || [who])[0]); const chairKey = () => (state.graph.nodes.find((node) => node.kind === "chair") || {id: HUMAN}).id; const readLabel = (reader) => Receipts.label(reader, (ts) => absolute.format(stampOf(ts))); const readerRow = (row) => { const {shown, hidden} = Receipts.strip(row); const avatar = (reader) => { const who = people()[reader.session] ? reader.session : reader.name; return h("button", {type: "button", class: "reader", "data-session": reader.session, "data-acked": String(reader.acked), ...named(readLabel(reader)), on: {click: openFrom(who)}}, face(who, false), reader.acked ? h("span", {class: "ack", "aria-hidden": "true"}, icon("bi-check2-all")) : null); }; const more = hidden.length ? h("span", {class: "readers-more", role: "img", ...named(`${hidden.length} more readers`, [...shown, ...hidden].map(readLabel).join("\n"))}, `+${hidden.length}`) : null; return shown.length ? h("div", {class: "readers", role: "group", "aria-label": `Read by ${shown.length + hidden.length}`}, shown.map(avatar), more) : null; }; const stamp = (life) => [life.born ? `🐣 ${life.born}` : "", life.died ? `🪦 ${life.died}` : ""].filter(Boolean).join(" · "); /** * @returns {SVGElement} a fresh hourglass face; a newly inserted face starts its flip and its sand from the top, so * matchCycle() swaps it in after every fetch and undoToast() puts one in each countdown. */ function glassFace() { return s("svg", {class: "match-glass-face", viewBox: "0 0 24 32", "aria-hidden": "true", focusable: "false"}, s("path", {class: "match-glass-frame", d: "M4 2h16M4 30h16M6 3c0 7 5 9 5 13s-5 6-5 13M18 3c0 7-5 9-5 13s5 6 5 13"}), s("path", {class: "match-glass-top", d: "M8 7h8l-4 7z"}), s("path", {class: "match-glass-bottom", d: "M7.5 28h9c-1.5-3.5-3.5-4.5-4.5-4.5s-3 1-4.5 4.5z"}), [0, 1, 2].map((grain) => s("circle", {class: "match-grain", cx: "12", cy: "15", r: "0.8", "data-grain": String(grain)}))); } const VANISH_MS = 180; const VANISH_SLACK = 150; const VANISH_EDGES = ["Top", "Bottom"]; const VANISH_SIDES = ["Left", "Right"]; /** * @param {Element} el an element in the page. * @returns {Keyframe[]} its fade to opacity 0 from the opacity it shows now; an element in the flow also gives up its * room: its height (its width when it is inline) with its margins and paddings along that axis. */ function vanishFrames(el) { const look = window.getComputedStyle(el); const from = {opacity: look.opacity}; const to = {opacity: 0}; if (look.position === "absolute" || look.position === "fixed" || look.display.startsWith("table")) { return [from, to]; } const inline = look.display.startsWith("inline"); const [size, edges] = inline ? ["width", VANISH_SIDES] : ["height", VANISH_EDGES]; from[size] = `${el.getBoundingClientRect()[size]}px`; to[size] = "0px"; for (const edge of edges) { for (const box of ["margin", "padding"]) { from[`${box}${edge}`] = look[`${box}${edge}`]; to[`${box}${edge}`] = "0px"; } } return [from, to]; } /** * @param {Element|null} el the element to take out of the page. * @param {Function} [then] runs once el has left the DOM. * Fades el and collapses its room in VANISH_MS before it leaves the DOM; at once under prefers-reduced-motion and for * a detached or unrendered el. A second call on an element already leaving does nothing. */ function vanish(el, then) { if (!el || (el.dataset && el.dataset.vanishing)) { return; } let gone = false; const done = () => { if (!gone) { gone = true; el.remove(); if (then) { then(); } } }; if (!el.isConnected || typeof el.animate !== "function" || !el.getClientRects().length || calm.matches) { done(); return; } el.dataset.vanishing = "true"; el.style.overflow = "hidden"; el.style.pointerEvents = "none"; el.animate(vanishFrames(el), {duration: VANISH_MS, easing: "ease-in", fill: "forwards"}).finished.then(done, done); window.setTimeout(done, VANISH_MS + VANISH_SLACK); } const SWAP_KEYS = ["data-key", "data-item", "data-card", "data-task", "data-job", "data-ref"]; const SWAP_KEYED = SWAP_KEYS.map((name) => `[${name}]`).join(", "); const swapsDue = new WeakMap(); /** * @param {Array} nodes elements and text. * @returns {Set} the key of every keyed element in nodes and below them, as "attribute=value" of the first * SWAP_KEYS attribute the element holds. */ function swapKeys(nodes) { const keyed = nodes.filter((node) => node instanceof Element).flatMap((node) => [node, ...node.querySelectorAll(SWAP_KEYED)]).filter((node) => node.matches(SWAP_KEYED)); return new Set(keyed.map((node) => { const name = SWAP_KEYS.find((key) => node.hasAttribute(key)); return `${name}=${node.getAttribute(name)}`; })); } /** * @param {Element} box a container about to get new children. * @param {Array} nodes the new children. * @returns {boolean} whether a keyed element box shows now is missing from nodes, so it leaves the page; false * without View Transitions, for a detached or unrendered box and while a field has the focus, whose typing a * transition would freeze. */ function swapLeaves(box, nodes) { if (!document.startViewTransition || !box.isConnected || !box.getClientRects().length) { return false; } const field = document.activeElement; if (field && field.matches("input, textarea, select, [contenteditable]")) { return false; } const next = swapKeys(nodes); return [...swapKeys([...box.children])].some((key) => !next.has(key)); } /** * @param {Element} box a visible container whose children a re-render replaces. * @param {Array} nodes its new children. * @param {Function} [around] called as around(box, swap) in place of swap(), for a keeper such as keepTyping() or for * work that needs nodes in the page. * @returns {Promise} settles once box holds nodes. When a keyed child leaves, the swap runs inside fadeTransition() * scoped to box, so it fades out while the rest of the page keeps taking clicks; else at once. Only the newest nodes given for box land, so a late transition never undoes a * newer swap. */ function fadeSwap(box, nodes, around) { swapsDue.set(box, nodes); const swap = () => { if (swapsDue.get(box) === nodes) { box.replaceChildren(...nodes); } }; const run = around ? () => around(box, swap) : swap; if (!swapLeaves(box, nodes)) { run(); return Promise.resolve(); } return fadeTransition(run, box); } function toast(title, lines, good) { const box = h("div", {class: `toast${good ? "" : " bad"}`, role: "status", title: "Close"}, h("strong", {}, title), lines.length ? h("pre", {}, lines.join("\n")) : null); box.addEventListener("click", () => vanish(box)); document.getElementById("toasts").append(box); window.setTimeout(() => vanish(box), good ? 9000 : 20000); return box; } function runLines(data) { return (data.runs || []).flatMap((run) => [`$ ${run.command} → ${run.code}`, run.stdout.trim(), run.stderr.trim()].filter(Boolean)); } function relabel(button, name, label, hint) { button.replaceChildren(icon(name)); button.setAttribute("aria-label", label); button.title = hint || label; } function copyButton(text) { const button = iconBtn("bi-clipboard", "Copy", "btn small ghost", null, "Copy: to the clipboard"); button.addEventListener("click", async () => { try { await navigator.clipboard.writeText(text); relabel(button, "bi-clipboard-check", "Copied"); } catch { relabel(button, "bi-x-circle", "Not possible"); } window.setTimeout(() => relabel(button, "bi-clipboard", "Copy"), 1600); }); return button; } const PATH_ACTIONS = "click opens in VS Code, right-click copies the path"; /** * @param {string} path a path on the operator's machine. * @returns {string} the link that opens it in VS Code: vscode://file plus the absolute path, every segment * URI-encoded and the slashes kept; "" for a relative or empty path. */ function vscodeHref(path) { return typeof path === "string" && path.startsWith("/") ? `vscode://file${path.split("/").map(encodeURIComponent).join("/")}` : ""; } /** * @param {string} root an absolute folder, such as a card's worktree. * @param {string} path a path relative to root. * @returns {string} path below root; "" without a root or a path. */ const pathUnder = (root, path) => (root && path ? `${root.replace(/\/+$/, "")}/${path}` : ""); /** * @param {string} path the full path the link names. * @param {Object} attrs the link's attributes besides href and its right-click handler. * @param {...*} children what the link shows. * @returns {HTMLElement|null} a link that opens path in VS Code, whose right-click copies path with ctxCopy() and * opens no context menu; null for a relative or empty path. */ function pathLink(path, attrs, ...children) { const href = vscodeHref(path); return href ? h("a", {...attrs, href, on: {contextmenu: (event) => { event.preventDefault(); ctxCopy(path); }}}, ...children) : null; } /** * @param {string} root the folder the diff was taken in: a card's worktree or directory. * @param {string} path the file's path relative to root. * @param {string} shown the text the head shows for the file. * @returns {HTMLElement} the file head's code.path, inside a pathLink() to root/path when root is absolute. */ function pathCode(root, path, shown) { const full = pathUnder(root, path); const code = h("code", {class: "path"}, shown); return pathLink(full, {class: "path-link", title: `${revealed(full)}: ${PATH_ACTIONS}`}, code) || code; } const MENUS ="details.menu, details.radio-station, details.radio-notify, .ctx-menu"; const MENU_LINGER = 3000; const ACTIONS_IN_MENU = "button, a[href], [role='button']"; /** * @param {MouseEvent} event a click anywhere on the page. * The menu the click landed in stays open, read from the event path because a toggle chip may redraw itself away * before the click reaches the document; an action entry of a details.menu (a button without aria-pressed) closes it. */ function menuClick(event) { const path = event.composedPath().filter((node) => node instanceof Element); const menu = path.find((node) => node.matches(MENUS)) || null; const control = path.find((node) => node.matches(`${ACTIONS_IN_MENU}, summary, label, input, select, textarea`)); const action = Boolean(menu && menu.matches("details.menu") && control && control.matches(ACTIONS_IN_MENU) && !control.hasAttribute("aria-pressed")); closeMenus(action ? null : menu); } /** * @param {Event} event a toggle of any details element, caught on the way down. * An opened details.menu closes MENU_LINGER ms after a mouse or pen leaves it; coming back in time keeps it open. */ function menuLinger(event) { const menu = event.target; if (!(menu instanceof HTMLDetailsElement) || !menu.matches("details.menu") || menu.dataset.linger) { return; } menu.dataset.linger = "on"; let timer = 0; menu.addEventListener("pointerleave", (left) => { if (left.pointerType !== "touch" && menu.open) { window.clearTimeout(timer); timer = window.setTimeout(() => { menu.open = false; }, MENU_LINGER); } }); menu.addEventListener("pointerenter", () => window.clearTimeout(timer)); menu.addEventListener("toggle", () => { if (!menu.open) { window.clearTimeout(timer); } }); } /** * @param {Element|null} [keep] the menu a click landed in: it stays open, and so does every menu around it, such as * the Tasks Actions menu holding Request choices. */ function closeMenus(keep) { for (const menu of document.querySelectorAll(MENUS)) { if (menu.open && menu !== keep && !(keep && menu.contains(keep))) { const inside = menu.contains(document.activeElement); menu.open = false; if (inside) { menu.querySelector("summary").focus({preventScroll: true}); } } } ctxDismiss(keep); } function openSheet(title, body, wide) { const sheet = document.getElementById("sheet"); const shown = revealed(title); sheet.replaceChildren(h("div", {class: `sheet-box${wide ? " wide" : ""}`, role: "dialog", "aria-modal": "true", "aria-label": shown}, h("div", {class: "sheet-head"}, h("h2", {class: "panel-title"}, shown), h("span", {class: "spacer"}), iconBtn("bi-x-lg", "Close", "btn small ghost", closeSheet)), h("div", {class: "sheet-body"}, body))); sheet.hidden = false; } /** * @param {HTMLElement} overlay a fixed overlay such as #sheet or #palette. * Sets overlay hidden at once, so every check of its hidden flag sees it closed, while its boxes fade out through * vanish(); the closing class keeps it drawn without taking clicks until the last box has left. */ function fadeShut(overlay) { const shut = () => { if (!overlay.children.length) { overlay.classList.remove("closing"); } }; overlay.classList.add("closing"); overlay.hidden = true; [...overlay.children].forEach((box) => vanish(box, shut)); shut(); } function closeSheet() { fadeShut(document.getElementById("sheet")); reviewDom = null; ui.review = null; }