A small translation system (the English text is its own key, so anything without a Swedish entry stays English) and a Language switch in the user menu, saved on the account (users.language) and following the browser when no choice has been made. Swedish covers the menu, shared parts (search, tables, dialogs, relative times), the sign-in page and the everyday pages: Dashboard, Alerts, Servers, Updates, Maintenance, My work, Coming up, To do, Integrations and the display settings. Server-written messages stay English for now. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
456 lines
20 KiB
TypeScript
456 lines
20 KiB
TypeScript
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<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());
|
||
// 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<MaintenanceWindow[]>([]);
|
||
const [away, setAway] = useState<AwayView | null>(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<HTMLElement>(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<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);
|
||
};
|
||
}, []);
|
||
|
||
// 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<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: 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 (
|
||
<div className={`page ${rail ? "sidebar-rail" : ""}`}>
|
||
<a
|
||
className="skip-link"
|
||
href="#main"
|
||
onClick={(e) => {
|
||
e.preventDefault();
|
||
mainRef.current?.focus();
|
||
}}
|
||
>
|
||
{t("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={t("Toggle navigation")}
|
||
>
|
||
<IconMenu2 size={20} />
|
||
</button>
|
||
<h1 className="navbar-brand navbar-brand-autodark">
|
||
<NavLink to="/" aria-label="Homelab Manager">
|
||
<img className="rail-mark" src="/icon-192.png" alt="" width={44} height={44} />
|
||
<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>
|
||
<SidebarNav nav={nav} pathname={pathname} badges={badges} openGroups={openGroups} onToggleGroup={toggleGroup} rail={rail} onNavigate={() => setSidebarOpen(false)} />
|
||
<div className="navbar-footer px-3 user-menu" ref={menuRef}>
|
||
<button
|
||
type="button"
|
||
className="rail-toggle d-none d-lg-flex"
|
||
aria-expanded={!collapsed}
|
||
aria-label={collapsed ? t("Widen the sidebar") : t("Narrow the sidebar to icons")}
|
||
title={collapsed ? t("Widen the sidebar ([)") : t("Narrow the sidebar to icons ([)")}
|
||
onClick={() => setCollapsed((c) => !c)}
|
||
>
|
||
{collapsed ? <IconChevronsRight size={16} /> : <IconChevronsLeft size={16} />}
|
||
<span className="rail-toggle-text">{t("Narrow sidebar")}</span>
|
||
</button>
|
||
{menuOpen && (
|
||
<div className="user-menu-list" role="menu">
|
||
<div className="user-menu-density" role="group" aria-label={t("How tightly pages are packed")}>
|
||
<span className="small opacity-75">{t("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);
|
||
}}
|
||
>
|
||
{t(d.label)}
|
||
</button>
|
||
))}
|
||
</div>
|
||
</div>
|
||
<div className="user-menu-density" role="group" aria-label={t("Language")}>
|
||
<span className="small opacity-75">{t("Language")}</span>
|
||
<div className="btn-group btn-group-sm w-100">
|
||
{LANGUAGES.map((l) => (
|
||
<button
|
||
key={l.code}
|
||
type="button"
|
||
lang={l.code}
|
||
className={`btn ${getLanguage() === l.code ? "active" : ""}`}
|
||
aria-pressed={getLanguage() === l.code}
|
||
onClick={() => {
|
||
// Saved on the account so it follows this person; the screen is drawn again in the new language at once.
|
||
setLanguage(l.code);
|
||
void api.me.setLanguage(l.code).catch(() => undefined);
|
||
}}
|
||
>
|
||
{l.name}
|
||
</button>
|
||
))}
|
||
</div>
|
||
</div>
|
||
<button type="button" className="user-menu-item" role="menuitem" onClick={toggleTheme}>
|
||
{theme === "dark" ? <IconSun size={16} /> : <IconMoon size={16} />}
|
||
{theme === "dark" ? t("Light mode") : t("Dark mode")}
|
||
</button>
|
||
<NavLink
|
||
to="/privacy"
|
||
className="user-menu-item"
|
||
role="menuitem"
|
||
onClick={() => {
|
||
setMenuOpen(false);
|
||
setSidebarOpen(false);
|
||
}}
|
||
>
|
||
<IconShieldLock size={16} />
|
||
{t("Privacy")}
|
||
</NavLink>
|
||
<NavLink
|
||
to="/api-tokens"
|
||
className="user-menu-item"
|
||
role="menuitem"
|
||
onClick={() => {
|
||
setMenuOpen(false);
|
||
setSidebarOpen(false);
|
||
}}
|
||
>
|
||
<IconKey size={16} />
|
||
{t("API tokens")}
|
||
</NavLink>
|
||
<NavLink
|
||
to="/wall"
|
||
className="user-menu-item"
|
||
role="menuitem"
|
||
onClick={() => {
|
||
setMenuOpen(false);
|
||
setSidebarOpen(false);
|
||
}}
|
||
>
|
||
<IconDeviceDesktop size={16} />
|
||
{t("Wall display")}
|
||
</NavLink>
|
||
<a className="user-menu-item" role="menuitem" href="/auth/logout">
|
||
<IconLogout size={16} />
|
||
{t("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)}
|
||
>
|
||
<Avatar name={user.name ?? user.email ?? user.sub} src={user.avatarUrl} />
|
||
<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">
|
||
{away && away.away.state !== "none" && away.away.until && (
|
||
<div className="alert alert-info d-flex align-items-center gap-2">
|
||
<IconPlaneDeparture size={18} />
|
||
<div>
|
||
{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 })}` : ""}. ` : ""}
|
||
<Link to="/settings/notifications?tab=when">{user.role === "admin" ? t("Manage") : t("Details")}</Link>
|
||
</div>
|
||
</div>
|
||
)}
|
||
{maintenance.length > 0 && (
|
||
<div className="alert alert-warning d-flex align-items-center gap-2">
|
||
<IconTool size={18} />
|
||
<div>
|
||
{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)),
|
||
})}
|
||
.{" "}
|
||
<Link to="/maintenance">{t("Manage")}</Link>
|
||
</div>
|
||
</div>
|
||
)}
|
||
{crumbs.length > 0 && (
|
||
<nav aria-label={t("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>
|
||
);
|
||
}
|