Accessibility pass, command palette actions, row detail panel, server activity, map, wall display and setup guide
Accessibility: skip link, labelled landmarks, visible focus, page-change announcements, sortable headings as real buttons, every label tied to its field, named row checkboxes, and text contrast raised to 4.5:1 in both themes. Command palette: also runs actions (silence/end maintenance, theme, density, wall display, sign out) and is a proper dialog; g-then-letter shortcuts, "/" and "?". Row detail panel for six tables. Server Activity card, with the health check now recording offline/back-online and disk events in the audit log. Map page of hosts, servers, DNS names and monitors. Full-screen wall display. A getting-started checklist on the admin dashboard. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f7f5e1cd41
commit
57fd4f8c52
36 files changed
+2790
-210
No files matched your search
@@ -1,7 +1,23 @@
|
||||
import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { IconSearch } from "@tabler/icons-react";
|
||||
import { api, type SearchResponse, type IntegrationType, type DnsProviderType, type SecretType } from "../api/client";
|
||||
import {
|
||||
api,
|
||||
type CurrentUser,
|
||||
type DnsProviderType,
|
||||
type IntegrationType,
|
||||
type MaintenanceTargetType,
|
||||
type MaintenanceTargets,
|
||||
type MaintenanceWindow,
|
||||
type SearchResponse,
|
||||
type SecretType,
|
||||
} from "../api/client";
|
||||
import { isGroup, visibleNav } from "../layout/nav";
|
||||
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 { SHOW_SETUP_EVENT } from "./SetupGuide";
|
||||
|
||||
const SECRET_TYPE_LABELS: Record<SecretType, string> = {
|
||||
api_token: "API Token",
|
||||
@@ -37,10 +53,17 @@ interface PaletteItem {
|
||||
category: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
path: 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 buildItems(res: SearchResponse): PaletteItem[] {
|
||||
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}` });
|
||||
@@ -109,21 +132,45 @@ function buildItems(res: SearchResponse): PaletteItem[] {
|
||||
return items;
|
||||
}
|
||||
|
||||
export default function CommandPalette() {
|
||||
/** 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 [items, setItems] = useState<PaletteItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
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[]>([]);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const opener = useRef<HTMLElement | null>(null);
|
||||
const navigate = useNavigate();
|
||||
const canAct = user.role === "admin" || user.role === "operator";
|
||||
|
||||
// Global Ctrl/Cmd+K opens the palette from anywhere in the app; Escape closes it.
|
||||
// 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) => !o);
|
||||
setOpen((o) => {
|
||||
if (!o) opener.current = document.activeElement as HTMLElement | null;
|
||||
return !o;
|
||||
});
|
||||
} else if (e.key === "Escape") {
|
||||
setOpen(false);
|
||||
}
|
||||
@@ -132,37 +179,158 @@ export default function CommandPalette() {
|
||||
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) {
|
||||
setQuery("");
|
||||
setItems([]);
|
||||
setActiveIndex(0);
|
||||
setTimeout(() => inputRef.current?.focus(), 0);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || query.trim().length < 2) {
|
||||
setItems([]);
|
||||
if (!open) {
|
||||
opener.current?.focus?.();
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setQuery("");
|
||||
setFound([]);
|
||||
setActiveIndex(0);
|
||||
setTimeout(() => inputRef.current?.focus(), 0);
|
||||
api.maintenance
|
||||
.list()
|
||||
.then((res) => {
|
||||
setTargets(res.targets);
|
||||
setWindows(res.windows);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [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" });
|
||||
}
|
||||
|
||||
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",
|
||||
});
|
||||
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") {
|
||||
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" })),
|
||||
];
|
||||
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, canAct, targets, windows, onToggleTheme, onSetDensity]);
|
||||
|
||||
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) => {
|
||||
setItems(buildItems(res));
|
||||
setActiveIndex(0);
|
||||
})
|
||||
.catch(() => setItems([]))
|
||||
.finally(() => setLoading(false));
|
||||
.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 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);
|
||||
}
|
||||
return [...commands.filter((c) => matches(c, terms)).slice(0, 14), ...found];
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [commands, found, query]);
|
||||
|
||||
useEffect(() => setActiveIndex(0), [items.length, query]);
|
||||
|
||||
function go(item: PaletteItem) {
|
||||
setOpen(false);
|
||||
navigate(item.path);
|
||||
if (item.run) void item.run();
|
||||
else if (item.path) navigate(item.path);
|
||||
}
|
||||
|
||||
function handleInputKeyDown(e: ReactKeyboardEvent<HTMLInputElement>) {
|
||||
@@ -175,16 +343,28 @@ export default function CommandPalette() {
|
||||
} 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"
|
||||
onClick={() => setOpen(true)}
|
||||
title="Search (Ctrl/Cmd+K)"
|
||||
onClick={() => {
|
||||
opener.current = document.activeElement as HTMLElement | null;
|
||||
setOpen(true);
|
||||
}}
|
||||
title="Search and actions (Ctrl/Cmd+K)"
|
||||
aria-keyshortcuts="Control+K Meta+K"
|
||||
>
|
||||
<IconSearch size={16} />
|
||||
Search
|
||||
@@ -194,6 +374,7 @@ export default function CommandPalette() {
|
||||
}
|
||||
|
||||
let lastCategory = "";
|
||||
const empty = terms.length > 0 && items.length === 0 && !searching;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -204,7 +385,7 @@ export default function CommandPalette() {
|
||||
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" style={{ maxWidth: 600 }} onClick={(e) => e.stopPropagation()}>
|
||||
<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">
|
||||
@@ -215,41 +396,53 @@ export default function CommandPalette() {
|
||||
<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 servers, DNS, secrets, IPs, integrations…"
|
||||
placeholder="Search, or type a command: silence, theme, wall…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={handleInputKeyDown}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ maxHeight: "60vh", overflowY: "auto" }}>
|
||||
{loading && <div className="p-3 text-secondary">Searching…</div>}
|
||||
{!loading && query.trim().length >= 2 && items.length === 0 && <div className="p-3 text-secondary">No matches.</div>}
|
||||
{!loading && query.trim().length < 2 && <div className="p-3 text-secondary">Type at least 2 characters…</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}>
|
||||
<div key={item.key} role="presentation">
|
||||
{showHeader && (
|
||||
<div className="px-3 pt-2 pb-1 text-uppercase text-secondary" style={{ fontSize: "0.7rem" }}>
|
||||
<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>
|
||||
{item.subtitle && <div className="text-secondary small text-truncate">{item.subtitle}</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>
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { useEffect, useId, useRef, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { IconX } from "@tabler/icons-react";
|
||||
import { formatDateTime } from "../utils/date";
|
||||
|
||||
/**
|
||||
* A panel that slides in from the right with everything about one row, so the table stays where it was. Mount it only while a row
|
||||
* is selected. Escape or a click outside closes it, the keyboard stays inside while it is open, and the focus goes back to the
|
||||
* row it came from.
|
||||
*/
|
||||
export default function DetailDrawer({ title, subtitle, onClose, children }: { title: string; subtitle?: string; onClose: () => void; children: ReactNode }) {
|
||||
const titleId = useId();
|
||||
const closeRef = useRef<HTMLButtonElement>(null);
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const opener = document.activeElement as HTMLElement | null;
|
||||
closeRef.current?.focus();
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
e.stopPropagation();
|
||||
onClose();
|
||||
} else if (e.key === "Tab" && panelRef.current) {
|
||||
const focusable = panelRef.current.querySelectorAll<HTMLElement>('a[href], button:not([disabled]), input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])');
|
||||
if (focusable.length === 0) return;
|
||||
const first = focusable[0];
|
||||
const last = focusable[focusable.length - 1];
|
||||
if (e.shiftKey && document.activeElement === first) {
|
||||
e.preventDefault();
|
||||
last.focus();
|
||||
} else if (!e.shiftKey && document.activeElement === last) {
|
||||
e.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
};
|
||||
document.addEventListener("keydown", onKey, true);
|
||||
return () => {
|
||||
document.removeEventListener("keydown", onKey, true);
|
||||
opener?.focus?.();
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return createPortal(
|
||||
<>
|
||||
<div className="detail-backdrop" onClick={onClose} />
|
||||
<div ref={panelRef} className="detail-drawer" role="dialog" aria-modal="true" aria-labelledby={titleId}>
|
||||
<div className="detail-drawer-header">
|
||||
<div className="flex-fill" style={{ minWidth: 0 }}>
|
||||
<h3 className="mb-0 text-truncate" id={titleId}>
|
||||
{title}
|
||||
</h3>
|
||||
{subtitle && <div className="text-secondary small text-truncate">{subtitle}</div>}
|
||||
</div>
|
||||
<button ref={closeRef} type="button" className="btn btn-icon btn-ghost-secondary" aria-label="Close" onClick={onClose}>
|
||||
<IconX size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="detail-drawer-body">{children}</div>
|
||||
</div>
|
||||
</>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Showing every field of a record ────────────────────────────────────────
|
||||
|
||||
/** "environmentName" → "Environment name". */
|
||||
function humanize(key: string): string {
|
||||
const spaced = key
|
||||
.replace(/([a-z])([A-Z])/g, "$1 $2")
|
||||
.replace(/([a-zA-Z])(\d)/g, "$1 $2")
|
||||
.replace(/[_-]+/g, " ")
|
||||
.toLowerCase()
|
||||
// A trailing unit reads better in brackets: "Response time (ms)".
|
||||
.replace(/ (ms|kb|mb|gb|tb)$/, " ($1)");
|
||||
return spaced.charAt(0).toUpperCase() + spaced.slice(1);
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
const units = ["B", "KB", "MB", "GB", "TB", "PB"];
|
||||
let value = bytes;
|
||||
let unit = 0;
|
||||
while (value >= 1024 && unit < units.length - 1) {
|
||||
value /= 1024;
|
||||
unit++;
|
||||
}
|
||||
return `${value.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`;
|
||||
}
|
||||
|
||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;
|
||||
|
||||
function formatValue(key: string, value: unknown): ReactNode {
|
||||
if (value === null || value === undefined || value === "") return <span className="text-secondary">—</span>;
|
||||
if (typeof value === "boolean") return value ? "Yes" : "No";
|
||||
if (typeof value === "number") return /bytes?$/i.test(key) ? `${formatBytes(value)} (${value.toLocaleString()} bytes)` : value.toLocaleString();
|
||||
if (typeof value === "string") {
|
||||
if (ISO_DATE.test(value) && !Number.isNaN(Date.parse(value))) return formatDateTime(new Date(value));
|
||||
return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Every field of a record as a labelled list: dates and sizes made readable, lists joined, nested records indented. */
|
||||
export function ObjectDetails({ data, omit = [], labels = {}, depth = 0 }: { data: object; omit?: string[]; labels?: Record<string, string>; depth?: number }) {
|
||||
const entries = Object.entries(data).filter(([k]) => !omit.includes(k));
|
||||
return (
|
||||
<dl className={`detail-list ${depth > 0 ? "detail-list-nested" : ""}`}>
|
||||
{entries.map(([key, value]) => {
|
||||
const label = labels[key] ?? humanize(key);
|
||||
let shown: ReactNode = formatValue(key, value);
|
||||
if (shown === null) {
|
||||
if (Array.isArray(value)) {
|
||||
if (value.length === 0) shown = <span className="text-secondary">—</span>;
|
||||
else if (value.every((v) => v === null || typeof v !== "object")) shown = value.map((v) => String(v)).join(", ");
|
||||
else if (depth < 2) shown = value.map((v, i) => <ObjectDetails key={i} data={v as object} depth={depth + 1} />);
|
||||
else shown = `${value.length} items`;
|
||||
} else if (typeof value === "object" && depth < 2) {
|
||||
shown = <ObjectDetails data={value as object} depth={depth + 1} />;
|
||||
} else {
|
||||
shown = String(value);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div key={key}>
|
||||
<dt>{label}</dt>
|
||||
<dd>{shown}</dd>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { IconAlertTriangle, IconCircleCheck, IconEdit, IconTool } from "@tabler/icons-react";
|
||||
import { api, type ServerActivityEvent } from "../api/client";
|
||||
import { formatDateTime } from "../utils/date";
|
||||
import { formatAgo } from "../utils/duration";
|
||||
import { BlockSkeleton } from "./Skeleton";
|
||||
|
||||
const TONE_CLASS: Record<ServerActivityEvent["tone"], string> = {
|
||||
good: "text-green",
|
||||
bad: "text-red",
|
||||
info: "text-blue",
|
||||
neutral: "text-secondary",
|
||||
};
|
||||
|
||||
function EventIcon({ event }: { event: ServerActivityEvent }) {
|
||||
const cls = TONE_CLASS[event.tone];
|
||||
if (event.kind === "maintenance") return <IconTool size={18} className={cls} aria-hidden="true" />;
|
||||
if (event.kind === "health") return event.tone === "good" ? <IconCircleCheck size={18} className={cls} aria-hidden="true" /> : <IconAlertTriangle size={18} className={cls} aria-hidden="true" />;
|
||||
return <IconEdit size={18} className={cls} aria-hidden="true" />;
|
||||
}
|
||||
|
||||
/** What has happened to a server, newest first. For operators and admins, since it draws on the audit log. */
|
||||
export default function ServerActivity({ serverId }: { serverId: number }) {
|
||||
const [events, setEvents] = useState<ServerActivityEvent[] | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
api.servers
|
||||
.activity(serverId)
|
||||
.then((res) => alive && setEvents(res.events))
|
||||
.catch(() => alive && setFailed(true));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [serverId]);
|
||||
|
||||
return (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Activity</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
{failed ? (
|
||||
<div className="text-secondary">Couldn't load the activity.</div>
|
||||
) : events === null ? (
|
||||
<BlockSkeleton lines={4} />
|
||||
) : events.length === 0 ? (
|
||||
<div className="text-secondary">Nothing recorded yet. Changes to this server, times it stopped reporting, and its maintenance windows will be listed here.</div>
|
||||
) : (
|
||||
<ol className="activity-list">
|
||||
{events.map((e, i) => (
|
||||
<li key={`${e.at}-${i}`}>
|
||||
<EventIcon event={e} />
|
||||
<div className="flex-fill" style={{ minWidth: 0 }}>
|
||||
<div>
|
||||
{e.title}
|
||||
{e.actor && <span className="text-secondary"> · {e.actor === "system" ? "automatic" : e.actor}</span>}
|
||||
</div>
|
||||
{e.detail && <div className="text-secondary small">{e.detail}</div>}
|
||||
</div>
|
||||
<time className="text-secondary small text-nowrap" dateTime={e.at} title={formatDateTime(new Date(e.at))}>
|
||||
{Date.parse(e.at) > Date.now() ? `at ${formatDateTime(new Date(e.at))}` : formatAgo(e.at)}
|
||||
</time>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { IconCircle, IconCircleCheck, IconX } from "@tabler/icons-react";
|
||||
|
||||
export interface SetupStep {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
to: string;
|
||||
/** What to call the button that goes there. */
|
||||
action: string;
|
||||
done: boolean;
|
||||
}
|
||||
|
||||
const DISMISSED_KEY = "hlm-setup-dismissed";
|
||||
export const SHOW_SETUP_EVENT = "show-setup-guide";
|
||||
|
||||
function wasDismissed(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(DISMISSED_KEY) === "1";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A checklist for a new installation, at the top of the dashboard: what to set up, which steps are already done (worked out from
|
||||
* what exists, never ticked by hand), and a way to put it away. It goes by itself once everything is done.
|
||||
*/
|
||||
export default function SetupGuide({ steps }: { steps: SetupStep[] }) {
|
||||
const [dismissed, setDismissed] = useState(wasDismissed);
|
||||
|
||||
// The command palette can bring it back.
|
||||
useEffect(() => {
|
||||
const show = () => {
|
||||
try {
|
||||
localStorage.removeItem(DISMISSED_KEY);
|
||||
} catch {
|
||||
// not remembered; it shows for this visit anyway
|
||||
}
|
||||
setDismissed(false);
|
||||
};
|
||||
window.addEventListener(SHOW_SETUP_EVENT, show);
|
||||
return () => window.removeEventListener(SHOW_SETUP_EVENT, show);
|
||||
}, []);
|
||||
|
||||
const done = steps.filter((s) => s.done).length;
|
||||
if (dismissed || steps.length === 0 || done === steps.length) return null;
|
||||
|
||||
const dismiss = () => {
|
||||
try {
|
||||
localStorage.setItem(DISMISSED_KEY, "1");
|
||||
} catch {
|
||||
// not remembered; it is gone for this visit anyway
|
||||
}
|
||||
setDismissed(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card mb-3" role="region" aria-labelledby="setup-guide-title">
|
||||
<div className="card-header">
|
||||
<div>
|
||||
<h3 className="card-title" id="setup-guide-title">
|
||||
Getting started
|
||||
</h3>
|
||||
<div className="text-secondary small">
|
||||
{done} of {steps.length} done
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-actions">
|
||||
<button type="button" className="btn btn-sm btn-ghost-secondary" onClick={dismiss} aria-label="Hide the getting started guide" title="Hide this guide (bring it back from the search box: Ctrl K)">
|
||||
<IconX size={16} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="progress progress-sm rounded-0" role="progressbar" aria-label="Setup progress" aria-valuemin={0} aria-valuemax={steps.length} aria-valuenow={done}>
|
||||
<div className="progress-bar bg-green" style={{ width: `${(done / steps.length) * 100}%` }} />
|
||||
</div>
|
||||
<ul className="list-group list-group-flush">
|
||||
{steps.map((s) => (
|
||||
<li key={s.id} className="list-group-item d-flex align-items-center gap-3">
|
||||
{s.done ? <IconCircleCheck size={22} className="text-green flex-shrink-0" aria-label="Done" /> : <IconCircle size={22} className="text-secondary flex-shrink-0" aria-label="Not done yet" />}
|
||||
<div className="flex-fill" style={{ minWidth: 0 }}>
|
||||
<div className={s.done ? "text-secondary" : "fw-medium"}>{s.title}</div>
|
||||
{!s.done && <div className="text-secondary small">{s.description}</div>}
|
||||
</div>
|
||||
{!s.done && (
|
||||
<Link to={s.to} className="btn btn-sm btn-primary flex-shrink-0">
|
||||
{s.action}
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { GO_SHORTCUTS, OTHER_SHORTCUTS, SHOW_SHORTCUTS_EVENT } from "../layout/shortcuts";
|
||||
|
||||
/** The keyboard shortcuts, listed. Opens on "?", from the command palette, or when asked for by event. Mount once, near the root. */
|
||||
export default function ShortcutHelp() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const titleId = useId();
|
||||
const closeRef = useRef<HTMLButtonElement>(null);
|
||||
const opener = useRef<HTMLElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const show = () => {
|
||||
opener.current = document.activeElement as HTMLElement | null;
|
||||
setOpen(true);
|
||||
};
|
||||
window.addEventListener(SHOW_SHORTCUTS_EVENT, show);
|
||||
return () => window.removeEventListener(SHOW_SHORTCUTS_EVENT, show);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
closeRef.current?.focus();
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
e.stopPropagation();
|
||||
setOpen(false);
|
||||
} else if (e.key === "Tab") {
|
||||
// The only thing to reach is the close button, so keep the keyboard on it.
|
||||
e.preventDefault();
|
||||
closeRef.current?.focus();
|
||||
}
|
||||
};
|
||||
document.addEventListener("keydown", onKey, true);
|
||||
return () => {
|
||||
document.removeEventListener("keydown", onKey, true);
|
||||
opener.current?.focus?.();
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
if (!open) return null;
|
||||
return createPortal(
|
||||
<>
|
||||
<div className="modal-backdrop show" />
|
||||
<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-labelledby={titleId} onClick={(e) => e.stopPropagation()}>
|
||||
<div className="modal-content">
|
||||
<div className="modal-header">
|
||||
<h3 className="modal-title" id={titleId}>
|
||||
Keyboard shortcuts
|
||||
</h3>
|
||||
<button ref={closeRef} type="button" className="btn-close" aria-label="Close" onClick={() => setOpen(false)} />
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<div className="fw-bold mb-2">Go to a page — press g, then…</div>
|
||||
<dl className="shortcut-list mb-3">
|
||||
{GO_SHORTCUTS.map((s) => (
|
||||
<div key={s.key}>
|
||||
<dt>
|
||||
<kbd>g</kbd> <kbd>{s.key}</kbd>
|
||||
</dt>
|
||||
<dd>{s.label}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<div className="fw-bold mb-2">Anywhere</div>
|
||||
<dl className="shortcut-list mb-0">
|
||||
{OTHER_SHORTCUTS.map((s) => (
|
||||
<div key={s.keys}>
|
||||
<dt>
|
||||
<kbd>{s.keys}</kbd>
|
||||
</dt>
|
||||
<dd>{s.label}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<div className="text-secondary small mt-3">Shortcuts for pages you can't open are ignored. They don't fire while you are typing in a box.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import type { ReactNode } from "react";
|
||||
import type { SortDirection } from "../hooks/useSortable";
|
||||
|
||||
/**
|
||||
* A column heading that sorts the table. The button inside is what the keyboard reaches and a screen reader announces ("Name,
|
||||
* sorted ascending"); the heading itself stays a real column header, so the table keeps its meaning for assistive technology.
|
||||
*/
|
||||
export default function SortableTh<T>({
|
||||
label,
|
||||
sortKeyName,
|
||||
@@ -18,16 +22,13 @@ export default function SortableTh<T>({
|
||||
}) {
|
||||
const active = activeKey === sortKeyName;
|
||||
return (
|
||||
<th
|
||||
className={className}
|
||||
role="button"
|
||||
style={{ cursor: "pointer", userSelect: "none", whiteSpace: "nowrap" }}
|
||||
onClick={() => onSort(sortKeyName)}
|
||||
>
|
||||
{label}
|
||||
<span className={active ? "" : "text-secondary"} style={{ marginLeft: 4, opacity: active ? 1 : 0.4 }}>
|
||||
{active ? (direction === "asc" ? "▲" : "▼") : "↕"}
|
||||
</span>
|
||||
<th className={className} scope="col" aria-sort={active ? (direction === "asc" ? "ascending" : "descending") : "none"}>
|
||||
<button type="button" className="th-sort" onClick={() => onSort(sortKeyName)}>
|
||||
{label}
|
||||
<span aria-hidden="true" className={active ? "" : "text-secondary"} style={{ marginLeft: 4, opacity: active ? 1 : 0.4 }}>
|
||||
{active ? (direction === "asc" ? "▲" : "▼") : "↕"}
|
||||
</span>
|
||||
</button>
|
||||
</th>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user