Accessibility: skip link, labelled landmarks, visible focus, page-change announcements, sortable headings as real buttons, every label tied to its field, named row checkboxes, and text contrast raised to 4.5:1 in both themes. Command palette: also runs actions (silence/end maintenance, theme, density, wall display, sign out) and is a proper dialog; g-then-letter shortcuts, "/" and "?". Row detail panel for six tables. Server Activity card, with the health check now recording offline/back-online and disk events in the audit log. Map page of hosts, servers, DNS names and monitors. Full-screen wall display. A getting-started checklist on the admin dashboard. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
387 lines
16 KiB
TypeScript
387 lines
16 KiB
TypeScript
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<string> {
|
||
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<Theme>(() => getTheme());
|
||
const [density, setDensityState] = useState<Density>(() => getDensity());
|
||
const [maintenance, setMaintenance] = useState<MaintenanceWindow[]>([]);
|
||
const environment = useEnvironment();
|
||
useStackedTables();
|
||
useShortcuts(user);
|
||
useFormLabels();
|
||
const mainRef = useRef<HTMLElement>(null);
|
||
const [announcement, setAnnouncement] = useState("");
|
||
const firstRoute = useRef(true);
|
||
const breadcrumbTail = useBreadcrumbTailValue();
|
||
const { report } = useAlertsReport();
|
||
const [menuOpen, setMenuOpen] = useState(false);
|
||
const menuRef = useRef<HTMLDivElement>(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<Set<string>>(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<string, NavBadge> = {};
|
||
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 ? (
|
||
<span className={`badge ms-auto ${b.className}`} title={b.title}>
|
||
<span aria-hidden="true">{b.text}</span>
|
||
<span className="visually-hidden">{b.title}</span>
|
||
</span>
|
||
) : null;
|
||
};
|
||
|
||
function toggleTheme() {
|
||
const next: Theme = theme === "dark" ? "light" : "dark";
|
||
setTheme(next);
|
||
setThemeState(next);
|
||
}
|
||
|
||
return (
|
||
<div className="page">
|
||
<a
|
||
className="skip-link"
|
||
href="#main"
|
||
onClick={(e) => {
|
||
e.preventDefault();
|
||
mainRef.current?.focus();
|
||
}}
|
||
>
|
||
Skip to content
|
||
</a>
|
||
<div className="visually-hidden" role="status" aria-live="polite" aria-atomic="true">
|
||
{announcement}
|
||
</div>
|
||
<ShortcutHelp />
|
||
<aside aria-label="Homelab Manager" className="navbar navbar-vertical navbar-expand-lg" data-bs-theme={environment && isLightColor(environment.color) ? "light" : "dark"}>
|
||
<div className="container-fluid">
|
||
<button
|
||
type="button"
|
||
className="navbar-toggler"
|
||
onClick={() => setSidebarOpen((open) => !open)}
|
||
aria-label="Toggle navigation"
|
||
>
|
||
<IconMenu2 size={20} />
|
||
</button>
|
||
<h1 className="navbar-brand navbar-brand-autodark">
|
||
<NavLink to="/" aria-label="Homelab Manager">
|
||
<span className="logo-frame">
|
||
<img src="/logo.webp" alt="Homelab Manager" width={901} height={460} />
|
||
</span>
|
||
</NavLink>
|
||
{environment?.name && <span className="badge ms-2 env-badge">{environment.name}</span>}
|
||
</h1>
|
||
<div className={`navbar-collapse collapse ${sidebarOpen ? "show" : ""}`}>
|
||
<div className="px-3 pt-3 pt-lg-0">
|
||
<CommandPalette
|
||
user={user}
|
||
onToggleTheme={toggleTheme}
|
||
onSetDensity={(d) => {
|
||
setDensity(d);
|
||
setDensityState(d);
|
||
}}
|
||
/>
|
||
</div>
|
||
<nav aria-label="Main menu">
|
||
<ul className="navbar-nav pt-lg-3">
|
||
{nav.map((entry) => {
|
||
if (!isGroup(entry)) {
|
||
return (
|
||
<li className="nav-item" key={entry.to}>
|
||
<NavLink to={entry.to} end={entry.to === "/"} className="nav-link" onClick={() => setSidebarOpen(false)}>
|
||
<span className="nav-link-icon d-md-none d-lg-inline-block">{entry.icon}</span>
|
||
<span className="nav-link-title">{entry.label}</span>
|
||
{badgeOf(entry.to)}
|
||
</NavLink>
|
||
</li>
|
||
);
|
||
}
|
||
const open = openGroups.has(entry.id);
|
||
const holdsCurrent = entry.items.some((item) => isCurrent(pathname, item.to));
|
||
return (
|
||
<li className="nav-item dropdown" key={entry.id}>
|
||
<button
|
||
type="button"
|
||
className={`nav-link dropdown-toggle w-100 border-0 bg-transparent text-start ${open ? "show" : ""} ${holdsCurrent ? "active" : ""}`}
|
||
aria-expanded={open}
|
||
onClick={() => toggleGroup(entry.id)}
|
||
>
|
||
<span className="nav-link-icon d-md-none d-lg-inline-block">{entry.icon}</span>
|
||
<span className="nav-link-title">{entry.label}</span>
|
||
{/* A closed group still says that something inside it needs a look. */}
|
||
{!open &&
|
||
(() => {
|
||
const inside = entry.items.map((item) => badges[item.to]).filter(Boolean);
|
||
if (inside.length === 0) return null;
|
||
const worst = inside.find((b) => b.className.includes("bg-red")) ?? inside.find((b) => b.className.includes("bg-yellow")) ?? inside[0];
|
||
return (
|
||
<span className={`badge ms-auto me-4 ${worst.className}`} title={inside.map((b) => b.title).join(", ")}>
|
||
<span aria-hidden="true">{inside.reduce((n, b) => n + Number(b.text), 0)}</span>
|
||
<span className="visually-hidden">{inside.map((b) => b.title).join(", ")}</span>
|
||
</span>
|
||
);
|
||
})()}
|
||
</button>
|
||
<div className={`dropdown-menu ${open ? "show" : ""}`}>
|
||
{entry.items.map((item) => (
|
||
<NavLink
|
||
key={item.to}
|
||
to={item.to}
|
||
className={({ isActive }) => `dropdown-item d-flex align-items-center ${isActive ? "active" : ""}`}
|
||
onClick={() => setSidebarOpen(false)}
|
||
>
|
||
{item.label}
|
||
{badgeOf(item.to)}
|
||
</NavLink>
|
||
))}
|
||
</div>
|
||
</li>
|
||
);
|
||
})}
|
||
</ul>
|
||
</nav>
|
||
<div className="navbar-footer px-3 user-menu" ref={menuRef}>
|
||
{menuOpen && (
|
||
<div className="user-menu-list" role="menu">
|
||
<div className="user-menu-density" role="group" aria-label="How tightly pages are packed">
|
||
<span className="small opacity-75">Density</span>
|
||
<div className="btn-group btn-group-sm w-100">
|
||
{DENSITIES.map((d) => (
|
||
<button
|
||
key={d.value}
|
||
type="button"
|
||
className={`btn ${density === d.value ? "active" : ""}`}
|
||
aria-pressed={density === d.value}
|
||
onClick={() => {
|
||
setDensity(d.value);
|
||
setDensityState(d.value);
|
||
}}
|
||
>
|
||
{d.label}
|
||
</button>
|
||
))}
|
||
</div>
|
||
</div>
|
||
<button type="button" className="user-menu-item" role="menuitem" onClick={toggleTheme}>
|
||
{theme === "dark" ? <IconSun size={16} /> : <IconMoon size={16} />}
|
||
{theme === "dark" ? "Light mode" : "Dark mode"}
|
||
</button>
|
||
<NavLink
|
||
to="/privacy"
|
||
className="user-menu-item"
|
||
role="menuitem"
|
||
onClick={() => {
|
||
setMenuOpen(false);
|
||
setSidebarOpen(false);
|
||
}}
|
||
>
|
||
<IconShieldLock size={16} />
|
||
Privacy
|
||
</NavLink>
|
||
<NavLink
|
||
to="/wall"
|
||
className="user-menu-item"
|
||
role="menuitem"
|
||
onClick={() => {
|
||
setMenuOpen(false);
|
||
setSidebarOpen(false);
|
||
}}
|
||
>
|
||
<IconDeviceDesktop size={16} />
|
||
Wall display
|
||
</NavLink>
|
||
<a className="user-menu-item" role="menuitem" href="/auth/logout">
|
||
<IconLogout size={16} />
|
||
Sign out
|
||
</a>
|
||
</div>
|
||
)}
|
||
<button
|
||
type="button"
|
||
className="user-menu-toggle"
|
||
aria-haspopup="menu"
|
||
aria-expanded={menuOpen}
|
||
title={user.email ?? undefined}
|
||
onClick={() => setMenuOpen((open) => !open)}
|
||
>
|
||
<span className="avatar avatar-sm">{initialsOf(user.name ?? user.email ?? user.sub)}</span>
|
||
<span className="user-menu-who">
|
||
<span className="d-block text-truncate">{user.name ?? user.email ?? user.sub}</span>
|
||
<span className="d-block small opacity-75">{user.role}</span>
|
||
</span>
|
||
<IconChevronUp size={16} className={menuOpen ? "" : "user-menu-chevron-closed"} />
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</aside>
|
||
|
||
<div className="page-wrapper">
|
||
<main className="page-body" id="main" tabIndex={-1} ref={mainRef}>
|
||
<div className="container-xl">
|
||
{maintenance.length > 0 && (
|
||
<div className="alert alert-warning d-flex align-items-center gap-2">
|
||
<IconTool size={18} />
|
||
<div>
|
||
Maintenance — alerts silenced for{" "}
|
||
{maintenance.map((w) => `${w.targetName} (${formatRemaining(w.endsAt)} left)`).join(", ")}.{" "}
|
||
<Link to="/maintenance">Manage</Link>
|
||
</div>
|
||
</div>
|
||
)}
|
||
{crumbs.length > 0 && (
|
||
<nav aria-label="breadcrumb" className="mb-2">
|
||
<ol className="breadcrumb breadcrumb-arrows mb-0">
|
||
{crumbs.map((c, i) => (
|
||
<li key={i} className={`breadcrumb-item ${i === crumbs.length - 1 ? "active" : ""}`} aria-current={i === crumbs.length - 1 ? "page" : undefined}>
|
||
{c.to ? <Link to={c.to}>{c.label}</Link> : c.label}
|
||
</li>
|
||
))}
|
||
</ol>
|
||
</nav>
|
||
)}
|
||
{children}
|
||
</div>
|
||
</main>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|