// Chronos Server admin panel — vanilla ES modules, no build step (BRIEF §14.8). import { api, ApiFailure } from "./api.js"; import { t, plural, loadStrings, applyStrings, setLanguage, languages, culture } from "./i18n.js"; import { icons } from "./icons.js"; import { escapeHtml, attr, errorText, nativeName, formatNumber, fitColumns } from "./ui.js"; const app = document.getElementById("app"); // The menu: its pages from the top, then the ones docked at its foot above the account (owner review 2). const topPages = ["dashboard", "users", "archive", "jobs", "logs"]; const bottomPages = ["settings"]; const pages = [...topPages, ...bottomPages]; /** Routes of old bookmarks and where they open now: About is the last group of Settings (owner review 2). */ const MOVED = { about: "settings?group=about" }; const THEME_KEY = "chronos.admin.theme"; const SIDEBAR_KEY = "chronos.admin.sidebar"; /** The narrow layout of admin.css, where the menu is the top bar and does not collapse. */ const NARROW = window.matchMedia("(max-width: 900px)"); let info = null; let events = null; const listeners = new Set(); /** The sidebar choice made on this page, kept here too: a browser that refuses storage still keeps it across pages. */ let sidebarChoice = null; applyTheme(storedTheme()); async function start() { await loadStrings(); info = await api.get("/api/v1/server/info").catch(() => null); await api.resume(); window.addEventListener("hashchange", () => render("title")); // The menu's names or its icons alone, as on the desktop (owner review 1). A layout whose B key types another letter // (Cyrillic, Greek, Hebrew, Arabic) is matched on the physical key, so the tooltips' Ctrl+B holds in every language. In the // narrow layout the menu is the top bar with no toggle: the browser keeps its own Ctrl+B there. document.addEventListener("keydown", (e) => { if (!(e.ctrlKey || e.metaKey) || e.shiftKey || e.altKey || e.repeat || !app.querySelector(".shell") || NARROW.matches) return; const key = e.key.toLowerCase(); if (key !== "b" && !(e.code === "KeyB" && !/^[a-z]$/.test(key))) return; e.preventDefault(); toggleSidebar(); }); window.addEventListener("chronos:signed-out", () => { events?.stop(); events = null; render(); }); render(); } function currentPage() { let p = location.hash.replace(/^#\/?/, "").split("?")[0]; if (Object.hasOwn(MOVED, p)) { // The address shows the new route; replaceState fires no hashchange. history.replaceState(null, "", `#/${MOVED[p]}`); p = MOVED[p].split("?")[0]; } return pages.includes(p) ? p : "dashboard"; } /** Draws the page for the session state; focus names the shell element that gets the keyboard focus. */ function render(focus = null) { const user = api.user(); if (!user) return renderLogin(); if (user.mustChangePassword) return renderPasswordChange(); renderShell(currentPage(), focus); } function brand() { return `
Chronos Server${escapeHtml(info?.name ?? "")} · v${escapeHtml(info?.version ?? "")}
`; } function renderLogin(message = "") { document.title = `${t("Admin.Login.SignIn")} · Chronos Server`; app.innerHTML = `
${brand()}
`; applyStrings(app); const form = app.querySelector("form"); const error = form.querySelector(".error"); form.addEventListener("submit", async (e) => { e.preventDefault(); error.textContent = ""; const data = new FormData(form); try { const r = await api.signIn(String(data.get("username")), String(data.get("password"))); if (r.user.role !== "admin") { await api.signOut(); error.textContent = t("Admin.Login.NotAdmin"); return; } render(); } catch (err) { error.textContent = err instanceof ApiFailure && err.status === 401 ? t("Admin.Login.Failed") : errorText(err); } }); form.querySelector("input").focus(); } function renderPasswordChange() { document.title = `${t("Admin.Password.Title")} · Chronos Server`; app.innerHTML = `
${brand()}

`; applyStrings(app); const form = app.querySelector("form"); const error = form.querySelector(".error"); app.querySelector("#cancel").addEventListener("click", async () => { await api.signOut(); render(); }); form.addEventListener("submit", async (e) => { e.preventDefault(); const data = new FormData(form); if (data.get("next") !== data.get("repeat")) { error.textContent = t("Admin.Password.Mismatch"); return; } try { await api.changePassword(String(data.get("current")), String(data.get("next"))); render(); } catch (err) { error.textContent = errorText(err); } }); form.querySelector("input").focus(); } function renderShell(page, focus) { const links = (group) => group.map((p) => ` ${icons[p]} `).join(""); const user = api.user(); const options = languages().map((code) => ``).join(""); app.innerHTML = `

`; applyStrings(app); applySidebar(sidebarCollapsed()); app.querySelector("#sidebar-toggle").addEventListener("click", toggleSidebar); document.title = `${t(`Admin.Nav.${cap(page)}`)} · Chronos Server`; app.querySelector("#signout").addEventListener("click", async () => { events?.stop(); events = null; await api.signOut(); render(); }); app.querySelector("#language").addEventListener("change", async (e) => { await setLanguage(e.target.value); render("language"); }); app.querySelector("#theme").addEventListener("click", (e) => { const theme = isDark() ? "light" : "dark"; applyTheme(theme); try { localStorage.setItem(THEME_KEY, theme); } catch { // Only this page keeps the theme then. } e.currentTarget.setAttribute("aria-pressed", String(theme === "dark")); }); if (focus) app.querySelector(`#${focus}`)?.focus(); events ??= api.events((e) => listeners.forEach((fn) => fn(e))); listeners.clear(); pages.forEach(showBadge); updateBadges(); listeners.add((e) => { if (e.type === "jobState") updateBadges(); }); const meta = app.querySelector("#meta"); const content = app.querySelector("#content"); const context = { api, info, /** Header text after the title (one line, full text in the tooltip); paths and file names stay left to right. */ setMeta(text, { ltr = false } = {}) { meta.textContent = text; meta.title = text; meta.dir = ltr ? "ltr" : "auto"; }, actions: app.querySelector("#actions"), onEvent: (fn) => listeners.add(fn), }; import(`./pages/${page}.js`) .then((m) => m.render(content, context)) .catch((err) => { content.innerHTML = `
${escapeHtml(errorText(err))}
`; }); } /** The menu shows icons alone: their tooltips then name the page, and the choice is kept in this browser. */ function applySidebar(collapsed) { const shell = app.querySelector(".shell"); if (!shell) return; shell.classList.toggle("collapsed", collapsed); const toggle = shell.querySelector("#sidebar-toggle"); const tip = t(collapsed ? "Admin.Nav.Expand.Tip" : "Admin.Nav.Collapse.Tip"); toggle.title = tip; toggle.setAttribute("aria-label", tip); toggle.setAttribute("aria-expanded", String(!collapsed)); shell.querySelectorAll(".nav a").forEach((a) => { const page = a.getAttribute("href").replace("#/", ""); const tip = t(`Admin.Nav.${cap(page)}.Tip`); a.title = collapsed ? t("Admin.Nav.Collapsed", t(`Admin.Nav.${cap(page)}`), tip) : tip; // Screen readers already have the name (the hidden label): their description stays the tip alone. if (collapsed) a.setAttribute("aria-description", tip); else a.removeAttribute("aria-description"); }); } function sidebarCollapsed() { if (sidebarChoice !== null) return sidebarChoice; try { return localStorage.getItem(SIDEBAR_KEY) === "collapsed"; } catch { return false; } } function toggleSidebar() { const collapsed = !app.querySelector(".shell")?.classList.contains("collapsed"); sidebarChoice = collapsed; applySidebar(collapsed); // The page's width changed by 200 px without a window resize: the tables fit their columns again. document.querySelectorAll(".table[data-levels]").forEach(fitColumns); try { localStorage.setItem(SIDEBAR_KEY, collapsed ? "collapsed" : "expanded"); } catch { // Only this page keeps the choice then (sidebarChoice). } } const badgeCounts = new Map(); let badgeTimer = null; let badgeAgain = false; /** Running jobs and accounts as nav badges: fetched at most every two seconds (then once more if asked meanwhile). */ function updateBadges() { if (badgeTimer) { badgeAgain = true; return; } badgeTimer = setTimeout(() => { badgeTimer = null; if (badgeAgain) { badgeAgain = false; updateBadges(); } }, 2000); api.get("/api/v1/jobs?state=running&limit=100").then((page) => setBadge("jobs", page.items.length)).catch(() => {}); api.get("/api/v1/users").then((users) => setBadge("users", users.length)).catch(() => {}); } function setBadge(page, count) { badgeCounts.set(page, count); showBadge(page); } /** The last known count on the page's nav link: a pill for the eye, a phrase for screen readers. */ function showBadge(page) { const badge = document.getElementById(`badge-${page}`); const count = badgeCounts.get(page); if (!badge || count === undefined) return; badge.hidden = count === 0; badge.textContent = formatNumber(count); badge.classList.toggle("quiet", page !== "jobs"); document.getElementById(`badge-text-${page}`).textContent = count === 0 ? "" : plural(page === "jobs" ? "Admin.Jobs.RunningCount" : "Admin.Users.Accounts", count); } function storedTheme() { try { return localStorage.getItem(THEME_KEY); } catch { return null; } } /** Light or dark as chosen in this browser; without a choice the operating system's setting applies (admin.css). */ function applyTheme(theme) { if (theme === "light" || theme === "dark") document.documentElement.dataset.theme = theme; } function isDark() { const chosen = document.documentElement.dataset.theme; return chosen ? chosen === "dark" : matchMedia("(prefers-color-scheme: dark)").matches; } function cap(s) { return s.charAt(0).toUpperCase() + s.slice(1); } start();