import { useEffect, useState, type ReactNode } from "react"; import type { WallGroup, WallTile } from "../api/client"; import { formatDate, formatTime } from "../utils/date"; import { formatRemaining } from "../utils/duration"; import { applyDisplay, groupMembers, nightState, pageOrOverview, ROTATE_CHOICES, stepPage, WAKE_FOR_MS, wallPages, type WallNight } from "../utils/wallPages"; import { t } from "../i18n"; export const REFRESH_MS = 30_000; const TYPE_LABELS: Record = { tailscale: "Tailscale", proxmox: "Proxmox", synology: "Synology", semaphore: "Semaphore", gitea: "Gitea", dockhand: "Docker", uptimekuma: "Uptime Kuma", phpipam: "phpIPAM", pbs: "Proxmox Backup", osticket: "osTicket", unifi: "UniFi", npm: "Nginx Proxy Manager", homeassistant: "Home Assistant", ups: "UPS", jellyfin: "Jellyfin", authentik: "Authentik", prometheus: "Prometheus", immich: "Immich", paperless: "Paperless-ngx", n8n: "n8n", netbox: "NetBox", nextcloud: "Nextcloud", hetzner: "Hetzner Cloud", speedtest: "Speedtest Tracker", fragnet: "Fragnet game servers", sonarr: "Sonarr", radarr: "Radarr", prowlarr: "Prowlarr", adguard: "AdGuard Home", technitium: "Technitium DNS", grafana: "Grafana", lidarr: "Lidarr", readarr: "Readarr", qbittorrent: "qBittorrent", sabnzbd: "SABnzbd", hetznerrobot: "Hetzner Robot", }; export type WallLevel = "critical" | "warning" | "ok" | "unsure"; /** Everything the board shows. A list that is null is not shown on this board (a share link that only gives numbers). */ export interface WallData { level: WallLevel; headline: string; servers: { online: number; total: number } | null; alerts: { critical: number; warning: number } | null; maintenance: number; integrationsFailing: number | null; problems: { id: string; severity: "critical" | "warning"; message: string }[] | null; windows: { id: number; name: string; endsAt: string }[] | null; integrations: { id: number; name: string; type: string; status: "ok" | "failing" | "unknown" }[] | null; /** What else is worth a glance, and a summary of each group of integrations; absent on a board that has none. */ tiles?: WallTile[]; groups?: WallGroup[]; environmentName: string | null; updatedAt: Date | null; } /** The headline in words for how many things need a look, or why there is no answer yet. */ export function wallHeadline(level: WallLevel, count: number, state: { loaded: boolean; failed: boolean }): string { if (level === "critical" || level === "warning") return `${count} ${count === 1 ? "thing needs" : "things need"} attention`; if (level === "unsure") return state.loaded ? t("No alerts — but some checks couldn't run") : state.failed ? "Can't reach the server" : "Checking…"; return "All clear"; } function useClock(): Date { const [now, setNow] = useState(() => new Date()); useEffect(() => { const t = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(t); }, []); return now; } /** Keeps the screen awake while the page is open, where the browser allows it — and lets go while `enabled` is false (a blank night screen, so the device may sleep). */ function useWakeLock(enabled = true) { useEffect(() => { if (!enabled) return; let lock: { release: () => Promise } | null = null; let gone = false; const request = async () => { try { const nav = navigator as Navigator & { wakeLock?: { request: (type: "screen") => Promise<{ release: () => Promise }> } }; if (nav.wakeLock && !gone) lock = await nav.wakeLock.request("screen"); } catch { // not allowed (battery saver, no permission): the screen may sleep like any other } }; void request(); const onVisible = () => document.visibilityState === "visible" && void request(); document.addEventListener("visibilitychange", onVisible); return () => { gone = true; document.removeEventListener("visibilitychange", onVisible); void lock?.release().catch(() => {}); }; }, [enabled]); } /** * The board itself: a full-screen status picture in type big enough to read across a room. It only draws what it is given, so the * signed-in wall and the one a share link opens look the same and can't drift apart. */ export default function WallView({ data, idle, footerActions, rotation, display, }: { data: WallData; idle: boolean; footerActions: ReactNode; /** A named display: its name (shown in the footer) and which pages it rotates through, in order; none listed is every page. */ display?: { name: string; pages: string[]; night?: WallNight | null } | null; /** How the pages rotate (seconds each, null for the overview alone) and how to change it; absent on a board that does not rotate. */ rotation?: { seconds: number | null; onChange: (seconds: number | null) => void }; }) { const now = useClock(); // The night: dimmed or blank by the screen's own clock, unless something is critical (and the schedule says to show it) or somebody has just touched the screen. const [wokenUntil, setWokenUntil] = useState(null); const night = nightState(now, display?.night, { critical: data.level === "critical", wokenUntil }); useWakeLock(night !== "off"); useEffect(() => { if (!display?.night) return; const wake = () => setWokenUntil(Date.now() + WAKE_FOR_MS); window.addEventListener("pointerdown", wake); window.addEventListener("keydown", wake); return () => { window.removeEventListener("pointerdown", wake); window.removeEventListener("keydown", wake); }; }, [display?.night]); // The pages: the overview, what needs attention (while something does), and one for each group of integrations. const rotating = !!rotation && rotation.seconds !== null; const pages = applyDisplay(wallPages(data), display?.pages ?? []); const pagesKey = pages.map((p) => p.id).join(","); const [pageId, setPageId] = useState("overview"); const [paused, setPaused] = useState(false); const page = rotating ? pageOrOverview(pages, pageId) : pages[0]; const seconds = rotation?.seconds ?? null; useEffect(() => { if (!rotating || paused || pages.length < 2 || seconds === null) return; const t = setTimeout(() => setPageId(stepPage(pages, page.id, 1).id), seconds * 1000); return () => clearTimeout(t); // eslint-disable-next-line react-hooks/exhaustive-deps }, [rotating, paused, seconds, page.id, pagesKey]); // The arrow keys step through the pages by hand (and start the wait again). useEffect(() => { if (!rotating) return; const onKey = (e: KeyboardEvent) => { const el = e.target as HTMLElement | null; if (el && (el.tagName === "SELECT" || el.tagName === "INPUT")) return; if (e.key === "ArrowRight") setPageId(stepPage(pages, page.id, 1).id); else if (e.key === "ArrowLeft") setPageId(stepPage(pages, page.id, -1).id); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); // eslint-disable-next-line react-hooks/exhaustive-deps }, [rotating, page.id, pagesKey]); const { level } = data; const offline = data.servers ? data.servers.total - data.servers.online : 0; const alertCount = data.alerts ? data.alerts.critical + data.alerts.warning : 0; const showsDetail = data.problems !== null || data.windows !== null || data.integrations !== null; return (
{night === "off" &&
{t("Night — touch the screen to wake it")}
}
Homelab Manager {data.environmentName && {data.environmentName}}
{formatTime(now, false)}
{now.toLocaleDateString([], { weekday: "long" })} {formatDate(now)}
{data.headline}
0 ? "wall-tile-bad" : ""}`}>
{data.servers ? (data.servers.total === 0 ? "—" : `${data.servers.online}/${data.servers.total}`) : "…"}
servers online
0 ? "wall-tile-bad" : (data.alerts?.warning ?? 0) > 0 ? "wall-tile-warn" : ""}`}>
{data.alerts ? alertCount : "…"}
alerts{data.alerts && alertCount > 0 ? ` (${data.alerts.critical} critical, ${data.alerts.warning} warning)` : ""}
0 ? "wall-tile-info" : ""}`}>
{data.maintenance}
in maintenance
0 ? "wall-tile-bad" : ""}`}>
{data.integrationsFailing === null ? "…" : data.integrationsFailing}
integrations failing
{(data.tiles ?? []).map((t) => (
{t.figure}
{t.label}
))}
{page.kind === "alerts" && } {page.kind === "group" && } {page.kind === "overview" && (data.groups ?? []).length > 0 && (
{(data.groups ?? []).map((g) => { const alerts = g.alerts.critical + g.alerts.warning; const level = g.failing > 0 || g.alerts.critical > 0 ? "bad" : alerts > 0 ? "warn" : "ok"; const parts = [g.failing > 0 ? `${g.failing} of ${g.integrations} failing` : null, alerts > 0 ? `${alerts} ${alerts === 1 ? "alert" : "alerts"}` : null].filter(Boolean); return (
{g.label}{" "} {parts.length > 0 ? parts.join(" · ") : `${g.integrations} connected`}
); })}
)} {page.kind !== "overview" ? null : showsDetail ? (
{data.problems && ( <>

{t("Needs attention")}

{data.problems.length === 0 ? (
{t("Nothing right now.")}
) : (
    {data.problems.slice(0, 7).map((a) => (
  • {a.severity}: {a.message}
  • ))} {alertCount > 7 &&
  • and {alertCount - 7} more
  • }
)} )} {data.windows && data.windows.length > 0 && ( <>

{t("In maintenance")}

    {data.windows.slice(0, 8).map((w) => (
  • {w.name} · {formatRemaining(w.endsAt, now.getTime())} left
  • ))} {data.maintenance > 8 &&
  • and {data.maintenance - 8} more
  • }
)}
{data.integrations && ( <>

{t("Integrations")}

{data.integrations.length === 0 ? (
{t("None connected.")}
) : (
    {data.integrations.map((i) => (
  • {i.name}{" "} {TYPE_LABELS[i.type] ?? i.type} — {i.status === "failing" ? "failing" : i.status === "ok" ? "working" : "not checked yet"}
  • ))}
)} )}
) : (
{t("This board shows the numbers only.")}
)}
{display?.name && {display.name} · } {data.updatedAt ? `Updated ${formatTime(data.updatedAt)}` : t("Loading…")} · refreshes every {REFRESH_MS / 1000} s {rotating && pages.length > 1 && ( p.id === page.id) + 1} of ${pages.length}: ${page.label}`}> {" "} · {page.label}{" "} {pages.map((p) => ( ))} )} {rotation && pages.length > 1 && ( <> {rotating && pages.length > 1 && ( )} )} {footerActions}
); } /** What needs attention, in the whole screen's type: the open alerts, and what is in maintenance. */ function AlertsPage({ data, now }: { data: WallData; now: Date }) { const problems = data.problems ?? []; const alertCount = data.alerts ? data.alerts.critical + data.alerts.warning : problems.length; const shown = problems.slice(0, 12); return (

{t("Needs attention")}

    {shown.map((a) => (
  • {a.severity}: {a.message}
  • ))} {alertCount > shown.length &&
  • and {alertCount - shown.length} more
  • }
{data.windows && data.windows.length > 0 && ( <>

{t("In maintenance")}

    {data.windows.slice(0, 8).map((w) => (
  • {w.name} · {formatRemaining(w.endsAt, now.getTime())} left
  • ))}
)}
); } /** One group of integrations (Infrastructure, Apps …): how it is, and each of them with its status. */ function GroupPage({ data, groupId, label }: { data: WallData; groupId: string; label: string }) { const members = groupMembers(data.integrations ?? [], groupId); const summary = (data.groups ?? []).find((g) => g.id === groupId); const alerts = summary ? summary.alerts.critical + summary.alerts.warning : 0; const failing = members.filter((m) => m.status === "failing").length; const level = failing > 0 || (summary?.alerts.critical ?? 0) > 0 ? "bad" : alerts > 0 ? "warn" : "ok"; return (

{label}{" "} {" "} {failing > 0 ? `${failing} of ${members.length} failing` : `${members.length} connected`} {alerts > 0 ? ` · ${alerts} ${alerts === 1 ? "alert" : "alerts"}` : ""}

    {members.map((i) => (
  • {i.name}{" "} {TYPE_LABELS[i.type] ?? i.type} — {i.status === "failing" ? "failing" : i.status === "ok" ? "working" : "not checked yet"}
  • ))}
); }