// SPDX-License-Identifier: CPAL-1.0 // Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution // License 1.0: see LICENSE (its Exhibit A is this file's notice). // Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state, // the server clock offset and toasts. No business logic: everything shown comes from control. import { call, newKey, sentence, setClientEvents } from "./api"; import type { Overview } from "./types"; export interface Toast { id: number; text: string; } export const app = $state({ overview: null as Overview | null, etag: null as string | null, loadError: false, lostContact: false, lostSince: 0, lastUpdated: 0, signedOut: false, offset: 0, now: Date.now(), path: typeof location === "undefined" ? "/" : location.pathname + location.search, toasts: [] as Toast[], /** Dismissed banner keys (reverted outcome, renewed, switched). */ dismissed: [] as string[], /** The outcome of the last engine switch, until dismissed (handoff §9.2). */ switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null }, /** A renewal just installed (handoff §13.5). */ renewedUntil: null as null | string, /** After a kept add or edit: the row whose More button gets focus (§7.5). */ focusHost: null as string | null, /** Narrower than 720 px (the phone layout, handoff §5.2). */ phone: false, /** Panels the main screen opens (add/edit host, share, engine). */ panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" }, }); let failures = 0; let firstFailure = 0; setClientEvents({ onSignedOut: () => { app.signedOut = true; }, onContact: (ok) => { if (ok) { failures = 0; app.lostContact = false; return; } if (failures === 0) firstFailure = Date.now(); failures++; // Retry quietly for 10 s (a reload takes about 2 s), then say so (§11.1). if (Date.now() - firstFailure >= 10_000) { if (!app.lostContact) app.lostSince = Date.now(); app.lostContact = true; } }, onServerTime: (o) => { app.offset = o; }, }); /** Server time now, in ms (all countdowns use it, §7.2). */ export function serverNow(): number { return app.now + app.offset; } /** Seconds left until an ISO time, on the server's clock. */ export function secondsLeft(iso: string | null | undefined): number { if (!iso) return 0; return Math.max(0, Math.ceil((Date.parse(iso) - serverNow()) / 1000)); } export async function refresh(): Promise { if (app.signedOut) return; try { const a = await call("GET", "/overview", undefined, { etag: app.etag ?? undefined }); if (a.status === 200 && a.data) { app.overview = a.data; app.etag = a.etag; } app.loadError = false; app.lastUpdated = Date.now(); } catch { if (!app.overview) app.loadError = true; } } let timer: ReturnType | undefined; let hiddenSince = 0; /** Poll every 5 s while visible, 30 s when hidden, stop after 15 min hidden (Q9). */ export function startPolling(): () => void { let stopped = false; const tick = async () => { if (stopped) return; const hidden = typeof document !== "undefined" && document.visibilityState === "hidden"; if (hidden && !hiddenSince) hiddenSince = Date.now(); if (!hidden) hiddenSince = 0; if (!(hidden && Date.now() - hiddenSince > 15 * 60_000)) await refresh(); const every = app.lostContact ? 5000 : hidden ? 30_000 : 5000; timer = setTimeout(tick, every); }; const vis = () => { if (document.visibilityState === "visible" && hiddenSince) { hiddenSince = 0; clearTimeout(timer); void tick(); } }; document.addEventListener("visibilitychange", vis); const clock = setInterval(() => (app.now = Date.now()), 1000); void tick(); return () => { stopped = true; clearTimeout(timer); clearInterval(clock); document.removeEventListener("visibilitychange", vis); }; } let toastId = 0; export function toast(text: string): void { const id = ++toastId; app.toasts = [...app.toasts.slice(-2), { id, text }]; setTimeout(() => { app.toasts = app.toasts.filter((t) => t.id !== id); }, 6000); } export function navigate(path: string): void { if (path === app.path) return; history.pushState({}, "", path); app.path = path; } if (typeof window !== "undefined" && typeof window.matchMedia === "function") { const mq = window.matchMedia("(max-width: 719.98px)"); app.phone = mq.matches; mq.addEventListener?.("change", (e) => (app.phone = e.matches)); } if (typeof window !== "undefined") { window.addEventListener("popstate", () => { app.path = location.pathname + location.search; }); } /** Is a change allowed now? (Paused, or no contact.) */ export function changesBlocked(): string | null { const o = app.overview; if (app.lostContact) return "Ianitor's control service is not answering."; if (o?.paused) return "Changes are paused."; return null; } /** "Restore the last kept version" (handoff §7.6): start it and show its progress in a panel. * Returns the sentence to show when it could not start. */ export async function restoreLastKept(): Promise { const o = app.overview; if (!o?.undo?.target) return null; try { const a = await call<{ apply: { id: string } }>("POST", "/restore", { change_id: o.undo.target.change_id, base_rev: o.rev }, { idem: newKey() }); if (a.data) app.panel = { kind: "host", resume: a.data.apply.id }; return null; } catch (e) { return sentence(e); } } /** Whether the pause can be cleared by restoring the last kept version. */ export function restorable(): boolean { const o = app.overview; return !!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target; }