Files
Homelab-manager/web/src/components/CommandPalette.tsx
T
bobbanandClaude Sonnet 5.5 68b41b5586 A year of history, one chart, and a read API with personal tokens
History: server load, memory and disks are also kept as hourly (four months) and
daily (over two years) averages with lowest and highest; endpoint answers as
hourly (four months) beside the daily figures. Charts ask for 24 hours to a year
and are drawn from whichever is fine enough. A disk that two weeks call flat is
looked at again over ninety days for the forecast. Built once from what is kept.

One chart: TimeChart replaces the sparkline and the multi-line chart: hover and
arrow-key readout, a lowest/highest band, gaps shown as gaps, the same ranges
everywhere and the choice remembered. Used for server trends, comparing servers,
a check's availability and answer times (Endpoints > History) and a server's
availability.

Read API: /api/v1 (servers, metrics, alerts, incidents, inventory, network,
endpoints and their history, maintenance) with personal read-only tokens made
under the user menu: shown once, hashed, 30/90/365 days or none, ten at most,
removed with their owner. GET only. Documented in API.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 20:22:58 +02:00

568 lines
24 KiB
TypeScript

import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { IconSearch } from "@tabler/icons-react";
import {
api,
type AlertItem,
type Asset,
type CurrentUser,
type DnsProviderType,
type IntegrationType,
type MaintenanceTargetType,
type MaintenanceTargets,
type MaintenanceWindow,
type SearchResponse,
type SecretType,
type UpdatesServer,
} from "../api/client";
import { isCurrent, isGroup, visibleNav, type NavLeaf } from "../layout/nav";
import { toggleFavorite, useFavorites } from "../utils/favorites";
import { describeView, splitView } from "../utils/savedViews";
import { SHOW_SHORTCUTS_EVENT, shortcutHintFor } from "../layout/shortcuts";
import { DENSITIES, type Density } from "../utils/density";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
import { SETTINGS_INDEX } from "../utils/settingsIndex";
import { SHOW_SETUP_EVENT } from "./SetupGuide";
const SECRET_TYPE_LABELS: Record<SecretType, string> = {
api_token: "API Token",
ssl_certificate: "SSL Certificate",
password: "Password",
generic: "Generic",
};
const INTEGRATION_TYPE_LABELS: Record<IntegrationType, string> = {
tailscale: "Tailscale",
proxmox: "Proxmox",
synology: "Synology",
semaphore: "Semaphore",
gitea: "Gitea",
dockhand: "Dockhand",
uptimekuma: "Uptime Kuma",
phpipam: "phpIPAM",
pbs: "Proxmox Backup Server",
osticket: "osTicket",
unifi: "UniFi",
};
const DNS_PROVIDER_LABELS: Record<DnsProviderType, string> = {
cloudflare: "Cloudflare",
loopia: "Loopia",
pihole: "Pi-hole",
azure: "Azure DNS",
cpanel: "cPanel",
technitium: "Technitium",
};
interface PaletteItem {
key: string;
category: string;
title: string;
subtitle: string;
/** A shortcut to show beside it, e.g. "g s". */
hint?: string;
/** Go to a page… */
path?: string;
/** …or do something. */
run?: () => void | Promise<void>;
/** Extra words it can be found by. */
keywords?: string;
}
function buildSearchItems(res: SearchResponse): PaletteItem[] {
const items: PaletteItem[] = [];
for (const s of res.servers) {
items.push({ key: `server-${s.id}`, category: "Servers", title: s.name, subtitle: s.hostname ?? "", path: `/servers/${s.id}` });
}
for (const s of res.secrets) {
items.push({
key: `secret-${s.id}`,
category: "Secrets",
title: s.name,
subtitle: SECRET_TYPE_LABELS[s.type],
path: `/secrets?q=${encodeURIComponent(s.name)}&editId=${s.id}`,
});
}
for (const i of res.ipam) {
items.push({
key: `ipam-${i.id}`,
category: "IP Addresses",
title: i.ipAddress,
subtitle: i.label ?? "",
path: `/ipam?q=${encodeURIComponent(i.ipAddress)}&editId=${i.id}`,
});
}
for (const z of res.dnsZones) {
items.push({
key: `zone-${z.providerId}-${z.zoneId}`,
category: "DNS zones",
title: z.zoneName,
subtitle: z.providerName,
path: `/dns?providerId=${z.providerId}&zoneId=${encodeURIComponent(z.zoneId)}`,
});
}
for (const r of res.dnsRecords) {
const params = new URLSearchParams({
providerId: String(r.providerId),
zoneId: r.zoneId,
recordType: r.type,
recordName: r.name,
recordContent: r.content,
});
items.push({
key: `record-${r.providerId}-${r.zoneId}-${r.type}-${r.name}-${r.content}`,
category: "DNS records",
title: `${r.type} ${r.name}`,
subtitle: `${r.content} · zone ${r.zoneName} · ${r.providerName}`,
path: `/dns?${params.toString()}`,
});
}
for (const p of res.dnsProviders) {
items.push({
key: `provider-${p.id}`,
category: "DNS providers",
title: p.name,
subtitle: DNS_PROVIDER_LABELS[p.providerType],
path: `/dns?providerId=${p.id}`,
});
}
for (const i of res.integrations) {
items.push({
key: `integration-${i.id}`,
category: "Integrations",
title: i.name,
subtitle: INTEGRATION_TYPE_LABELS[i.type],
path: `/integrations?editId=${i.id}`,
});
}
return items;
}
/** Every word typed must appear somewhere in the item's title, subtitle or keywords. */
function matches(item: PaletteItem, terms: string[]): boolean {
if (terms.length === 0) return true;
const hay = `${item.title} ${item.subtitle} ${item.keywords ?? ""}`.toLowerCase();
return terms.every((t) => hay.includes(t));
}
const SUGGESTED_LIMIT = 9;
export default function CommandPalette({
user,
onToggleTheme,
onSetDensity,
}: {
user: CurrentUser;
onToggleTheme: () => void;
onSetDensity: (density: Density) => void;
}) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [found, setFound] = useState<PaletteItem[]>([]);
const [searching, setSearching] = useState(false);
const [activeIndex, setActiveIndex] = useState(0);
const [targets, setTargets] = useState<MaintenanceTargets | null>(null);
const [windows, setWindows] = useState<MaintenanceWindow[]>([]);
// What the actions below are offered for, read each time the palette opens.
const [alertsToAck, setAlertsToAck] = useState<AlertItem[]>([]);
const [updatable, setUpdatable] = useState<UpdatesServer[]>([]);
const [assets, setAssets] = useState<Asset[]>([]);
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.
useEffect(() => {
function onKeyDown(e: KeyboardEvent) {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
e.preventDefault();
setOpen((o) => {
if (!o) opener.current = document.activeElement as HTMLElement | null;
return !o;
});
} else if (e.key === "Escape") {
setOpen(false);
}
}
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, []);
// On open: start clean, focus the box, and fetch what the maintenance actions need; on close: hand the focus back.
useEffect(() => {
if (!open) {
opener.current?.focus?.();
return;
}
setQuery("");
setFound([]);
setActiveIndex(0);
setTimeout(() => inputRef.current?.focus(), 0);
api.maintenance
.list()
.then((res) => {
setTargets(res.targets);
setWindows(res.windows);
})
.catch(() => {});
if (canAct) {
api.alerts
.list(false)
.then((res) => setAlertsToAck(res.alerts.filter((a) => !a.silenced && a.severity !== "info" && !a.ack?.active).sort((a, b) => Number(b.severity === "critical") - Number(a.severity === "critical"))))
.catch(() => setAlertsToAck([]));
api.servers
.updates()
.then((res) => setUpdatable(res.servers.filter((s) => (s.updates?.count ?? 0) > 0)))
.catch(() => setUpdatable([]));
}
api.inventory
.list()
.then((res) => setAssets(res.assets))
.catch(() => setAssets([]));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
// The commands: pages to go to, and things to do.
const commands = useMemo<PaletteItem[]>(() => {
const items: PaletteItem[] = [];
const pages: { to: string; label: string; group: string }[] = [];
for (const entry of visibleNav(user.role)) {
if (isGroup(entry)) entry.items.forEach((i) => pages.push({ to: i.to, label: i.label, group: entry.label }));
else pages.push({ to: entry.to, label: entry.label, group: "" });
}
pages.push({ to: "/wall", label: "Wall display", group: "" });
for (const p of pages) {
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" });
}
items.push({
key: "act-refresh-alerts",
category: "Actions",
title: "Check alerts again",
subtitle: "",
run: () => {
window.dispatchEvent(new Event("maintenance-changed"));
toast.info("Checking alerts again…");
},
keywords: "refresh reload alerts",
});
// Quick acknowledgements: the worst few alerts nobody is on, and all of them at once.
if (canAct && alertsToAck.length > 0) {
const ack = async (list: AlertItem[]) => {
try {
await Promise.all(list.map((a) => api.alerts.ack({ alertId: a.id, note: "Acknowledged from the command palette", assigneeId: user.id, hours: 4 })));
toast.success(list.length === 1 ? "Acknowledged for 4 hours, handed to you. Change that on the Alerts page." : `Acknowledged ${list.length} alerts for 4 hours, handed to you.`);
window.dispatchEvent(new Event("maintenance-changed"));
} catch (err) {
toast.error(readableError(err));
}
};
for (const a of alertsToAck.slice(0, 5)) {
items.push({ key: `ack-${a.id}`, category: "Alerts", title: `Acknowledge: ${a.message}`, subtitle: `${a.severity} · for 4 hours, handed to you`, run: () => ack([a]), keywords: "acknowledge ack alert on it mine" });
}
if (alertsToAck.length > 1) {
items.push({ key: "ack-all", category: "Alerts", title: `Acknowledge all ${alertsToAck.length} alerts nobody is on`, subtitle: "for 4 hours, handed to you", run: () => ack(alertsToAck), keywords: "acknowledge ack alerts all" });
}
}
items.push({ key: "go-alerts-open", category: "Alerts", title: "Show the alerts nobody is on", subtitle: "", path: "/alerts", keywords: "alerts unacknowledged attention" });
// Update a server straight from here: opens the update drawer for it, which asks before it does anything.
if (canAct) {
for (const s of updatable) {
items.push({
key: `update-${s.id}`,
category: "Updates",
title: `Update ${s.name} now`,
subtitle: `${s.updates?.count ?? 0} waiting${s.updates?.security ? ` · ${s.updates.security} security` : ""}`,
path: `/updates?update=${s.id}`,
keywords: "update upgrade patch install run",
});
}
}
// Hardware: open it, or print its label.
items.push({ key: "inv-labels", category: "Inventory", title: "Print inventory labels", subtitle: "a sheet of QR stickers", path: "/inventory/labels", keywords: "label labels qr print sticker" });
for (const a of assets) {
items.push({ key: `inv-open-${a.id}`, category: "Inventory", title: `Open ${a.name} in the inventory`, subtitle: [a.manufacturer, a.model].filter(Boolean).join(" "), path: `/inventory?asset=${a.id}`, keywords: "hardware asset inventory serial" });
items.push({ key: `inv-label-${a.id}`, category: "Inventory", title: `Print the label for ${a.name}`, subtitle: a.rackUnit ?? a.location ?? "", path: `/inventory/labels?only=${a.id}`, keywords: "label qr print sticker" });
}
// What would go down with a server or a service.
if (targets) {
for (const s of targets.servers) {
items.push({ key: `dep-server-${s.id}`, category: "Dependencies", title: `What depends on ${s.name}?`, subtitle: "server · opens the dependency map", path: `/map?view=dependencies&select=server:${s.id}`, keywords: "depends dependency impact reboot down" });
}
for (const i of targets.integrations) {
items.push({ key: `dep-int-${i.id}`, category: "Dependencies", title: `What depends on ${i.name}?`, subtitle: `${i.type} · opens the dependency map`, path: `/map?view=dependencies&select=integration:${i.id}`, keywords: "depends dependency impact down" });
}
}
items.push({ key: "act-tokens", category: "Actions", title: "API tokens", subtitle: "Read-only access for scripts and Home Assistant", path: "/api-tokens", keywords: "api token key read home assistant script bearer" });
items.push({ key: "act-shortcuts", category: "Actions", title: "Show keyboard shortcuts", subtitle: "", hint: "?", run: () => void window.dispatchEvent(new Event(SHOW_SHORTCUTS_EVENT)), keywords: "keys help" });
if (user.role === "admin") {
// Each setting, so "quiet hours" or "flapping" finds the place it is set.
for (const [i, s] of SETTINGS_INDEX.entries()) {
items.push({ key: `setting-${i}`, category: "Settings", title: s.title, subtitle: s.where, path: s.to, keywords: `settings ${s.words}` });
}
items.push({
key: "act-setup",
category: "Actions",
title: "Show the getting started guide",
subtitle: "on the dashboard",
run: () => {
window.dispatchEvent(new Event(SHOW_SETUP_EVENT));
navigate("/");
},
keywords: "setup onboarding checklist first run",
});
}
items.push({ key: "act-signout", category: "Actions", title: "Sign out", subtitle: "", run: () => void (window.location.href = "/auth/logout"), keywords: "log out logout" });
if (canAct && targets) {
const start = (type: MaintenanceTargetType, id: number, name: string, minutes: number, words: string) => async () => {
try {
await api.maintenance.start({ targetType: type, targetId: id, minutes, reason: "Started from the command palette" });
toast.success(`${name} is silenced for ${words}. End it early under Maintenance.`);
window.dispatchEvent(new Event("maintenance-changed"));
} catch (err) {
toast.error(readableError(err));
}
};
const targetList: { type: MaintenanceTargetType; id: number; name: string; kind: string }[] = [
...targets.servers.map((s) => ({ type: "server" as const, id: s.id, name: s.name, kind: "server" })),
...targets.integrations.map((i) => ({ type: "integration" as const, id: i.id, name: i.name, kind: i.type })),
...targets.dnsProviders.map((p) => ({ type: "dns_provider" as const, id: p.id, name: p.name, kind: "DNS provider" })),
...targets.devices.map((d) => ({ type: "device" as const, id: d.id, name: d.name, kind: "network device" })),
];
for (const t of targetList) {
for (const [minutes, words] of [
[60, "1 hour"],
[240, "4 hours"],
] as const) {
items.push({
key: `maint-${t.type}-${t.id}-${minutes}`,
category: "Maintenance",
title: `Silence ${t.name} for ${words}`,
subtitle: `${t.kind} · starts a maintenance window`,
run: start(t.type, t.id, t.name, minutes, words),
keywords: "maintenance silence mute window",
});
}
}
for (const w of windows) {
items.push({
key: `maint-end-${w.id}`,
category: "Maintenance",
title: `End maintenance on ${w.targetName}`,
subtitle: "alerts about it become active again",
run: async () => {
try {
await api.maintenance.end(w.id);
toast.success(`Maintenance on ${w.targetName} ended.`);
window.dispatchEvent(new Event("maintenance-changed"));
} catch (err) {
toast.error(readableError(err));
}
},
keywords: "maintenance end stop silence window",
});
}
}
return items;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [user.role, user.id, canAct, targets, windows, alertsToAck, updatable, assets, onToggleTheme, onSetDensity, pathname, favorites]);
const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
// Data search, for two characters or more.
useEffect(() => {
if (!open || query.trim().length < 2) {
setFound([]);
setSearching(false);
return;
}
setSearching(true);
const handle = setTimeout(() => {
api.search
.query(query.trim())
.then((res) => setFound(buildSearchItems(res)))
.catch(() => setFound([]))
.finally(() => setSearching(false));
}, 200);
return () => clearTimeout(handle);
}, [query, open]);
// 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) => {
const [base, search] = splitView(p);
const c = commands.find((x) => x.key === `page-${base}`);
// A pinned view goes to the page with its filters, and says what they are.
return c && search ? { ...c, key: `page-${p}`, path: p, title: `${c.title}: ${describeView(search)}` } : c;
})
.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"];
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, favorites]);
useEffect(() => setActiveIndex(0), [items.length, query]);
function go(item: PaletteItem) {
setOpen(false);
if (item.run) void item.run();
else if (item.path) navigate(item.path);
}
function handleInputKeyDown(e: ReactKeyboardEvent<HTMLInputElement>) {
if (e.key === "ArrowDown") {
e.preventDefault();
setActiveIndex((i) => Math.min(i + 1, items.length - 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActiveIndex((i) => Math.max(i - 1, 0));
} else if (e.key === "Enter") {
e.preventDefault();
if (items[activeIndex]) go(items[activeIndex]);
} else if (e.key === "Tab") {
// Nothing else in here is worth tabbing to: the list is driven from the box.
e.preventDefault();
}
}
// Keep the highlighted row in view as the arrows move it.
useEffect(() => {
document.getElementById(`palette-opt-${activeIndex}`)?.scrollIntoView({ block: "nearest" });
}, [activeIndex]);
if (!open) {
return (
<button
type="button"
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} />
<span className="palette-text">Search</span>
<kbd className="ms-auto palette-text">Ctrl K</kbd>
</button>
);
}
let lastCategory = "";
const empty = terms.length > 0 && items.length === 0 && !searching;
return (
<>
{/* Rendered as a sibling, not a child, of .modal — Tabler/Bootstrap's z-index values
(backdrop 1050 vs modal 1055) only sort correctly when compared in the same
stacking context. Nested inside .modal, the backdrop was created its own stacking
context and painted on top of .modal-dialog, silently swallowing every click meant
for a result row. */}
<div className="modal-backdrop show"></div>
<div className="modal modal-blur show" style={{ display: "block" }} onClick={() => setOpen(false)}>
<div className="modal-dialog modal-dialog-centered" role="dialog" aria-modal="true" aria-label="Search and actions" style={{ maxWidth: 640 }} onClick={(e) => e.stopPropagation()}>
<div className="modal-content">
<div className="modal-body p-0">
<div className="p-2 border-bottom">
<div className="input-icon">
<span className="input-icon-addon">
<IconSearch size={18} />
</span>
<input
ref={inputRef}
type="text"
role="combobox"
aria-expanded="true"
aria-controls="palette-list"
aria-activedescendant={items[activeIndex] ? `palette-opt-${activeIndex}` : undefined}
aria-autocomplete="list"
aria-label="Search, or type a command"
className="form-control form-control-lg border-0"
placeholder="Search, or type a command: acknowledge, update, label…"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={handleInputKeyDown}
/>
</div>
</div>
<div id="palette-list" role="listbox" aria-label="Results" style={{ maxHeight: "60vh", overflowY: "auto" }}>
{items.map((item, index) => {
const showHeader = item.category !== lastCategory;
lastCategory = item.category;
return (
<div key={item.key} role="presentation">
{showHeader && (
<div role="presentation" className="px-3 pt-2 pb-1 text-uppercase text-secondary" style={{ fontSize: "0.7rem" }}>
{item.category}
</div>
)}
<div
id={`palette-opt-${index}`}
role="option"
aria-selected={index === activeIndex}
className={`px-3 py-2 d-flex justify-content-between align-items-center gap-3 ${index === activeIndex ? "bg-secondary-lt" : ""}`}
style={{ cursor: "pointer" }}
onMouseEnter={() => setActiveIndex(index)}
onClick={() => go(item)}
>
<div className="text-truncate">{item.title}</div>
<div className="d-flex align-items-center gap-2 flex-shrink-0">
{item.subtitle && <span className="text-secondary small text-truncate">{item.subtitle}</span>}
{item.hint && <kbd>{item.hint}</kbd>}
</div>
</div>
</div>
);
})}
</div>
<div className="px-3 py-2 border-top text-secondary small" role="status" aria-live="polite">
{searching ? "Searching…" : empty ? "No matches." : terms.length === 0 ? "Type to search servers, DNS, secrets and more — or a command." : `${items.length} result${items.length === 1 ? "" : "s"}`}
</div>
</div>
</div>
</div>
</div>
</>
);
}