import { useEffect, useRef, useState, type ReactNode } from "react"; import { Link, NavLink, useLocation } from "react-router-dom"; import { IconMenu2, IconSun, IconMoon, IconShieldLock, IconTool, IconChevronUp, IconLogout, IconDeviceDesktop } from "@tabler/icons-react"; import { api, type CurrentUser, type MaintenanceWindow } from "../api/client"; import { isCurrent, isGroup, visibleNav, type NavGroup } from "./nav"; 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 { useStackedTables } from "../hooks/useStackedTables"; import { useShortcuts } from "../hooks/useShortcuts"; import { useFormLabels } from "../hooks/useFormLabels"; import ShortcutHelp from "../components/ShortcutHelp"; import { useBreadcrumbTailValue } from "../utils/breadcrumb"; interface NavBadge { text: string; className: string; title: string; } /** Up to two initials for the little avatar in the user menu. */ function initialsOf(name: string): string { const words = name.replace(/@.*$/, "").split(/[\s._-]+/).filter(Boolean); return (words.length > 1 ? words[0][0] + words[1][0] : (words[0] ?? "?").slice(0, 2)).toUpperCase(); } 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()); const [maintenance, setMaintenance] = useState([]); const environment = useEnvironment(); useStackedTables(); useShortcuts(user); useFormLabels(); const mainRef = useRef(null); const [announcement, setAnnouncement] = useState(""); const firstRoute = useRef(true); const breadcrumbTail = useBreadcrumbTailValue(); const { report } = useAlertsReport(); 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); }; }, []); 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: entry.label }, breadcrumbTail ? { label: leaf.label, to: leaf.to } : { label: 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: `${alerts.count} active alert${alerts.count === 1 ? "" : "s"}`, }; } if (maintenance.length > 0) { badges["/maintenance"] = { text: String(maintenance.length), className: "bg-blue text-blue-fg", title: `${maintenance.length} maintenance window${maintenance.length === 1 ? "" : "s"} open`, }; } const badgeOf = (to: string) => { const b = badges[to]; return b ? ( {b.title} ) : null; }; function toggleTheme() { const next: Theme = theme === "dark" ? "light" : "dark"; setTheme(next); setThemeState(next); } return (
{ e.preventDefault(); mainRef.current?.focus(); }} > Skip to content
{announcement}
{maintenance.length > 0 && (
Maintenance — alerts silenced for{" "} {maintenance.map((w) => `${w.targetName} (${formatRemaining(w.endsAt)} left)`).join(", ")}.{" "} Manage
)} {crumbs.length > 0 && ( )} {children}
); }