Favourite pages that follow the user, and a narrow icon-only sidebar

A star beside each page in the sidebar pins it under "Favourites" at the top of
the menu; the list is saved with the user (users.favorites, migration 0020), so
it follows them to any browser, is offered first in the search box, and can be
changed from there too. A button at the foot of the sidebar, or the [ key,
narrows it to a strip of icons, where a group's pages open in a small menu
beside its icon and the alert and maintenance counts stay visible; the choice
is kept per browser and applies only on wide screens. Menu text on a coloured
(environment) sidebar is full strength for contrast, and menu badges sit in
line on a phone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-15 22:38:48 +02:00
1 parent 57fd4f8c52
commit 65263a64e3
17 files changed
+2736 -86

No files matched your search

+1
View File
@@ -86,6 +86,7 @@ Everyone who has signed in through Authentik. The first one becomes admin.
| `role` | text NOT NULL, default `viewer` | `admin` \| `operator` \| `viewer`. |
| `created_at` | text NOT NULL | SQLite UTC. |
| `last_login_at` | text | ISO. |
| `favorites` | text | JSON array of the page paths this person pinned to the top of their menu (`["/servers","/alerts"]`), up to 24. Follows them to any browser. |
#### `audit_log`
+10
View File
@@ -355,6 +355,16 @@ schedule needs a login on the Uptime Kuma integration (see INTEGRATIONS.md).
"Import now" is the older, simpler route: it only looks at what is in
maintenance this moment and starts a window for a duration you choose.
**Favourites and a narrow sidebar.** Hover (or tab to) a page in the sidebar and
click its star to pin it: pinned pages are listed under "Favourites" at the top
of the menu, are offered first in the search box, and follow you to any
browser, because they are saved with your user (the search box can also pin or
unpin the page you are on). A button at the foot of the sidebar — or the `[` key
— narrows it to a strip of icons for more room on a laptop screen: a group's
pages then open in a small menu beside its icon, the alert and maintenance
counts stay visible, and your choice is remembered in that browser. On a phone
the sidebar is the same slide-out menu as ever.
**Getting around.** Ctrl/Cmd+K opens a search that also runs actions: go to any
page, switch light/dark or the density, start (or end) a maintenance window on
a server, integration or DNS provider ("silence elsa"), open the wall display,
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `users` ADD `favorites` text;
File diff suppressed because it is too large. Load diff
+7
View File
@@ -141,6 +141,13 @@
"when": 1792014514813,
"tag": "0019_complex_proudstar",
"breakpoints": true
},
{
"idx": 20,
"version": "6",
"when": 1792093015342,
"tag": "0020_salty_black_tom",
"breakpoints": true
}
]
}
+2
View File
@@ -16,6 +16,8 @@ export const users = sqliteTable("users", {
.notNull()
.default(sql`(current_timestamp)`),
lastLoginAt: text("last_login_at"),
// The pages this person pinned to the top of their menu, as a JSON array of paths ("/servers", "/alerts"). It follows them to any browser.
favorites: text("favorites"),
});
// ─── Audit log ──────────────────────────────────────────────────────────────
+38 -2
View File
@@ -1,9 +1,45 @@
import { Router } from "express";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { users } from "../db/schema.js";
import { requireAuth } from "../auth/middleware.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const meRouter = Router();
/** The most pages anyone can pin: enough for a working set, not a second menu. */
export const MAX_FAVORITES = 24;
/** What is stored, read back as a list. Anything that isn't one is no favourites rather than an error. */
export function parseFavorites(stored: string | null): string[] {
if (!stored) return [];
try {
const value = JSON.parse(stored);
return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string").slice(0, MAX_FAVORITES) : [];
} catch {
return [];
}
}
meRouter.get("/", requireAuth, (req, res) => {
const { id, email, name, role, oidcSub } = req.currentUser!;
res.json({ user: { id, sub: oidcSub, email, name, role } });
const { id, email, name, role, oidcSub, favorites } = req.currentUser!;
res.json({ user: { id, sub: oidcSub, email, name, role, favorites: parseFavorites(favorites) } });
});
// Paths inside the app only: a slash, then letters, digits, dashes, underscores and further slashes. Which of them are real pages is
// the menu's business; a favourite for a page that is gone, or that this person's role can't open, is simply not shown.
const favoritesSchema = z.object({
paths: z.array(z.string().regex(/^\/[A-Za-z0-9\-_/]{0,80}$/, "Not a page path")).max(MAX_FAVORITES),
});
// Replaces the signed-in person's pinned pages. Only ever their own.
meRouter.put("/favorites", requireAuth, asyncHandler(async (req, res) => {
const parsed = favoritesSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: "invalid_body", message: `Pin up to ${MAX_FAVORITES} pages, by their path.`, details: parsed.error.flatten() });
}
const paths = [...new Set(parsed.data.paths)];
await db.update(users).set({ favorites: JSON.stringify(paths) }).where(eq(users.id, req.currentUser!.id));
res.json({ favorites: paths });
}));
+117
View File
@@ -0,0 +1,117 @@
/**
* Pinned pages follow the person: stored on their user, read with /api/me, replaced with PUT /api/me/favorites, and only ever their own.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-favorites-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { meRouter, parseFavorites, MAX_FAVORITES } = await import("../src/routes/me.js");
await runMigrations();
describe("parseFavorites", () => {
test("a stored list reads back; anything else is an empty list", () => {
assert.deepEqual(parseFavorites('["/servers","/alerts"]'), ["/servers", "/alerts"]);
assert.deepEqual(parseFavorites(null), []);
assert.deepEqual(parseFavorites("not json"), []);
assert.deepEqual(parseFavorites('{"a":1}'), []);
assert.deepEqual(parseFavorites('["/ok", 5, null]'), ["/ok"]);
});
});
describe("/api/me favourites", () => {
let app: Server;
let base = "";
let who = "anna";
before(async () => {
await db.insert(users).values([
{ oidcSub: "anna", name: "Anna", role: "viewer" },
{ oidcSub: "bob", name: "Bob", role: "operator" },
]);
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
if (who) (req as unknown as { session: unknown }).session = { user: { sub: who } };
else (req as unknown as { session: unknown }).session = {};
next();
});
a.use("/api/me", meRouter);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/me`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const put = (paths: unknown) =>
fetch(`${base}/favorites`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ paths }) });
const me = async () => (await (await fetch(base)).json()).user;
test("a new user has none", async () => {
assert.deepEqual((await me()).favorites, []);
});
test("a saved list comes back with the user, in order, with repeats removed", async () => {
const res = await put(["/servers", "/alerts", "/servers", "/settings/notifications"]);
assert.equal(res.status, 200);
assert.deepEqual((await res.json()).favorites, ["/servers", "/alerts", "/settings/notifications"]);
assert.deepEqual((await me()).favorites, ["/servers", "/alerts", "/settings/notifications"]);
});
test("it is replaced, not added to, and can be emptied", async () => {
await put(["/maintenance"]);
assert.deepEqual((await me()).favorites, ["/maintenance"]);
await put([]);
assert.deepEqual((await me()).favorites, []);
});
test("one person's list is not another's", async () => {
who = "anna";
await put(["/secrets"]);
who = "bob";
assert.deepEqual((await me()).favorites, []);
await put(["/dns"]);
who = "anna";
assert.deepEqual((await me()).favorites, ["/secrets"]);
});
test("anything that isn't an in-app path is refused, as is a list that is too long", async () => {
for (const bad of [["https://evil.example"], ["//evil.example"], ["servers"], ["/a b"], ["/<script>"], [42], ["/" + "x".repeat(200)]]) {
assert.equal((await put(bad)).status, 400, JSON.stringify(bad));
}
assert.equal((await put(Array.from({ length: MAX_FAVORITES + 1 }, (_, i) => `/p${i}`))).status, 400);
assert.equal((await fetch(`${base}/favorites`, { method: "PUT", headers: { "content-type": "application/json" }, body: "{}" })).status, 400);
assert.deepEqual((await me()).favorites, ["/secrets"], "a refused change leaves the list as it was");
});
test("without a session there is nothing to read or change", async () => {
who = "";
assert.equal((await fetch(base)).status, 401);
assert.equal((await put(["/servers"])).status, 401);
who = "anna";
});
});
+5 -1
View File
@@ -6,6 +6,8 @@ export interface CurrentUser {
email?: string;
name?: string;
role: UserRole;
/** Pages this person pinned to the top of their menu, by path. */
favorites?: string[];
}
export interface UserRecord {
@@ -1103,7 +1105,9 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
}
export const api = {
me: () => request<{ user: CurrentUser }>("/api/me"),
me: Object.assign(() => request<{ user: CurrentUser }>("/api/me"), {
setFavorites: (paths: string[]) => request<{ favorites: string[] }>("/api/me/favorites", { method: "PUT", body: JSON.stringify({ paths }) }),
}),
search: {
query: (q: string) => request<SearchResponse>(`/api/search?q=${encodeURIComponent(q)}`),
},
+37 -8
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
import { useNavigate } from "react-router-dom";
import { useLocation, useNavigate } from "react-router-dom";
import { IconSearch } from "@tabler/icons-react";
import {
api,
@@ -12,7 +12,8 @@ import {
type SearchResponse,
type SecretType,
} from "../api/client";
import { isGroup, visibleNav } from "../layout/nav";
import { isCurrent, isGroup, visibleNav, type NavLeaf } from "../layout/nav";
import { toggleFavorite, useFavorites } from "../utils/favorites";
import { SHOW_SHORTCUTS_EVENT, shortcutHintFor } from "../layout/shortcuts";
import { DENSITIES, type Density } from "../utils/density";
import { readableError } from "../utils/errors";
@@ -160,6 +161,8 @@ export default function CommandPalette({
const inputRef = useRef<HTMLInputElement>(null);
const opener = useRef<HTMLElement | null>(null);
const navigate = useNavigate();
const { pathname } = useLocation();
const favorites = useFavorites();
const canAct = user.role === "admin" || user.role === "operator";
// Ctrl/Cmd+K opens it from anywhere in the app; Escape closes it.
@@ -211,6 +214,24 @@ export default function CommandPalette({
items.push({ key: `page-${p.to}`, category: "Go to", title: p.label, subtitle: p.group, hint: shortcutHintFor(p.to) ?? undefined, path: p.to, keywords: "go open page" });
}
// Pin or unpin the page you are on.
const leaves: NavLeaf[] = [];
for (const entry of visibleNav(user.role)) {
if (isGroup(entry)) leaves.push(...entry.items);
else leaves.push(entry);
}
const here = leaves.filter((l) => isCurrent(pathname, l.to)).sort((a, b) => b.to.length - a.to.length)[0];
if (here) {
const pinned = favorites.includes(here.to);
items.push({
key: "act-favourite",
category: "Actions",
title: pinned ? `Remove ${here.label} from favourites` : `Add ${here.label} to favourites`,
subtitle: "the pages pinned at the top of your menu",
run: () => void toggleFavorite(here.to),
keywords: "favourite favorite pin star bookmark",
});
}
items.push({ key: "act-theme", category: "Actions", title: "Switch between light and dark mode", subtitle: "", run: onToggleTheme, keywords: "theme dark light mode appearance" });
for (const d of DENSITIES) {
items.push({ key: `act-density-${d.value}`, category: "Actions", title: `Density: ${d.label}`, subtitle: "How tightly pages are packed", run: () => onSetDensity(d.value), keywords: "density compact roomy spacing size" });
@@ -293,7 +314,7 @@ export default function CommandPalette({
}
return items;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [user.role, canAct, targets, windows, onToggleTheme, onSetDensity]);
}, [user.role, canAct, targets, windows, onToggleTheme, onSetDensity, pathname, favorites]);
const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
@@ -318,12 +339,19 @@ export default function CommandPalette({
// What is listed: with nothing typed, a few suggestions; otherwise every command that matches, then the data search results.
const items = useMemo(() => {
if (terms.length === 0) {
const pinned = favorites
.map((p) => commands.find((c) => c.key === `page-${p}`))
.filter((c): c is PaletteItem => !!c)
.map((c) => ({ ...c, key: `fav-${c.key}`, category: "Favourites" }));
const wanted = ["page-/", "page-/alerts", "page-/servers", "page-/maintenance", "page-/wall", "act-theme", "act-shortcuts"];
return wanted.map((k) => commands.find((c) => c.key === k)).filter((c): c is PaletteItem => !!c).slice(0, SUGGESTED_LIMIT);
const rest = wanted
.map((k) => commands.find((c) => c.key === k))
.filter((c): c is PaletteItem => !!c && !favorites.includes(c.path ?? ""));
return [...pinned, ...rest].slice(0, SUGGESTED_LIMIT + 3);
}
return [...commands.filter((c) => matches(c, terms)).slice(0, 14), ...found];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [commands, found, query]);
}, [commands, found, query, favorites]);
useEffect(() => setActiveIndex(0), [items.length, query]);
@@ -358,17 +386,18 @@ export default function CommandPalette({
return (
<button
type="button"
className="btn btn-outline-secondary btn-sm w-100 d-flex align-items-center justify-content-center gap-2"
className="btn btn-outline-secondary btn-sm w-100 d-flex align-items-center justify-content-center gap-2 palette-trigger"
onClick={() => {
opener.current = document.activeElement as HTMLElement | null;
setOpen(true);
}}
title="Search and actions (Ctrl/Cmd+K)"
aria-label="Search and actions"
aria-keyshortcuts="Control+K Meta+K"
>
<IconSearch size={16} />
Search
<kbd className="ms-auto">Ctrl K</kbd>
<span className="palette-text">Search</span>
<kbd className="ms-auto palette-text">Ctrl K</kbd>
</button>
);
}
+3
View File
@@ -50,6 +50,9 @@ export function useShortcuts(user: CurrentUser): void {
if (e.key === "g") {
waitingForSecondKey = true;
timer = setTimeout(reset, 1200);
} else if (e.key === "[") {
e.preventDefault();
window.dispatchEvent(new Event("toggle-sidebar"));
} else if (e.key === "?") {
e.preventDefault();
window.dispatchEvent(new Event(SHOW_SHORTCUTS_EVENT));
+57 -74
View File
@@ -1,8 +1,10 @@
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 { IconMenu2, IconSun, IconMoon, IconShieldLock, IconTool, IconChevronUp, IconLogout, IconDeviceDesktop, IconChevronsLeft, IconChevronsRight } from "@tabler/icons-react";
import { api, type CurrentUser, type MaintenanceWindow } from "../api/client";
import { isCurrent, isGroup, visibleNav, type NavGroup } from "./nav";
import SidebarNav, { type NavBadge } from "./SidebarNav";
import { initFavorites } from "../utils/favorites";
import { formatRemaining } from "../utils/duration";
import { getTheme, setTheme, type Theme } from "../utils/theme";
import { DENSITIES, getDensity, setDensity, type Density } from "../utils/density";
@@ -15,10 +17,19 @@ import { useFormLabels } from "../hooks/useFormLabels";
import ShortcutHelp from "../components/ShortcutHelp";
import { useBreadcrumbTailValue } from "../utils/breadcrumb";
interface NavBadge {
text: string;
className: string;
title: string;
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;
}
/** Up to two initials for the little avatar in the user menu. */
@@ -42,6 +53,33 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
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);
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 environment = useEnvironment();
useStackedTables();
@@ -158,16 +196,6 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
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);
@@ -175,7 +203,7 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
}
return (
<div className="page">
<div className={`page ${rail ? "sidebar-rail" : ""}`}>
<a
className="skip-link"
href="#main"
@@ -202,6 +230,7 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
</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>
@@ -219,65 +248,19 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
}}
/>
</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>
<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 ? "Widen the sidebar" : "Narrow the sidebar to icons"}
title={collapsed ? "Widen the sidebar ([)" : "Narrow the sidebar to icons ([)"}
onClick={() => setCollapsed((c) => !c)}
>
{collapsed ? <IconChevronsRight size={16} /> : <IconChevronsLeft size={16} />}
<span className="rail-toggle-text">Narrow sidebar</span>
</button>
{menuOpen && (
<div className="user-menu-list" role="menu">
<div className="user-menu-density" role="group" aria-label="How tightly pages are packed">
+180
View File
@@ -0,0 +1,180 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { NavLink } from "react-router-dom";
import { IconStar, IconStarFilled } from "@tabler/icons-react";
import { isCurrent, isGroup, type NavEntry, type NavGroup, type NavLeaf } from "./nav";
import { toggleFavorite, useFavorites } from "../utils/favorites";
export interface NavBadge {
text: string;
className: string;
title: string;
}
interface Flyout {
group: NavGroup;
top: number;
left: number;
}
/**
* The menu in the sidebar: this person's pinned pages first, then the pages and groups. Wide, a group opens in place; narrow (the
* icon-only strip) it opens to the side as a small menu instead, because there is no room beside an icon for a list.
*/
export default function SidebarNav({
nav,
pathname,
badges,
openGroups,
onToggleGroup,
rail,
onNavigate,
}: {
nav: NavEntry[];
pathname: string;
badges: Record<string, NavBadge>;
openGroups: Set<string>;
onToggleGroup: (id: string) => void;
/** The sidebar is the narrow, icon-only strip. */
rail: boolean;
/** Called when a link is followed (to close the menu on a phone). */
onNavigate: () => void;
}) {
const favorites = useFavorites();
const [flyout, setFlyout] = useState<Flyout | null>(null);
const flyoutRef = useRef<HTMLDivElement>(null);
const opener = useRef<HTMLElement | null>(null);
// Every page that can be pinned, by path.
const leaves = new Map<string, NavLeaf>();
for (const entry of nav) {
if (isGroup(entry)) entry.items.forEach((i) => leaves.set(i.to, i));
else leaves.set(entry.to, entry);
}
const pinned = favorites.map((p) => leaves.get(p)).filter((l): l is NavLeaf => !!l);
// The side menu goes away when the page changes, when the strip is widened, on Escape, and on a click anywhere else.
useEffect(() => setFlyout(null), [pathname, rail]);
useEffect(() => {
if (!flyout) return;
const onDown = (e: MouseEvent) => {
const t = e.target as Node;
if (flyoutRef.current?.contains(t) || opener.current?.contains(t)) return;
setFlyout(null);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
setFlyout(null);
opener.current?.focus();
}
};
document.addEventListener("mousedown", onDown);
document.addEventListener("keydown", onKey);
return () => {
document.removeEventListener("mousedown", onDown);
document.removeEventListener("keydown", onKey);
};
}, [flyout]);
const badgeOf = (to: string): ReactNode => {
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;
};
const star = (leaf: NavLeaf) => {
const on = favorites.includes(leaf.to);
const label = on ? `Remove ${leaf.label} from favourites` : `Add ${leaf.label} to favourites`;
return (
<button type="button" className="fav-star" aria-pressed={on} aria-label={label} title={label} onClick={() => void toggleFavorite(leaf.to)}>
{on ? <IconStarFilled size={16} /> : <IconStar size={16} />}
</button>
);
};
const leafRow = (leaf: NavLeaf, key: string) => (
<li className="nav-item nav-row" key={key}>
<NavLink to={leaf.to} end={leaf.to === "/"} className="nav-link" title={rail ? leaf.label : undefined} onClick={onNavigate}>
<span className="nav-link-icon d-md-none d-lg-inline-block">{leaf.icon}</span>
<span className="nav-link-title">{leaf.label}</span>
{badgeOf(leaf.to)}
</NavLink>
{star(leaf)}
</li>
);
const subRow = (leaf: NavLeaf) => (
<div className="nav-row" key={leaf.to}>
<NavLink to={leaf.to} className={({ isActive }) => `dropdown-item d-flex align-items-center ${isActive ? "active" : ""}`} onClick={onNavigate}>
{leaf.label}
{badgeOf(leaf.to)}
</NavLink>
{star(leaf)}
</div>
);
return (
<nav aria-label="Main menu">
<ul className="navbar-nav pt-lg-3">
{pinned.length > 0 && (
<li className="nav-item nav-favourites">
<div className="nav-heading" id="nav-favourites-heading">
Favourites
</div>
<ul className="navbar-nav" aria-labelledby="nav-favourites-heading">
{pinned.map((leaf) => leafRow(leaf, `fav-${leaf.to}`))}
</ul>
</li>
)}
{nav.map((entry) => {
if (!isGroup(entry)) return leafRow(entry, entry.to);
const open = openGroups.has(entry.id);
const holdsCurrent = entry.items.some((item) => isCurrent(pathname, item.to));
const inside = entry.items.map((item) => badges[item.to]).filter(Boolean);
const showSummary = (!open || rail) && inside.length > 0;
const worst = inside.find((b) => b.className.includes("bg-red")) ?? inside.find((b) => b.className.includes("bg-yellow")) ?? inside[0];
const flyOpen = rail && flyout?.group.id === entry.id;
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 ${(rail ? flyOpen : open) ? "show" : ""} ${holdsCurrent ? "active" : ""}`}
aria-expanded={rail ? flyOpen : open}
title={rail ? entry.label : undefined}
onClick={(e) => {
if (!rail) return onToggleGroup(entry.id);
if (flyOpen) return setFlyout(null);
const r = e.currentTarget.getBoundingClientRect();
opener.current = e.currentTarget;
setFlyout({ group: entry, top: r.top, left: r.right + 6 });
}}
>
<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. */}
{showSummary && (
<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(subRow)}</div>
</li>
);
})}
</ul>
{rail && flyout && (
<div ref={flyoutRef} className="rail-flyout" role="group" aria-label={flyout.group.label} style={{ top: flyout.top, left: flyout.left, maxHeight: `calc(100vh - ${flyout.top}px - 0.75rem)` }}>
<div className="rail-flyout-title">{flyout.group.label}</div>
{flyout.group.items.map(subRow)}
</div>
)}
</nav>
);
}
+1
View File
@@ -22,6 +22,7 @@ export const GO_SHORTCUTS: GoShortcut[] = [
export const OTHER_SHORTCUTS: { keys: string; label: string }[] = [
{ keys: "Ctrl K", label: "Search, and run actions (silence a server, switch theme…)" },
{ keys: "/", label: "Jump to the search box of the table on this page" },
{ keys: "[", label: "Narrow the sidebar to icons, or widen it again" },
{ keys: "?", label: "Show this list" },
{ keys: "Esc", label: "Close a dialog, the search or this list" },
];
+5 -1
View File
@@ -213,7 +213,11 @@ export default function Alerts({ user }: { user: CurrentUser }) {
<SortableTh<Row> label="Kind" sortKeyName="category" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Source" sortKeyName="source" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Alert" sortKeyName="message" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
{canSilence && <th className="w-1"></th>}
{canSilence && (
<th className="w-1">
<span className="visually-hidden">Actions</span>
</th>
)}
</tr>
</thead>
<tbody>
+255
View File
@@ -72,6 +72,29 @@ html[data-env] .navbar-vertical {
background-color: var(--hlm-env-color) !important;
}
/* The menu text is Tabler's 70%-white, fine on navy but too faint on a coloured sidebar; make it full strength there. */
html[data-env] .navbar-vertical[data-bs-theme="dark"] {
color: rgba(255, 255, 255, 0.97);
}
html[data-env] .navbar-vertical[data-bs-theme="dark"] :is(.nav-link, .dropdown-item, .nav-heading) {
color: rgba(255, 255, 255, 0.95);
}
html[data-env] .navbar-vertical[data-bs-theme="dark"] :is(.nav-link, .dropdown-item):hover,
html[data-env] .navbar-vertical[data-bs-theme="dark"] :is(.nav-link, .dropdown-item).active {
color: #fff;
}
html[data-env] .navbar-vertical[data-bs-theme="dark"] .btn-outline-secondary {
color: rgba(255, 255, 255, 0.95);
border-color: rgba(255, 255, 255, 0.55);
}
.user-menu-who .opacity-75 {
opacity: 0.92;
}
.env-badge {
background-color: #fff;
color: var(--hlm-env-color, #000);
@@ -853,6 +876,238 @@ a.map-node:focus-visible {
color: #0b5cad;
}
/* ── Favourites: pinned pages at the top of the menu, and the star that pins them. ── */
.nav-heading {
padding: 0.5rem 1rem 0.15rem;
font-size: 0.68rem;
font-weight: 600;
letter-spacing: 0.08em;
text-transform: uppercase;
opacity: 0.7;
}
.nav-favourites {
padding-bottom: 0.35rem;
margin-bottom: 0.35rem;
border-bottom: 1px solid color-mix(in srgb, currentColor 18%, transparent);
}
.nav-favourites > .navbar-nav {
padding: 0;
}
.nav-row,
.navbar-vertical .navbar-nav .nav-row {
position: relative;
display: flex;
flex-direction: row;
align-items: center;
}
.nav-row > .nav-link,
.nav-row > .dropdown-item {
flex: 1 1 auto;
min-width: 0;
}
.nav-row .badge {
align-self: center;
}
/* On a phone Tabler draws a menu badge as a superscript on the corner of the link; here it reads better in line, as on a wide screen. */
@media (max-width: 991.98px) {
.navbar-vertical .nav-link .badge {
position: static !important;
transform: none !important;
}
}
.fav-star {
display: inline-grid;
flex: 0 0 auto;
place-items: center;
width: 1.9rem;
height: 1.9rem;
margin-right: 0.25rem;
color: inherit;
cursor: pointer;
background: none;
border: 0;
border-radius: 0.3rem;
opacity: 0;
}
.nav-row:hover > .fav-star,
.nav-row:focus-within > .fav-star,
.fav-star[aria-pressed="true"],
.fav-star:focus-visible {
opacity: 0.85;
}
.fav-star[aria-pressed="true"] {
color: #fbbf24;
}
.fav-star:hover {
background: color-mix(in srgb, currentColor 14%, transparent);
opacity: 1;
}
@media (hover: none) {
.fav-star {
opacity: 0.55;
}
}
/* ── The narrow, icon-only sidebar (wide screens): a strip of icons, with a group's pages opening to the side. ── */
.rail-mark {
display: none;
}
.rail-toggle {
display: flex;
gap: 0.5rem;
align-items: center;
width: 100%;
padding: 0.35rem 0.5rem;
margin-bottom: 0.4rem;
font-size: 0.8rem;
color: inherit;
cursor: pointer;
background: none;
border: 1px solid color-mix(in srgb, currentColor 20%, transparent);
border-radius: 0.3rem;
}
.rail-toggle:hover {
background: color-mix(in srgb, currentColor 14%, transparent);
}
.rail-flyout {
position: fixed;
z-index: 1040;
min-width: 13rem;
max-width: 18rem;
padding: 0.35rem;
overflow-y: auto;
color: var(--tblr-body-color);
background: var(--tblr-bg-surface);
border: 1px solid var(--tblr-border-color);
border-radius: 0.5rem;
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.4);
}
.rail-flyout-title {
padding: 0.35rem 0.6rem 0.25rem;
font-size: 0.68rem;
font-weight: 600;
letter-spacing: 0.08em;
text-transform: uppercase;
opacity: 0.65;
}
.rail-flyout .fav-star {
opacity: 0.55;
}
@media (min-width: 992px) {
.sidebar-rail {
--tblr-sidebar-width: 4.75rem;
}
.sidebar-rail .navbar-vertical .navbar-brand {
flex-direction: column;
gap: 0.35rem;
justify-content: center;
padding: 0.75rem 0.25rem;
}
.sidebar-rail .rail-mark {
display: block;
width: 2.75rem;
height: 2.75rem;
border-radius: 0.5rem;
}
.sidebar-rail .navbar-brand .logo-frame {
display: none;
}
.sidebar-rail .navbar-brand .env-badge {
padding: 0.1rem 0.35rem;
margin: 0 !important;
font-size: 0.6rem;
}
.sidebar-rail .navbar-vertical .px-3 {
padding-right: 0.5rem !important;
padding-left: 0.5rem !important;
}
/* The words go, but stay for screen readers. */
.sidebar-rail :is(.nav-link-title, .palette-text, .rail-toggle-text, .user-menu-who) {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
}
.sidebar-rail .nav-link {
position: relative;
justify-content: center;
padding-right: 0.25rem;
padding-left: 0.25rem;
}
.sidebar-rail .nav-link-icon {
margin-right: 0 !important;
}
.sidebar-rail .nav-link .badge {
position: absolute;
top: 0.1rem;
right: 0.4rem;
padding: 0.05rem 0.3rem;
margin: 0 !important;
font-size: 0.6rem;
}
.sidebar-rail .dropdown-toggle::after,
.sidebar-rail .nav-heading,
.sidebar-rail .navbar-nav .fav-star,
.sidebar-rail .user-menu-toggle > svg {
display: none;
}
.sidebar-rail .nav-item.dropdown > .dropdown-menu {
display: none !important;
}
.sidebar-rail .palette-trigger,
.sidebar-rail .rail-toggle {
justify-content: center;
}
.sidebar-rail .user-menu-toggle {
justify-content: center;
padding: 0.3rem;
}
.sidebar-rail .user-menu-list {
position: fixed;
bottom: 0.75rem;
left: 5.1rem;
z-index: 1040;
width: 15rem;
color: var(--tblr-body-color);
background: var(--tblr-bg-surface);
border-color: var(--tblr-border-color);
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.4);
}
}
/* Sidebar submenus: a little tighter than Tabler's dropdown rows, so several open groups still fit on one screen. */
.navbar-vertical .dropdown-menu .dropdown-item {
padding-top: 0.3rem;
+58
View File
@@ -0,0 +1,58 @@
import { useSyncExternalStore } from "react";
import { api } from "../api/client";
import { readableError } from "./errors";
import { toast } from "./toast";
// The pages this person pinned to the top of the menu. They live on the user's record on the server, so they follow the person to
// any browser; here they are kept in step so the sidebar, the command palette and the star buttons all show the same list at once.
/** The same limit the server enforces. */
export const MAX_FAVORITES = 24;
let favorites: string[] = [];
const listeners = new Set<() => void>();
/** Only the answer to the latest change may overwrite the list, however the replies are ordered. */
let latest = 0;
function set(next: string[]) {
favorites = next;
for (const l of listeners) l();
}
function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
/** Loads the list the server sent with the signed-in user. Call before the menu is first drawn. */
export function initFavorites(list: string[] | undefined): void {
set([...(list ?? [])]);
}
export function useFavorites(): string[] {
return useSyncExternalStore(subscribe, () => favorites);
}
/** Pins a page, or unpins it. Shown at once; put back, with a message, if the server can't save it. */
export async function toggleFavorite(path: string): Promise<void> {
const before = favorites;
const adding = !before.includes(path);
if (adding && before.length >= MAX_FAVORITES) {
toast.info(`You can pin up to ${MAX_FAVORITES} pages. Unpin one first.`);
return;
}
const next = adding ? [...before, path] : before.filter((p) => p !== path);
set(next);
const mine = ++latest;
try {
const res = await api.me.setFavorites(next);
if (mine === latest) set(res.favorites);
} catch (err) {
if (mine === latest) {
set(before);
toast.error(`Couldn't save your favourites: ${readableError(err)}`);
}
}
}