// sessions-web: progressive enhancement. The page works without this file; // with it, buttons answer in place (no reload) and the list keeps itself fresh. // // - Every POST form is sent with fetch() and `Accept: application/json`; the // server then answers {ok, message|error} instead of redirecting. // - The button and card show the change at once; the real state follows from // a background refresh, which re-fetches "/" and swaps #live and the // Repository options. Nothing from the server is inserted as HTML except // that same-origin page. // - The list refreshes every 15 s (every 3 s while something is starting or // stopping) and only while the tab is visible. (() => { "use strict"; const $ = (sel, root = document) => root.querySelector(sel); const BUSY_LABEL = { start: "Starting", stop: "Stopping", archive: "Archiving", unarchive: "Restoring", create: "Creating", "add-repo": "Checking", }; const SLOW = 15000, FAST = 3000; let inFlight = 0, timer = 0; // The no-JS flow lands on /?ok=… — drop it so a reload doesn't repeat it. if (location.search) history.replaceState(null, "", location.pathname); // ------------------------------------------------------------ toasts function dismiss(el, after) { setTimeout(() => { el.classList.add("out"); setTimeout(() => el.remove(), 300); }, after); } function toast(kind, text) { const el = document.createElement("div"); el.className = "toast " + kind; el.setAttribute("role", kind === "err" ? "alert" : "status"); el.textContent = text; $("#toasts").appendChild(el); dismiss(el, kind === "err" ? 9000 : 4500); } document.querySelectorAll("#toasts .toast").forEach((el) => dismiss(el, 6000)); // ------------------------------------------------------------ relative times function ago(iso) { const s = (Date.now() - Date.parse(iso)) / 1000; if (!isFinite(s)) return null; if (s < 60) return "just now"; const units = [["d", 86400], ["h", 3600], ["min", 60]]; for (const [u, n] of units) if (s >= n) return `${Math.floor(s / n)} ${u} ago`; return null; } function humanizeTimes(root) { root.querySelectorAll("time[datetime]").forEach((t) => { const rel = ago(t.dateTime); if (rel) { t.title = t.textContent; t.textContent = rel; } }); } // ------------------------------------------------------------ refresh function needsFastPoll() { return !!$('#live [data-state="activating"], #live [data-state="deactivating"], #live .card.ghost') || !!$('#live [data-state="active"]:not([data-linked])'); // waiting for the Remote Control link } function schedule() { clearTimeout(timer); if (!document.hidden) timer = setTimeout(refresh, needsFastPoll() ? FAST : SLOW); } async function refresh() { if (inFlight) return schedule(); // an action's own refresh follows it let res; try { res = await fetch("/", { headers: { Accept: "text/html" }, cache: "no-store", credentials: "same-origin" }); } catch { return schedule(); // offline, or the login expired (redirect to another origin) } if (!res.ok || inFlight) return schedule(); const doc = new DOMParser().parseFromString(await res.text(), "text/html"); const live = $("#live", doc); if (!live) return schedule(); swapLive(live); swapRepos($("#repo", doc)); schedule(); } function swapLive(fresh) { const current = $("#live"); const wasOpen = $("details.archive", current)?.open; const archive = $("details.archive", fresh); if (archive && wasOpen) archive.open = true; humanizeTimes(fresh); current.replaceWith(document.adoptNode(fresh)); } function swapRepos(freshSelect) { const select = $("#repo"); if (!select || !freshSelect) return; setRepoOptions([...freshSelect.options].map((o) => o.value)); } function setRepoOptions(names, pick) { const select = $("#repo"); const have = [...select.options].map((o) => o.value); if (have.join("\n") === names.join("\n") && !pick) return; const keep = pick || select.value; select.replaceChildren(...names.map((n) => new Option(n, n))); if (names.includes(keep)) select.value = keep; } // ------------------------------------------------------------ actions // Show the action as happening right away. Returns an undo for failures. function showPending(verb, form, button) { const undo = []; const label = button.textContent; button.disabled = true; button.classList.add("loading"); button.textContent = BUSY_LABEL[verb] || "Working"; undo.push(() => { button.disabled = false; button.classList.remove("loading"); button.textContent = label; }); const card = form.closest(".card"); if (card) { card.classList.add("pending"); card.querySelectorAll("button").forEach((b) => { b.disabled = true; }); const badge = $(".badge", card); const old = badge.cloneNode(true); const state = { start: "activating", stop: "deactivating", archive: "deactivating" }[verb]; if (state) { badge.className = "badge " + state; badge.lastChild.textContent = BUSY_LABEL[verb]; card.dataset.state = state; } if (verb === "archive" || verb === "unarchive") card.classList.add("leaving"); undo.push(() => { card.classList.remove("pending", "leaving"); badge.replaceWith(old); }); } if (verb === "create") { const ghost = document.createElement("article"); ghost.className = "card ghost"; ghost.innerHTML = '

' + 'Cloning
'; $(".title", ghost).textContent = new FormData(form).get("name"); $(".mono", ghost).textContent = new FormData(form).get("repo"); const list = $("#live .list"); const empty = $(".empty", list); if (empty) empty.hidden = true; list.prepend(ghost); undo.push(() => { ghost.remove(); if (empty) empty.hidden = false; }); } return () => undo.forEach((f) => f()); } async function submit(form, button) { const verb = new URL(form.action).pathname.slice(1); const body = new URLSearchParams(new FormData(form)); const undo = showPending(verb, form, button); inFlight++; clearTimeout(timer); let data; try { const res = await fetch(form.action, { method: "POST", body, credentials: "same-origin", headers: { Accept: "application/json" }, }); data = res.headers.get("Content-Type")?.startsWith("application/json") ? await res.json() : { ok: false, error: `${res.status} ${(await res.text()).trim().slice(0, 200)}` }; } catch { data = { ok: false, error: "Couldn't reach the server. Check your connection and try again." }; } inFlight--; if (data.ok) { toast("ok", data.message); if (!form.closest(".card")) undo(); // side panel forms stay; cards are replaced by the refresh if (verb === "create") { const repo = form.elements.repo.value; form.reset(); form.elements.repo.value = repo; } if (verb === "add-repo") { const added = new FormData(form).get("key") || null; form.reset(); if (data.repos) setRepoOptions(data.repos, data.repos.find((r) => r === added) || newest(data.repos)); $("#name")?.focus(); } } else { undo(); toast("err", data.error || "Something went wrong"); } refresh(); } // The key add-repo just added: the one that wasn't in the list before. function newest(names) { const before = new Set([...$("#repo").options].map((o) => o.value)); return names.find((n) => !before.has(n)); } document.addEventListener("submit", (ev) => { const form = ev.target; if (!(form instanceof HTMLFormElement) || form.method.toLowerCase() !== "post") return; ev.preventDefault(); const button = ev.submitter || $("button", form); if (button?.disabled) return; submit(form, button); }); document.addEventListener("click", (ev) => { const link = ev.target.closest("[data-refresh]"); if (!link) return; ev.preventDefault(); link.classList.add("loading"); refresh().finally(() => link.classList.remove("loading")); }); document.addEventListener("visibilitychange", () => (document.hidden ? clearTimeout(timer) : refresh())); humanizeTimes(document); schedule(); })();