import { useEffect, useRef, useState, type ReactNode } from "react"; import { Link, NavLink, useLocation } from "react-router-dom"; import { IconPlaneDeparture, IconKey, IconMenu2, IconSun, IconMoon, IconShieldLock, IconTool, IconChevronUp, IconLogout, IconDeviceDesktop, IconChevronsLeft, IconChevronsRight } from "@tabler/icons-react"; import { api, type AwayView, type CurrentUser, type MaintenanceWindow } from "../api/client"; import { formatDateTime } from "../utils/date"; import { isCurrent, isGroup, visibleNav, type NavGroup } from "./nav"; import SidebarNav, { type NavBadge } from "./SidebarNav"; import { initFavorites } from "../utils/favorites"; import { initDashboardLayout } from "../utils/dashboardLayout"; import { initServerPageLayout } from "../utils/serverPageLayout"; import { formatRemaining } from "../utils/duration"; import { getTheme, setTheme, type Theme } from "../utils/theme"; import { DENSITIES, getDensity, setDensity, type Density } from "../utils/density"; import CommandPalette from "../components/CommandPalette"; import { isLightColor, useEnvironment } from "../utils/environment"; import { alertBadge, useAlertsReport } from "../hooks/useAlertsReport"; import { useMyWork } from "../hooks/useMyWork"; import { useStackedTables } from "../hooks/useStackedTables"; import { useShortcuts } from "../hooks/useShortcuts"; import { useHiddenPages, useMenuHiding } from "../hooks/useMenuHiding"; import { useFormLabels } from "../hooks/useFormLabels"; import ShortcutHelp from "../components/ShortcutHelp"; import Avatar from "../components/Avatar"; import { useBreadcrumbTailValue } from "../utils/breadcrumb"; import { getLanguage, LANGUAGES, setLanguage, t, tn } from "../i18n"; const RAIL_KEY = "hlm-sidebar-rail"; /** Whether the screen is at least this wide; follows the window as it is resized. */ function useMediaQuery(query: string): boolean { const [matches, setMatches] = useState(() => window.matchMedia(query).matches); useEffect(() => { const list = window.matchMedia(query); const onChange = () => setMatches(list.matches); list.addEventListener("change", onChange); onChange(); return () => list.removeEventListener("change", onChange); }, [query]); return matches; } const OPEN_GROUPS_KEY = "hlm-nav-open-groups"; function loadOpenGroups(): Set { try { const value = JSON.parse(localStorage.getItem(OPEN_GROUPS_KEY) ?? "[]"); return new Set(Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : []); } catch { return new Set(); // storage blocked or corrupted: start with everything closed } } export default function AppShell({ user, children }: { user: CurrentUser; children: ReactNode }) { const [sidebarOpen, setSidebarOpen] = useState(false); const [theme, setThemeState] = useState(() => getTheme()); const [density, setDensityState] = useState(() => getDensity()); // This person's pinned pages come with the user; load them before the menu is first drawn. useState(() => { initFavorites(user.favorites); initDashboardLayout(user.dashboard); initServerPageLayout(user.serverPage); return null; }); // The narrow, icon-only sidebar: remembered per browser (a laptop wants it, a big monitor may not), and only on wide screens. const [collapsed, setCollapsed] = useState(() => { try { return localStorage.getItem(RAIL_KEY) === "1"; } catch { return false; } }); const wide = useMediaQuery("(min-width: 992px)"); const rail = collapsed && wide; useEffect(() => { try { localStorage.setItem(RAIL_KEY, collapsed ? "1" : "0"); } catch { // not remembered; it still applies for this visit } }, [collapsed]); useEffect(() => { const toggle = () => setCollapsed((c) => !c); window.addEventListener("toggle-sidebar", toggle); return () => window.removeEventListener("toggle-sidebar", toggle); }, []); const [maintenance, setMaintenance] = useState([]); const [away, setAway] = useState(null); const environment = useEnvironment(); useStackedTables(); useMenuHiding(); useHiddenPages(); // so the menu is drawn again when the pages it leaves out change useShortcuts(user); useFormLabels(); const mainRef = useRef(null); const [announcement, setAnnouncement] = useState(""); const firstRoute = useRef(true); const breadcrumbTail = useBreadcrumbTailValue(); const { report } = useAlertsReport(); // Viewers have nothing to follow, so nothing is asked for them. const { work: myWork } = useMyWork(user.role === "admin" || user.role === "operator"); const [menuOpen, setMenuOpen] = useState(false); const menuRef = useRef(null); // Closes the user menu when you click elsewhere or press Escape. useEffect(() => { if (!menuOpen) return; const onDown = (e: MouseEvent) => { if (menuRef.current && !menuRef.current.contains(e.target as Node)) setMenuOpen(false); }; const onKey = (e: KeyboardEvent) => e.key === "Escape" && setMenuOpen(false); document.addEventListener("mousedown", onDown); document.addEventListener("keydown", onKey); return () => { document.removeEventListener("mousedown", onDown); document.removeEventListener("keydown", onKey); }; }, [menuOpen]); // Everyone sees what's currently silenced, so nobody is left wondering why an alert never came. useEffect(() => { let cancelled = false; const load = () => api.maintenance .list() .then((res) => { if (!cancelled) setMaintenance(res.windows); }) .catch(() => {}); load(); const poll = setInterval(load, 60_000); window.addEventListener("maintenance-changed", load); return () => { cancelled = true; clearInterval(poll); window.removeEventListener("maintenance-changed", load); }; }, []); // Everyone sees when notifications are being held because somebody is away, for the same reason. useEffect(() => { let cancelled = false; const load = () => api.away .get() .then((res) => { if (!cancelled) setAway(res); }) .catch(() => {}); load(); const poll = setInterval(load, 60_000); window.addEventListener("away-changed", load); return () => { cancelled = true; clearInterval(poll); window.removeEventListener("away-changed", load); }; }, []); const nav = visibleNav(user.role); const { pathname } = useLocation(); // A page change in a single-page app is silent: tell screen readers where they are, and move the keyboard to the new page's start // (not on the first load, where the browser has already done its own thing). useEffect(() => { const timer = setTimeout(() => { const title = document.querySelector(".page-title")?.textContent?.trim() || document.title; setAnnouncement(title); if (!firstRoute.current) mainRef.current?.focus({ preventScroll: true }); firstRoute.current = false; }, 200); return () => clearTimeout(timer); }, [pathname]); // Where this page sits in the menu: "Infrastructure › Servers", and on a page about one thing, that thing's name as well. const crumbs: { label: string; to?: string }[] = []; for (const entry of nav) { if (!isGroup(entry)) continue; const leaf = entry.items.find((item) => isCurrent(pathname, item.to)); if (!leaf) continue; crumbs.push({ label: t(entry.label) }, breadcrumbTail ? { label: t(leaf.label), to: leaf.to } : { label: t(leaf.label) }); if (breadcrumbTail) crumbs.push({ label: breadcrumbTail }); break; } const [openGroups, setOpenGroups] = useState>(loadOpenGroups); // The group holding the current page is always open, so you can see where you are (others stay as you left them). useEffect(() => { const active = nav.find((entry): entry is NavGroup => isGroup(entry) && entry.items.some((item) => isCurrent(pathname, item.to))); if (active) setOpenGroups((prev) => (prev.has(active.id) ? prev : new Set(prev).add(active.id))); // eslint-disable-next-line react-hooks/exhaustive-deps }, [pathname, user.role]); useEffect(() => { try { localStorage.setItem(OPEN_GROUPS_KEY, JSON.stringify([...openGroups])); } catch { // not persisted; the menu still works for this visit } }, [openGroups]); function toggleGroup(id: string) { setOpenGroups((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); } // What needs a look, shown next to the page that deals with it. const badges: Record = {}; const alerts = alertBadge(report); if (alerts) { badges["/alerts"] = { text: String(alerts.count), className: alerts.level === "critical" ? "bg-red text-red-fg" : "bg-yellow text-yellow-fg", title: tn(alerts.count, "{n} active alert", "{n} active alerts"), }; } if (myWork && myWork.needsAttention > 0) { badges["/my-work"] = { text: String(myWork.needsAttention), className: "bg-blue text-blue-fg", title: tn(myWork.needsAttention, "{n} thing of yours wants a look: handed to you, about to run out, or still going", "{n} things of yours want a look: handed to you, about to run out, or still going"), }; } if (maintenance.length > 0) { badges["/maintenance"] = { text: String(maintenance.length), className: "bg-blue text-blue-fg", title: tn(maintenance.length, "{n} maintenance window open", "{n} maintenance windows open"), }; } function toggleTheme() { const next: Theme = theme === "dark" ? "light" : "dark"; setTheme(next); setThemeState(next); } return (
{ e.preventDefault(); mainRef.current?.focus(); }} > {t("Skip to content")}
{announcement}
{away && away.away.state !== "none" && away.away.until && (
{away.away.state === "planned" ? t("Away from {from} until {until}", { from: formatDateTime(new Date(away.away.from!)), until: formatDateTime(new Date(away.away.until)) }) : t("Away until {until}", { until: formatDateTime(new Date(away.away.until)) })} {away.away.note ? ` — ${away.away.note}` : ""}.{" "} {away.away.state === "active" ? `${t("Notifications are held")}${away.away.criticalThrough ? ` ${t("(critical alerts still come through)")}` : ""}${away.held > 0 ? ` — ${t("{n} so far", { n: away.held })}` : ""}. ` : ""} {user.role === "admin" ? t("Manage") : t("Details")}
)} {maintenance.length > 0 && (
{t("Maintenance — alerts silenced for")}{" "} {maintenance.length <= 3 ? maintenance.map((w) => t("{name} ({time} left)", { name: w.targetName, time: formatRemaining(w.endsAt) })).join(", ") : t("{names} and {n} more (the last ends in {time})", { names: maintenance.slice(0, 3).map((w) => w.targetName).join(", "), n: maintenance.length - 3, time: formatRemaining(maintenance.reduce((latest, w) => (w.endsAt > latest ? w.endsAt : latest), maintenance[0].endsAt)), })} .{" "} {t("Manage")}
)} {crumbs.length > 0 && ( )} {children}
); }