diff options
Diffstat (limited to 'static/app.js')
| -rw-r--r-- | static/app.js | 210 |
1 files changed, 26 insertions, 184 deletions
diff --git a/static/app.js b/static/app.js index 8c6d4e2..c296b90 100644 --- a/static/app.js +++ b/static/app.js @@ -1,4 +1,4 @@ -// deck-it - the page shell: tabs, cards and polling +// deck-it - the page shell: tabs and polling // Copyright (C) 2026 Danilo M. <danix@danix.xyz> // // This program is free software; you can redistribute it and/or modify @@ -15,42 +15,17 @@ // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // The shell: discover modules, sort them into tabs, mount each panel and poll -// its state. A module is static/modules/<name>.js exporting default {title, -// tab, interval, mount(el), update(state, el)}. Modules without a tab go into -// the Dashboard. Card order and size are kept in this browser's localStorage. +// its state. A module with a tab is static/modules/<name>.js exporting default +// {title, tab, interval, mount(el), update(state, el)}. The Dashboard tab is +// static/dashboard.js, which draws the modules without a tab. const tabBar = document.getElementById("tabs"); document.getElementById("reload").onclick = () => location.reload(); const tabBody = document.getElementById("tab-body"); const refreshers = []; -const LAYOUT_KEY = "deckit.layout"; const TAB_KEY = "deckit.tab"; -// Folded cards: id -> the height to restore when unfolded. -const FOLD_KEY = "deckit.folded"; -const DEFAULT_W = 6; -const DEFAULT_H = 4; const tabs = {}; -let ready = false; - -function loadLayout() { - try { - const saved = JSON.parse(localStorage.getItem(LAYOUT_KEY)); - return Array.isArray(saved) ? saved : []; - } catch { - return []; - } -} - -function saveLayout() { - if (!ready) return; // don't clobber the stored layout while the cards mount - try { - localStorage.setItem(LAYOUT_KEY, JSON.stringify(grid.save(false))); - } catch { - // private mode or storage full: the layout just won't persist - } -} - // Tab icons, Font Awesome glyphs in the Nerd Font the server serves; a tab // not listed shows its name. The name also shows next to the active one. const TAB_ICONS = { Dashboard: "\uf0e4", Windows: "\uf2d2", OBS: "\uf03d", Assistant: "\uf086", K1C: "\uf02f" }; @@ -97,163 +72,29 @@ function showTab(name) { try { localStorage.setItem(TAB_KEY, name); } catch {} - if (name === "Dashboard") window.dispatchEvent(new Event("resize")); } -// Dashboard is the grid; it exists before the modules so Gridstack measures a -// visible container. const dashboard = ensureTab("Dashboard"); dashboard.section.hidden = false; dashboard.button.classList.add("active"); -const gridEl = document.createElement("div"); -gridEl.id = "grid"; -gridEl.className = "grid-stack"; -dashboard.section.append(gridEl); - -const grid = GridStack.init({ - column: 12, - cellHeight: 80, - margin: 8, - float: true, - handle: ".panel-drag", - resizable: { handles: "se" }, -}, gridEl); -grid.on("change", saveLayout); - -const savedById = {}; -for (const node of loadLayout()) { - if (node.id) savedById[node.id] = node; -} - -function loadFolded() { - try { - const saved = JSON.parse(localStorage.getItem(FOLD_KEY)); - return saved && typeof saved === "object" ? saved : {}; - } catch { - return {}; - } -} -const folded = loadFolded(); - -// Folding shrinks the card to one grid row and hides its body; the row it -// keeps is only the title bar (the content stops at the header). Its height -// before folding is kept so unfolding restores it, and it cannot be resized -// while folded. -function setFolded(item, fold) { - const id = item.getAttribute("gs-id"); - const content = item.querySelector(".panel"); - const button = item.querySelector(".panel-fold"); - if (fold) { - const node = item.gridstackNode; - if (!(id in folded)) folded[id] = node?.h ?? DEFAULT_H; - grid.update(item, { h: 1, noResize: true }); - closeGaps(); - } else if (id in folded) { - grid.update(item, { h: folded[id], noResize: false }); - delete folded[id]; - } - content.classList.toggle("folded", fold); - button.textContent = fold ? "▸" : "▾"; - button.setAttribute("aria-label", fold ? "Unfold panel" : "Fold panel"); - button.setAttribute("aria-expanded", String(!fold)); - try { - localStorage.setItem(FOLD_KEY, JSON.stringify(folded)); - } catch {} -} - -// The grid floats, so nothing moves into rows a folded card gave back. Pull -// each card below a folded one, in its columns, up as far as the space is -// free (never above the folded card's title bar). Unfolding needs no mirror: -// the grid pushes down whatever the regrown card hits. -function closeGaps() { - const nodes = grid.engine.nodes; - const clash = (n, y) => nodes.some((o) => o !== n && o.x < n.x + n.w && o.x + o.w > n.x - && o.y < y + n.h && o.y + o.h > y); - const folds = nodes.filter((n) => n.el.querySelector(".panel.folded")); - const below = nodes - .filter((n) => folds.some((f) => n.y > f.y && n.x < f.x + f.w && n.x + n.w > f.x)) - .sort((a, b) => a.y - b.y); - for (const n of below) { - const floor = Math.max(...folds.filter((f) => n.y > f.y && n.x < f.x + f.w && n.x + n.w > f.x) - .map((f) => f.y + f.h)); - let y = n.y; - while (y - 1 >= floor && !clash(n, y - 1)) y--; - if (y !== n.y) { - grid.update(n.el, { y }); - } - } -} - -function header(title) { - const head = document.createElement("div"); - head.className = "panel-head"; - const dot = document.createElement("span"); - dot.className = "panel-dot"; - const h = document.createElement("h2"); - h.textContent = title; - const fold = document.createElement("button"); - fold.className = "panel-fold"; - fold.textContent = "▾"; - fold.setAttribute("aria-label", "Fold panel"); - fold.setAttribute("aria-expanded", "true"); - fold.onclick = () => { - const item = fold.closest(".grid-stack-item"); - setFolded(item, !item.querySelector(".panel").classList.contains("folded")); - }; - const drag = document.createElement("button"); - drag.className = "panel-drag"; - drag.textContent = "⠿"; - drag.setAttribute("aria-label", "Move panel"); - head.append(dot, h, fold, drag); - return head; -} - -function makeCard(name, title) { - const item = document.createElement("div"); - item.className = "grid-stack-item"; - item.setAttribute("gs-id", name); - const s = savedById[name]; - item.setAttribute("gs-w", String(s?.w ?? DEFAULT_W)); - item.setAttribute("gs-h", String(s?.h ?? DEFAULT_H)); - if (s) { - item.setAttribute("gs-x", String(s.x)); - item.setAttribute("gs-y", String(s.y)); - } - const content = document.createElement("div"); - content.className = "grid-stack-item-content panel"; - const body = document.createElement("div"); - body.className = "panel-body"; - content.append(header(title), body); - item.append(content); - gridEl.append(item); - grid.makeWidget(item); - if (name in folded) setFolded(item, true); - return body; -} - -// The first poll is not awaited: a slow source (the build VM over ssh, a -// printer that is off) must not hold back the other panels. -function startPoll(name, panel, el) { - const poll = async () => { +// Polls /api/<name> every `seconds` and hands the state to update. The first +// poll is not awaited: a slow source (the build VM over ssh, a printer that +// is off) must not hold back the others. +function poll(name, seconds, update) { + const tick = async () => { try { const r = await fetch(`/api/${name}`); if (r.headers.get("X-Deckit-Sleep")) return goodnight("The PC is asleep"); awake(); - if (r.ok) panel.update?.(await r.json(), el); + if (r.ok) update(await r.json()); } catch { // keep the last state; the next tick retries } }; - refreshers.push(poll); - poll(); - setInterval(poll, (panel.interval ?? 1) * 1000); -} - -function mountDashboard(name, panel) { - const body = makeCard(name, panel.title ?? name); - panel.mount?.(body); - startPoll(name, panel, body); + refreshers.push(tick); + tick(); + setInterval(tick, seconds * 1000); } function mountTab(name, panel, section) { @@ -261,31 +102,32 @@ function mountTab(name, panel, section) { wrap.className = "tab-content"; section.append(wrap); panel.mount?.(wrap); - startPoll(name, panel, wrap); + poll(name, panel.interval ?? 1, (st) => panel.update?.(st, wrap)); } async function boot() { const r = await fetch("/api/modules"); if (!r.ok) return; // Every panel's code at once; then mount in the server's order, so the - // cards and tabs do not shuffle with whichever import lands first. + // tabs do not shuffle with whichever import lands first. const names = (await r.json()).map(({ name }) => name); const loaded = await Promise.all(names.map((name) => import(`./modules/${name}.js`).then((m) => m.default, () => null))); names.forEach((name, i) => { const panel = loaded[i]; - if (!panel) return; - const tabName = panel.tab ?? "Dashboard"; + if (!panel?.tab) return; // no tab: drawn by the Dashboard, if at all try { - if (tabName === "Dashboard") mountDashboard(name, panel); - else mountTab(name, panel, ensureTab(tabName).section); + mountTab(name, panel, ensureTab(panel.tab).section); } catch { - // a broken panel must not take down the rest of the dashboard + // a broken panel must not take down the rest of the page } }); - closeGaps(); - ready = true; - saveLayout(); + try { + const { default: dash } = await import("./dashboard.js"); + dash.mount(dashboard.section, names, { poll, open: showTab }); + } catch { + // the other tabs still work + } sortTabs(); const saved = localStorage.getItem(TAB_KEY); showTab(tabs[saved] ? saved : "Dashboard"); @@ -299,7 +141,7 @@ function stepTab(dir) { } // Swipe the content sideways to change tab, from anywhere but sliders and -// the dashboard's drag and resize handles, whose sideways drags are theirs. +// text fields, whose sideways drags are theirs. // #tab-body is `touch-action: pan-y`: otherwise the browser claims the moving // finger as a pan and sends pointercancel, which is why swipes never worked. // A swipe that started on a button must not also click it. @@ -307,7 +149,7 @@ let swipe = null; let swallowClick = false; tabBody.addEventListener("pointerdown", (e) => { if (e.pointerType === "mouse" && e.buttons !== 1) return; - if (e.target.closest("input, select, textarea, .panel-drag, .ui-resizable-handle")) { + if (e.target.closest("input, select, textarea")) { swipe = null; return; } |
