Add repos from the page, answer actions in place, Expo-style redesign
Add repository: - New remote verb `add-repo KEY OWNER/NAME`. Off unless config.toml has [repo_add] (base_url + owners). Only listed owners; the dev box builds the URL itself, checks it with `git ls-remote` (bot access), then appends to [repos] under the lock. No URL crosses the SSH link. - `repos` also reports where adding is allowed, so the page shows the form only when it's on and rejects other hosts before calling SSH. - set_toml_string inserts after the section's last key, not after trailing blank lines / the next section's comments. Responsiveness: - web/static/app.js (progressive enhancement; every form still works without JS): forms go via fetch and get a JSON answer instead of POST-redirect-GET; buttons/cards show the change immediately; the list refreshes itself (15 s, 3 s while something is starting). - `repos` is cached for 5 min (refreshed on add-repo), so a page view is one SSH call instead of two. - `list` reads all unit states with one `systemctl show` instead of one per session: 676 -> 374 ms on the dev box with 21 sessions. - Static assets are content-hashed and cached immutably. Design: slate greys, hairline borders, black primary action, tinted status badges, monospace repo/branch, two columns on desktop, stacked on phones, light and dark. Docs: README security model, AGENTS.md (JS convention, add-repo invariant), config.example.toml. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MCUMXh8zZConC75Mptbeou
This commit is contained in:
parent
39997de1e8
commit
1b3172bd50
10 changed files with 1084 additions and 92 deletions
224
web/static/app.js
Normal file
224
web/static/app.js
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
// 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 = '<div class="card-top"><h3 class="title"></h3>' +
|
||||
'<span class="badge activating"><i></i>Cloning</span></div><div class="meta"><span class="mono"></span></div>';
|
||||
$(".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();
|
||||
})();
|
||||
Loading…
Add table
Add a link
Reference in a new issue