// Hash router and the printer status pill. import {get} from "./api.js"; import {$} from "./dom.js"; import {editorView} from "./editor.js"; import {historyView} from "./history.js"; import {printView} from "./print.js"; import {schedulesView} from "./schedules.js"; import {settingsView} from "./settings.js"; const view = $("#view"); let current = null; // what the active view returned: a cleanup function or {canLeave} let currentHash = location.hash; async function route() { const hash = location.hash || "#print"; if (current?.canLeave && hash !== currentHash && !current.canLeave()) { history.replaceState(null, "", currentHash); // stay put return; } if (typeof current === "function") current(); current = null; currentHash = hash; const [tab, arg] = hash.slice(1).split("/"); document.querySelectorAll("nav.tabs a").forEach((a) => a.classList.toggle("on", a.getAttribute("href") === `#${tab}`)); view.setAttribute("aria-busy", "true"); if (tab === "schedules" && arg) current = await editorView(view, arg); else if (tab === "schedules") current = await schedulesView(view); else if (tab === "history") current = await historyView(view, arg); else if (tab === "settings") current = await settingsView(view); else current = printView(view); view.removeAttribute("aria-busy"); window.scrollTo(0, 0); } window.addEventListener("hashchange", route); window.addEventListener("beforeunload", (e) => { if (current?.isDirty?.()) e.preventDefault(); }); async function checkStatus() { const pill = $("#status"); pill.textContent = "checking…"; pill.className = "pill"; const r = await get("api/status"); pill.textContent = r.body.busy ? "printer busy" : r.ok ? "printer ready" : "printer offline"; pill.className = `pill ${r.ok ? "ok" : "err"}`; pill.title = r.text; } $("#status").addEventListener("click", checkStatus); checkStatus(); route();