From 587e8856a0bd8ed8588a14b33865e7b56cf48af0 Mon Sep 17 00:00:00 2001 From: Bobban Rydh Date: Sun, 8 Nov 2026 22:11:05 +0100 Subject: [PATCH] Add a setting to leave unused integration pages out of the menu Settings -> Display -> Menu: when on, the menu, command palette and shortcuts omit the pages of integration kinds nobody has added (off by default, the same for everyone). Pages useful without an integration always stay; adding an integration brings its page back at once. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 + server/src/routes/settings.ts | 2 +- server/src/services/settingsStore.ts | 4 +- server/test/menuHiding.test.ts | 170 +++++++++++++++++++++ web/src/api/client.ts | 2 + web/src/components/CommandPalette.tsx | 4 +- web/src/hooks/useMenuHiding.ts | 35 +++++ web/src/hooks/useShortcuts.ts | 4 +- web/src/layout/AppShell.tsx | 3 + web/src/layout/nav.tsx | 5 +- web/src/pages/Integrations.tsx | 2 + web/src/pages/settings/DisplaySettings.tsx | 56 ++++++- web/src/utils/navVisibility.ts | 64 ++++++++ 13 files changed, 346 insertions(+), 7 deletions(-) create mode 100644 server/test/menuHiding.test.ts create mode 100644 web/src/hooks/useMenuHiding.ts create mode 100644 web/src/utils/navVisibility.ts diff --git a/README.md b/README.md index 7bdd0bd..98f1162 100644 --- a/README.md +++ b/README.md @@ -950,6 +950,8 @@ switched by `?view=`, so a section can be linked to: an alert about a failing se **The status strip.** Under a server's name, on every section of its page, a row of figures says how it is at a glance: **Status** (online, with when it last reported — or *offline*, with when it did, and a note when Proxmox says the guest is still running, so a stopped agent is not read as a dead machine; for a server with no agent report, what Proxmox says, or that nothing has reported), **Maintenance** (only while a window on this server is on, with when it ends and why), **Alerts** (how many are open about this server and how bad — what a maintenance window, a snooze or a closing has put aside is not counted, but said — and a link to the Alerts page), **Updates** (what is waiting, how many of them security fixes, whether a reboot is needed), **Disk** (the fullest, against its own limit: green, yellow within ten points of it, red at it; a mount with its own limit is judged by that, and an ignored mount is left out), **CPU · memory** and **how long it has run** (for a guest Proxmox reads, or from an agent of version 8 on Linux, 7 on Windows, which say it in every report; left out while the server is offline, since it is then no longer how long it has been up). A figure nothing is known for is left out or says so — it is never filled in. It uses what the page already has plus the alerts and the maintenance windows, read again whenever the page is (the *Refresh* button). Everyone signed in sees it. +**A shorter menu for a smaller homelab.** The menu has a page for every kind of integration the app can read, whether or not you run it. **Settings → Display → Menu → Hide the pages of integrations I have not added** (off until you switch it on, the same for everyone) leaves out of the menu, the command palette and the `g`-shortcuts the pages whose integrations are not in **Administration → Integrations**: Gitea, n8n, Grafana … as the list under the switch says (a disabled integration still counts as added; any one of Sonarr, Radarr, Lidarr, Readarr or Prowlarr keeps *Media managers*, and a Proxmox or a Backup Server keeps *Proxmox backups*). Pages that are useful without an integration — Servers, Alerts, DNS, Endpoints, Secrets, Inventory and the rest — always stay, a group with nothing left disappears, and a hidden page is still there by its address. Adding an integration brings its page back at once. + **Away mode, and critical alerts through the night.** For a one-person homelab, "on call" is about *when you can be reached*. **Settings → Notifications → When → Away** is a one-off "I'm away until Sunday evening": notifications are held while it lasts (a banner on every page says so and counts them) and sent as **one digest** when it ends — at the time you gave, or when you press *I'm back* — so a week away is one message to read, not a buzzing phone. **Critical** alerts (a server down, a disk full, mains power lost) can still come through at once, which is the default; untick it for true silence. You can plan one ahead (start later) and add a note. **Quiet hours** got the same option, *Still send critical alerts*, off by default: a full disk at 03:00 is diff --git a/server/src/routes/settings.ts b/server/src/routes/settings.ts index 695b7f1..10b2bd0 100644 --- a/server/src/routes/settings.ts +++ b/server/src/routes/settings.ts @@ -138,7 +138,7 @@ const updateSchema = z.object({ providerColors: z.record(z.string()).optional(), integrationColors: z.record(z.string()).optional(), display: z - .object({ dateFormat: z.enum(["ymd", "dmy", "mdy"]), timeFormat: z.enum(["24h", "12h"]), pageSize: z.number().int().min(5).max(500) }) + .object({ dateFormat: z.enum(["ymd", "dmy", "mdy"]), timeFormat: z.enum(["24h", "12h"]), pageSize: z.number().int().min(5).max(500), hideUnusedPages: z.boolean() }) .partial() .optional(), logRetention: z diff --git a/server/src/services/settingsStore.ts b/server/src/services/settingsStore.ts index 5dc1902..33c21bc 100644 --- a/server/src/services/settingsStore.ts +++ b/server/src/services/settingsStore.ts @@ -102,6 +102,8 @@ export interface DisplaySettings { timeFormat: TimeFormat; /** Rows per page for every paginated table in the app. */ pageSize: number; + /** Leave out of the menu the pages of integrations nobody has added (the page is still there by its address). */ + hideUnusedPages: boolean; } export interface LogRetentionSettings { @@ -354,7 +356,7 @@ const DEFAULTS: AppSettings = { }, providerColors: {}, integrationColors: {}, - display: { dateFormat: "ymd", timeFormat: "24h", pageSize: 20 }, + display: { dateFormat: "ymd", timeFormat: "24h", pageSize: 20, hideUnusedPages: false }, logRetention: { enabled: false, retentionDays: 90, intervalHours: 24 }, quietHours: { enabled: false, start: "22:00", end: "07:00", criticalThrough: false }, away: { from: null, until: null, criticalThrough: true, note: "" }, diff --git a/server/test/menuHiding.test.ts b/server/test/menuHiding.test.ts new file mode 100644 index 0000000..a6ede06 --- /dev/null +++ b/server/test/menuHiding.test.ts @@ -0,0 +1,170 @@ +/** + * Leaving out of the menu the pages of integrations nobody has added: which pages belong to which kinds, what is left out for what has been added, the store the menu, + * the command palette and the shortcuts share, and the Display setting that switches it on (off until someone does). + * + * Run with: npm test --workspace server + */ +import { test, describe, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, 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-menu-")); +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 { settingsRouter } = await import("../src/routes/settings.js"); +const { PAGE_KINDS, pagePath, unusedPages, setHiddenPages, getHiddenPages, isPageHidden, subscribeHiddenPages } = await import("../../web/src/utils/navVisibility.js"); +const { TYPE_PAGES } = await import("../../web/src/utils/integrationTypes.js"); + +await runMigrations(); + +const navSource = readFileSync(join(import.meta.dirname, "..", "..", "web", "src", "layout", "nav.tsx"), "utf8"); +const navPaths = new Set([...navSource.matchAll(/to: "([^"]+)"/g)].map((m) => pagePath(m[1]))); + +describe("which pages belong to an integration", () => { + test("a path loses its query", () => { + assert.equal(pagePath("/backups?view=pbs"), "/backups"); + assert.equal(pagePath("/media"), "/media"); + assert.equal(pagePath("/x#top"), "/x"); + }); + + test("every kind of integration has its page, and every such page is one in the menu", () => { + for (const page of Object.values(TYPE_PAGES)) assert.ok(PAGE_KINDS[pagePath(page)], `${page} has no kinds`); + for (const page of Object.keys(PAGE_KINDS)) assert.ok(navPaths.has(page), `${page} is not a page in the menu`); + }); + + test("pages shared by several kinds list them all; the backups page also reads Proxmox", () => { + assert.deepEqual([...PAGE_KINDS["/media"]].sort(), ["lidarr", "prowlarr", "radarr", "readarr", "sonarr"]); + assert.deepEqual([...PAGE_KINDS["/downloads"]].sort(), ["qbittorrent", "sabnzbd"]); + assert.deepEqual([...PAGE_KINDS["/backups"]].sort(), ["pbs", "proxmox"]); + }); + + test("pages with uses of their own are never among them", () => { + for (const page of ["/", "/alerts", "/servers", "/dns", "/secrets", "/duplicati", "/ports", "/endpoints", "/settings", "/integrations", "/inventory", "/maintenance"]) { + assert.equal(PAGE_KINDS[page], undefined, page); + } + }); +}); + +describe("what is left out for what has been added", () => { + test("nothing added: every integration page is left out, and only those", () => { + const left = unusedPages([]); + assert.deepEqual([...left].sort(), Object.keys(PAGE_KINDS).sort()); + assert.ok(!left.has("/servers")); + }); + + test("a kind added brings its page back, and nothing else", () => { + const left = unusedPages(["jellyfin"]); + assert.ok(!left.has("/jellyfin")); + assert.ok(left.has("/gitea") && left.has("/proxmox")); + }); + + test("any one of the kinds behind a page is enough", () => { + assert.ok(!unusedPages(["lidarr"]).has("/media")); + assert.ok(!unusedPages(["sabnzbd"]).has("/downloads")); + assert.ok(unusedPages(["sabnzbd"]).has("/media")); + }); + + test("a Proxmox keeps the backups page, a Backup Server does too, neither leaves it out", () => { + assert.ok(!unusedPages(["proxmox"]).has("/backups")); + assert.ok(!unusedPages(["pbs"]).has("/backups")); + assert.ok(unusedPages(["gitea"]).has("/backups")); + }); + + test("a kind the app does not know is no reason to keep anything", () => { + assert.deepEqual([...unusedPages(["martian"])].sort(), Object.keys(PAGE_KINDS).sort()); + }); +}); + +describe("the store the menu shares", () => { + test("it starts leaving nothing out, and a link with a query is judged by its path", () => { + assert.equal(getHiddenPages().size, 0); + assert.equal(isPageHidden("/gitea"), false); + setHiddenPages(["/backups"]); + assert.equal(isPageHidden("/backups?view=pbs"), true); + assert.equal(isPageHidden("/servers"), false); + setHiddenPages([]); + }); + + test("listeners hear of a change, not of the same set again, and can stop listening", () => { + let heard = 0; + const stop = subscribeHiddenPages(() => heard++); + setHiddenPages(["/gitea", "/n8n"]); + assert.equal(heard, 1); + setHiddenPages(["/n8n", "/gitea"]); + assert.equal(heard, 1, "the same pages in another order are no change"); + setHiddenPages(["/gitea"]); + assert.equal(heard, 2); + stop(); + setHiddenPages([]); + assert.equal(heard, 2); + }); +}); + +describe("the Display setting", () => { + let app: Server; + let base = ""; + let sub = "admin"; + + before(async () => { + await db.insert(users).values([ + { oidcSub: "admin", name: "Ada", role: "admin" }, + { oidcSub: "viewer", name: "Vic", role: "viewer" }, + ]); + const a = express(); + a.use(express.json()); + a.use((req, _res, next) => { + (req as unknown as { session: unknown }).session = { user: { sub } }; + next(); + }); + a.use("/api/settings", settingsRouter); + app = await new Promise((resolve) => { + const x = a.listen(0, "127.0.0.1", () => resolve(x)); + }); + base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/settings`; + }); + after(() => { + app.close(); + try { + rmSync(dir, { recursive: true, force: true }); + } catch { + // Windows keeps the database file locked until the process exits. + } + }); + + const display = async () => ((await (await fetch(`${base}/display`)).json()) as { display: { hideUnusedPages: boolean; pageSize: number } }).display; + const put = (body: unknown) => fetch(base, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + + test("it is off until somebody switches it on, and anyone signed in can read it", async () => { + sub = "viewer"; + assert.equal((await display()).hideUnusedPages, false); + sub = "admin"; + }); + + test("an administrator switches it on and off, and saving the other display settings does not undo it", async () => { + assert.equal((await put({ display: { hideUnusedPages: true } })).status, 200); + assert.equal((await display()).hideUnusedPages, true); + assert.equal((await put({ display: { pageSize: 50 } })).status, 200); + const d = await display(); + assert.deepEqual([d.hideUnusedPages, d.pageSize], [true, 50]); + assert.equal((await put({ display: { hideUnusedPages: false } })).status, 200); + assert.equal((await display()).hideUnusedPages, false); + }); + + test("it must be true or false, and a viewer may not change it", async () => { + assert.equal((await put({ display: { hideUnusedPages: "yes" } })).status, 400); + sub = "viewer"; + assert.equal((await put({ display: { hideUnusedPages: true } })).status, 403); + sub = "admin"; + assert.equal((await display()).hideUnusedPages, false); + }); +}); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 1e0c957..1e9d1b6 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -560,6 +560,8 @@ export type DateFormat = "ymd" | "dmy" | "mdy"; export type TimeFormat = "24h" | "12h"; export interface DisplaySettings { + /** Leave out of the menu the pages of integrations nobody has added. */ + hideUnusedPages: boolean; dateFormat: DateFormat; timeFormat: TimeFormat; pageSize: number; diff --git a/web/src/components/CommandPalette.tsx b/web/src/components/CommandPalette.tsx index 1d723c2..2e3b7ad 100644 --- a/web/src/components/CommandPalette.tsx +++ b/web/src/components/CommandPalette.tsx @@ -24,6 +24,7 @@ import { DENSITIES, type Density } from "../utils/density"; import { readableError } from "../utils/errors"; import { toast } from "../utils/toast"; import { SETTINGS_INDEX } from "../utils/settingsIndex"; +import { useHiddenPages } from "../hooks/useMenuHiding"; import { SHOW_SETUP_EVENT } from "./SetupGuide"; const SECRET_TYPE_LABELS: Record = { @@ -160,6 +161,7 @@ export default function CommandPalette({ const navigate = useNavigate(); const { pathname } = useLocation(); const favorites = useFavorites(); + const hiddenPages = useHiddenPages(); const canAct = user.role === "admin" || user.role === "operator"; // Ctrl/Cmd+K opens it from anywhere in the app; Escape closes it. @@ -382,7 +384,7 @@ export default function CommandPalette({ } return items; // eslint-disable-next-line react-hooks/exhaustive-deps - }, [user.role, user.id, canAct, targets, windows, alertsToAck, updatable, assets, onToggleTheme, onSetDensity, pathname, favorites]); + }, [user.role, user.id, canAct, targets, windows, alertsToAck, updatable, assets, onToggleTheme, onSetDensity, pathname, favorites, hiddenPages]); const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean); diff --git a/web/src/hooks/useMenuHiding.ts b/web/src/hooks/useMenuHiding.ts new file mode 100644 index 0000000..8fd619f --- /dev/null +++ b/web/src/hooks/useMenuHiding.ts @@ -0,0 +1,35 @@ +import { useEffect, useSyncExternalStore } from "react"; +import { api } from "../api/client"; +import { getHiddenPages, setHiddenPages, subscribeHiddenPages, unusedPages } from "../utils/navVisibility"; + +/** Said by the pages that change what the menu depends on (adding or removing an integration, the Display setting), so it is worked out again at once. */ +export const MENU_CHANGED = "menu-changed"; + +/** Which pages the menu leaves out, as a set that changes when it does — for a component that draws or lists the menu. */ +export function useHiddenPages(): ReadonlySet { + return useSyncExternalStore(subscribeHiddenPages, getHiddenPages, getHiddenPages); +} + +/** + * Keeps the menu's hidden pages up to date: if the Display setting asks for pages of integrations nobody has added to be left out, they are; otherwise nothing is. + * Used once, by the shell. When it cannot find out (offline, an error) it leaves the menu as it was — never hiding a page on a guess. + */ +export function useMenuHiding(): void { + useEffect(() => { + let cancelled = false; + const load = () => + Promise.all([api.settings.display(), api.integrations.list()]) + .then(([d, i]) => { + if (!cancelled) setHiddenPages(d.display.hideUnusedPages ? unusedPages(i.integrations.map((x) => x.type)) : []); + }) + .catch(() => {}); + void load(); + const timer = setInterval(load, 5 * 60_000); + window.addEventListener(MENU_CHANGED, load); + return () => { + cancelled = true; + clearInterval(timer); + window.removeEventListener(MENU_CHANGED, load); + }; + }, []); +} diff --git a/web/src/hooks/useShortcuts.ts b/web/src/hooks/useShortcuts.ts index e56c9d6..7a8b924 100644 --- a/web/src/hooks/useShortcuts.ts +++ b/web/src/hooks/useShortcuts.ts @@ -3,6 +3,7 @@ import { useNavigate } from "react-router-dom"; import type { CurrentUser } from "../api/client"; import { visibleNav, isGroup } from "../layout/nav"; import { GO_SHORTCUTS, SHOW_SHORTCUTS_EVENT } from "../layout/shortcuts"; +import { useHiddenPages } from "./useMenuHiding"; /** Whether the keyboard is typing into something, in which case a letter is a letter and not a shortcut. */ function isTyping(target: EventTarget | null): boolean { @@ -18,6 +19,7 @@ function isTyping(target: EventTarget | null): boolean { */ export function useShortcuts(user: CurrentUser): void { const navigate = useNavigate(); + const hiddenPages = useHiddenPages(); useEffect(() => { const allowed = new Set(["/", "/wall"]); @@ -80,5 +82,5 @@ export function useShortcuts(user: CurrentUser): void { window.removeEventListener("keydown", onKeyDown); reset(); }; - }, [user.role, navigate]); + }, [user.role, navigate, hiddenPages]); } diff --git a/web/src/layout/AppShell.tsx b/web/src/layout/AppShell.tsx index 78f496d..5fea536 100644 --- a/web/src/layout/AppShell.tsx +++ b/web/src/layout/AppShell.tsx @@ -17,6 +17,7 @@ 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"; @@ -85,6 +86,8 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr 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); diff --git a/web/src/layout/nav.tsx b/web/src/layout/nav.tsx index 517a49b..cf66fea 100644 --- a/web/src/layout/nav.tsx +++ b/web/src/layout/nav.tsx @@ -64,6 +64,7 @@ import { IconReportAnalytics, } from "@tabler/icons-react"; import type { CurrentUser } from "../api/client"; +import { isPageHidden } from "../utils/navVisibility"; // The menu: what pages there are, how they are grouped, and which role is needed to see each. Used by the sidebar, the command // palette, the keyboard shortcuts and the breadcrumbs, so they always agree. @@ -222,9 +223,9 @@ export const NAV: NavEntry[] = [ const roleRank: Record = { viewer: 0, operator: 1, admin: 2 }; -/** What this role can see: pages it isn't allowed are dropped, an emptied group disappears, and a group down to one page becomes that page's own link. */ +/** What this role can see: pages it isn't allowed are dropped, so are pages of integrations nobody has added when the Display setting says to leave those out, an emptied group disappears, and a group down to one page becomes that page's own link. */ export function visibleNav(role: CurrentUser["role"]): NavEntry[] { - const allowed = (leaf: NavLeaf) => !leaf.minRole || roleRank[role] >= roleRank[leaf.minRole]; + const allowed = (leaf: NavLeaf) => (!leaf.minRole || roleRank[role] >= roleRank[leaf.minRole]) && !isPageHidden(leaf.to); const out: NavEntry[] = []; for (const entry of NAV) { if (!isGroup(entry)) { diff --git a/web/src/pages/Integrations.tsx b/web/src/pages/Integrations.tsx index 07cbeef..ac0a0d8 100644 --- a/web/src/pages/Integrations.tsx +++ b/web/src/pages/Integrations.tsx @@ -7,6 +7,7 @@ import DiagLogView from "../views/DiagLogView"; import IntegrationEditForm from "../components/IntegrationEditForm"; import TableToolbar from "../components/TableToolbar"; import { useTableSearch } from "../hooks/useTableSearch"; +import { MENU_CHANGED } from "../hooks/useMenuHiding"; import { downloadCsv } from "../utils/csv"; import { confirmDialog } from "../utils/dialogs"; import { ErrorNotice } from "../components/Notice"; @@ -109,6 +110,7 @@ function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode } .list() .then((res) => { setIntegrations(res.integrations); + window.dispatchEvent(new Event(MENU_CHANGED)); // the menu may leave out pages of integrations nobody has added // Deep-link from global search (?editId=) — jump straight to that integration's edit form. const editId = Number(searchParams.get("editId")); const target = res.integrations.find((i) => i.id === editId); diff --git a/web/src/pages/settings/DisplaySettings.tsx b/web/src/pages/settings/DisplaySettings.tsx index 25b5ff3..e2742bd 100644 --- a/web/src/pages/settings/DisplaySettings.tsx +++ b/web/src/pages/settings/DisplaySettings.tsx @@ -2,6 +2,9 @@ import { useEffect, useState } from "react"; import { api, type AppSettings, type DateFormat, type TimeFormat } from "../../api/client"; import { setDateTimeSettings } from "../../utils/date"; import { setPageSize } from "../../utils/pageSize"; +import { MENU_CHANGED } from "../../hooks/useMenuHiding"; +import { PAGE_KINDS, unusedPages } from "../../utils/navVisibility"; +import { NAV, isGroup } from "../../layout/nav"; import { ErrorNotice } from "../../components/Notice"; import { PageSkeleton } from "../../components/Skeleton"; @@ -21,6 +24,9 @@ export default function DisplaySettings() { const [dateFormat, setDateFormatState] = useState("ymd"); const [timeFormat, setTimeFormatState] = useState("24h"); const [pageSize, setPageSizeState] = useState(20); + const [hideUnusedPages, setHideUnusedPages] = useState(false); + // The kinds of integration that have been added, to say which pages the setting would leave out. + const [added, setAdded] = useState(null); const [saving, setSaving] = useState(false); const [saved, setSaved] = useState(false); const [saveError, setSaveError] = useState(null); @@ -32,9 +38,14 @@ export default function DisplaySettings() { setDateFormatState(res.settings.display.dateFormat); setTimeFormatState(res.settings.display.timeFormat); setPageSizeState(res.settings.display.pageSize); + setHideUnusedPages(res.settings.display.hideUnusedPages); }) .catch((err) => setLoadError(err instanceof Error ? err.message : String(err))) .finally(() => setLoading(false)); + api.integrations + .list() + .then((res) => setAdded(res.integrations.map((i) => i.type))) + .catch(() => {}); }, []); async function handleSave() { @@ -42,9 +53,10 @@ export default function DisplaySettings() { setSaveError(null); setSaved(false); try { - const res = await api.settings.update({ display: { dateFormat, timeFormat, pageSize } }); + const res = await api.settings.update({ display: { dateFormat, timeFormat, pageSize, hideUnusedPages } }); setDateTimeSettings(res.settings.display); setPageSize(res.settings.display.pageSize); + window.dispatchEvent(new Event(MENU_CHANGED)); setSaved(true); setTimeout(() => setSaved(false), 3000); } catch (err) { @@ -56,6 +68,8 @@ export default function DisplaySettings() { if (loading) return ; + // The menu's pages the setting would leave out, by name, with what has been added so far. + const wouldHide = added === null ? null : menuLabelsOf(unusedPages(added)); const dateExample = DATE_FORMAT_OPTIONS.find((o) => o.value === dateFormat)?.example ?? ""; return ( @@ -138,7 +152,47 @@ export default function DisplaySettings() { + +
+
+
+

Menu

+
+
+ +
+ A page for something that is not in your homelab (Jellyfin, Gitea, n8n …) is left out of the menu, the command palette and the keyboard shortcuts until you add that integration under + Administration → Integrations. It is still there by its address, and pages that are useful without an integration (Servers, Alerts, DNS, Secrets …) always stay. A group with nothing left disappears. +
+ {wouldHide !== null && ( +
+ {wouldHide.length === 0 ? ( + With what you have added, there is nothing to leave out. + ) : ( + <> + {hideUnusedPages ? "Left out now" : "Would leave out"} ({wouldHide.length}): + {wouldHide.join(", ")} + + )} +
+ )} +
+
+
); } + +/** The menu's names for pages, in the menu's order, for the pages given (by path). */ +function menuLabelsOf(pages: Set): string[] { + const out: string[] = []; + for (const entry of NAV) { + const leaves = isGroup(entry) ? entry.items : [entry]; + for (const leaf of leaves) if (pages.has(leaf.to.split("?")[0]) && PAGE_KINDS[leaf.to.split("?")[0]]) out.push(leaf.label); + } + return out; +} diff --git a/web/src/utils/navVisibility.ts b/web/src/utils/navVisibility.ts new file mode 100644 index 0000000..bf78995 --- /dev/null +++ b/web/src/utils/navVisibility.ts @@ -0,0 +1,64 @@ +import type { IntegrationType } from "../api/client"; +import { TYPE_PAGES } from "./integrationTypes"; + +/** + * Which pages of the menu belong to an integration, so that a homelab without that integration need not see them. + * + * A page is only ever hidden when it exists for the sake of integrations (Proxmox, Jellyfin, Gitea …). A page that has uses of its own + * (Servers, Alerts, DNS, Secrets, Duplicati …) is never in this map, so it is never hidden. The page is still there by its address either way. + */ + +/** The path of a menu link, without a query ("/backups?view=pbs" is "/backups"). */ +export function pagePath(to: string): string { + const cut = to.search(/[?#]/); + return cut === -1 ? to : to.slice(0, cut); +} + +/** For each page, the kinds of integration that give it something to show. Built from the page each kind gets, plus what a page also reads from elsewhere. */ +export const PAGE_KINDS: Record = (() => { + const out: Record = {}; + for (const [type, page] of Object.entries(TYPE_PAGES) as [IntegrationType, string][]) { + const path = pagePath(page); + (out[path] ??= []).push(type); + } + // The backups page lists Proxmox's own backups as well as the Backup Server's, so a Proxmox is reason enough for it. + (out["/backups"] ??= []).push("proxmox"); + return out; +})(); + +/** The pages with nothing to show: every one of the kinds behind it is missing from what has been added. Pure. */ +export function unusedPages(added: Iterable): Set { + const have = new Set(added); + const hidden = new Set(); + for (const [page, kinds] of Object.entries(PAGE_KINDS)) { + if (!kinds.some((k) => have.has(k))) hidden.add(page); + } + return hidden; +} + +// What the menu leaves out right now. Held here, not in a component, so the sidebar, the command palette and the keyboard shortcuts — which all ask the +// menu what there is — agree without being handed it (the same way the date and page-size settings are held). +let hidden: ReadonlySet = new Set(); +const listeners = new Set<() => void>(); + +/** Sets which pages the menu leaves out (an empty set shows them all). Tells whoever is listening only when it has changed. */ +export function setHiddenPages(pages: Iterable): void { + const next = new Set(pages); + if (next.size === hidden.size && [...next].every((p) => hidden.has(p))) return; + hidden = next; + listeners.forEach((l) => l()); +} + +export function getHiddenPages(): ReadonlySet { + return hidden; +} + +export function subscribeHiddenPages(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** Is this menu link one the menu leaves out? */ +export function isPageHidden(to: string): boolean { + return hidden.has(pagePath(to)); +}