Add saved filter views, a customisable dashboard, server comparison, row keyboard navigation and share links
- Table search, status, tag and sort live in the address; Save view pins one as a favourite. - Dashboard cards can be moved and hidden per user (users.dashboard_layout, migration 0022). - Compare two to four servers' load, memory or disk on one chart. - j/k move through table rows that open a detail panel. - Share links open a read-only wall without signing in, numbers only or with names (share_links, migration 0023); the wall is split into a shared view over two data sources. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
906220040e
commit
44e393f172
50 files changed
+6114
-258
No files matched your search
+17
-1
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { Routes, Route, Navigate } from "react-router-dom";
|
||||
import { Routes, Route, Navigate, useLocation } from "react-router-dom";
|
||||
import { api, type CurrentUser, type UserRole, UnauthorizedError } from "./api/client";
|
||||
import Login from "./pages/Login";
|
||||
import Dashboard from "./pages/Dashboard";
|
||||
@@ -13,6 +13,7 @@ import Ports from "./pages/Ports";
|
||||
import Dns from "./pages/Dns";
|
||||
import Servers from "./pages/Servers";
|
||||
import ServerDetail from "./pages/ServerDetail";
|
||||
import ServerCompare from "./pages/ServerCompare";
|
||||
import Integrations from "./pages/Integrations";
|
||||
import Docker from "./pages/Docker";
|
||||
import Tailscale from "./pages/Tailscale";
|
||||
@@ -40,9 +41,11 @@ import LogSettings from "./pages/settings/LogSettings";
|
||||
import BackupSettings from "./pages/settings/BackupSettings";
|
||||
import NameSettings from "./pages/settings/NameSettings";
|
||||
import AlertTicketSettings from "./pages/settings/AlertTicketSettings";
|
||||
import ShareSettings from "./pages/settings/ShareSettings";
|
||||
import AppShell from "./layout/AppShell";
|
||||
import DialogHost from "./components/DialogHost";
|
||||
import Wall from "./pages/Wall";
|
||||
import SharedWall from "./pages/SharedWall";
|
||||
import MapPage from "./pages/Map";
|
||||
import { setDateTimeSettings } from "./utils/date";
|
||||
import { setPageSize } from "./utils/pageSize";
|
||||
@@ -69,8 +72,11 @@ function RequireRole({
|
||||
|
||||
export default function App() {
|
||||
const [user, setUser] = useState<CurrentUser | null | undefined>(undefined);
|
||||
// A share link's page is for someone who isn't signed in: it asks nothing of the app's own session.
|
||||
const shared = useLocation().pathname.startsWith("/share/wall/");
|
||||
|
||||
useEffect(() => {
|
||||
if (shared) return;
|
||||
api.me().then(
|
||||
(res) => setUser(res.user),
|
||||
(err) => {
|
||||
@@ -86,6 +92,14 @@ export default function App() {
|
||||
}).catch(() => {});
|
||||
}, []);
|
||||
|
||||
if (shared) {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/share/wall/:token" element={<SharedWall />} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
|
||||
if (user === undefined) {
|
||||
return <div className="loading-screen">Loading…</div>;
|
||||
}
|
||||
@@ -110,6 +124,7 @@ function Shelled({ user }: { user: CurrentUser }) {
|
||||
<Route path="/" element={<Dashboard user={user} />} />
|
||||
<Route path="/map" element={<MapPage />} />
|
||||
<Route path="/servers" element={<Servers user={user} />} />
|
||||
<Route path="/servers/compare" element={<ServerCompare />} />
|
||||
<Route path="/servers/:id" element={<ServerDetail user={user} />} />
|
||||
<Route path="/dns" element={<Dns user={user} />} />
|
||||
<Route path="/ipam" element={<Ipam user={user} />} />
|
||||
@@ -179,6 +194,7 @@ function Shelled({ user }: { user: CurrentUser }) {
|
||||
<Route path="tags" element={<TagSettings />} />
|
||||
<Route path="names" element={<NameSettings />} />
|
||||
<Route path="alert-tickets" element={<AlertTicketSettings />} />
|
||||
<Route path="share" element={<ShareSettings />} />
|
||||
<Route path="cache" element={<CacheSettings />} />
|
||||
<Route path="logs" element={<LogSettings />} />
|
||||
<Route path="backup" element={<BackupSettings />} />
|
||||
|
||||
+55
-1
@@ -6,8 +6,47 @@ export interface CurrentUser {
|
||||
email?: string;
|
||||
name?: string;
|
||||
role: UserRole;
|
||||
/** Pages this person pinned to the top of their menu, by path. */
|
||||
/** Pages this person pinned to the top of their menu, by path — a page alone, or with filters ("/servers?status=offline"). */
|
||||
favorites?: string[];
|
||||
/** How this person arranged the dashboard cards. */
|
||||
dashboard?: DashboardLayout;
|
||||
}
|
||||
|
||||
export type ShareLinkDetail = "summary" | "names";
|
||||
|
||||
/** A link that opens the wall display without signing in, as the settings list shows it (never the secret). */
|
||||
export interface ShareLink {
|
||||
id: number;
|
||||
label: string;
|
||||
tokenPrefix: string;
|
||||
detail: ShareLinkDetail;
|
||||
createdBy: string | null;
|
||||
createdAt: string;
|
||||
expiresAt: string | null;
|
||||
lastUsedAt: string | null;
|
||||
expired: boolean;
|
||||
}
|
||||
|
||||
/** What a share link may show: numbers, and with "names" also the names of what is wrong. Built on the server. */
|
||||
export interface PublicWall {
|
||||
detail: ShareLinkDetail;
|
||||
level: "ok" | "warning" | "critical" | "unsure";
|
||||
environment: string | null;
|
||||
servers: { online: number; offline: number };
|
||||
alerts: { critical: number; warning: number };
|
||||
maintenance: number;
|
||||
integrationsFailing: number;
|
||||
problems?: { id: string; severity: "critical" | "warning"; message: string }[];
|
||||
maintenanceWindows?: { id: number; name: string; endsAt: string }[];
|
||||
integrations?: { id: number; name: string; type: string; status: "ok" | "failing" | "unknown" }[];
|
||||
generatedAt: string;
|
||||
display: { dateFormat: string; timeFormat: string };
|
||||
}
|
||||
|
||||
/** The dashboard cards a person hid, and the order they put the rest in (a lower number comes first). */
|
||||
export interface DashboardLayout {
|
||||
hidden: string[];
|
||||
order: Record<string, number>;
|
||||
}
|
||||
|
||||
/** One thing worth a line in "Since you last looked". */
|
||||
@@ -1148,12 +1187,27 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
export const api = {
|
||||
me: Object.assign(() => request<{ user: CurrentUser }>("/api/me"), {
|
||||
setFavorites: (paths: string[]) => request<{ favorites: string[] }>("/api/me/favorites", { method: "PUT", body: JSON.stringify({ paths }) }),
|
||||
setDashboard: (layout: DashboardLayout) => request<{ dashboard: DashboardLayout }>("/api/me/dashboard", { method: "PUT", body: JSON.stringify(layout) }),
|
||||
changes: () => request<ChangesSummary>("/api/me/changes"),
|
||||
markChangesSeen: () => request<{ lastLookedAt: string }>("/api/me/changes/seen", { method: "POST" }),
|
||||
}),
|
||||
uptime: {
|
||||
get: () => request<UptimeReport>("/api/uptime"),
|
||||
},
|
||||
shareLinks: {
|
||||
list: () => request<{ links: ShareLink[] }>("/api/share-links"),
|
||||
create: (data: { label: string; detail: ShareLinkDetail; expiresInDays: number | null }) =>
|
||||
request<{ link: ShareLink; token: string; path: string }>("/api/share-links", { method: "POST", body: JSON.stringify(data) }),
|
||||
remove: (id: number) => request<void>(`/api/share-links/${id}`, { method: "DELETE" }),
|
||||
},
|
||||
// Opened by someone who isn't signed in: no cookies, and the status is kept so a link that has ended can say so.
|
||||
publicWall: {
|
||||
get: async (token: string): Promise<PublicWall> => {
|
||||
const res = await fetch(`/api/public/wall/${encodeURIComponent(token)}`, { credentials: "omit", cache: "no-store" });
|
||||
if (!res.ok) throw Object.assign(new Error(`Request failed (${res.status})`), { status: res.status });
|
||||
return (await res.json()) as PublicWall;
|
||||
},
|
||||
},
|
||||
search: {
|
||||
query: (q: string) => request<SearchResponse>(`/api/search?q=${encodeURIComponent(q)}`),
|
||||
},
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} 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";
|
||||
@@ -340,7 +341,12 @@ export default function CommandPalette({
|
||||
const items = useMemo(() => {
|
||||
if (terms.length === 0) {
|
||||
const pinned = favorites
|
||||
.map((p) => commands.find((c) => c.key === `page-${p}`))
|
||||
.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"];
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { formatDate, formatTime } from "../utils/date";
|
||||
|
||||
export interface ChartSeries {
|
||||
name: string;
|
||||
color: string;
|
||||
/** SVG dash pattern, so lines can be told apart without their colour. Empty for a solid line. */
|
||||
dash: string;
|
||||
points: { t: string; v: number }[];
|
||||
}
|
||||
|
||||
const W = 720;
|
||||
const H = 260;
|
||||
const PAD = { left: 40, right: 12, top: 10, bottom: 26 };
|
||||
|
||||
/**
|
||||
* Several percentage lines over the same stretch of time, on a fixed 0–100% scale (so a quiet server never looks as busy as a loaded
|
||||
* one). Each line has its own colour and dash pattern. It is a picture: the numbers are in the table beside it.
|
||||
*/
|
||||
export default function MultiLineChart({ series, from, to, label }: { series: ChartSeries[]; from: number; to: number; label: string }) {
|
||||
const x = (t: number) => PAD.left + ((t - from) / Math.max(to - from, 1)) * (W - PAD.left - PAD.right);
|
||||
const y = (v: number) => PAD.top + (1 - Math.min(100, Math.max(0, v)) / 100) * (H - PAD.top - PAD.bottom);
|
||||
|
||||
const ticks = [0, 0.25, 0.5, 0.75, 1].map((f) => from + f * (to - from));
|
||||
const spanDays = (to - from) / 86_400_000;
|
||||
const tickLabel = (t: number) => (spanDays <= 1.5 ? formatTime(new Date(t), false) : formatDate(new Date(t)).replace(/^\d{4}-|\/\d{4}$/, ""));
|
||||
|
||||
return (
|
||||
<svg viewBox={`0 0 ${W} ${H}`} className="multi-chart" role="img" aria-label={label}>
|
||||
{[0, 25, 50, 75, 100].map((v) => (
|
||||
<g key={v}>
|
||||
<line x1={PAD.left} x2={W - PAD.right} y1={y(v)} y2={y(v)} stroke="currentColor" strokeOpacity={v === 0 ? 0.4 : 0.15} />
|
||||
<text x={PAD.left - 6} y={y(v) + 4} textAnchor="end" fontSize="11" fill="currentColor" fillOpacity="0.7">
|
||||
{v}%
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
{ticks.map((t, i) => (
|
||||
<text key={i} x={x(t)} y={H - 6} textAnchor={i === 0 ? "start" : i === ticks.length - 1 ? "end" : "middle"} fontSize="11" fill="currentColor" fillOpacity="0.7">
|
||||
{tickLabel(t)}
|
||||
</text>
|
||||
))}
|
||||
{series.map((s) => {
|
||||
if (s.points.length === 0) return null;
|
||||
const d = s.points.map((p, i) => `${i === 0 ? "M" : "L"}${x(Date.parse(p.t)).toFixed(1)},${y(p.v).toFixed(1)}`).join(" ");
|
||||
return s.points.length === 1 ? (
|
||||
<circle key={s.name} cx={x(Date.parse(s.points[0].t))} cy={y(s.points[0].v)} r="3" fill={s.color} />
|
||||
) : (
|
||||
<path key={s.name} d={d} fill="none" stroke={s.color} strokeWidth="2" strokeDasharray={s.dash || undefined} strokeLinejoin="round" strokeLinecap="round" />
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { IconStar, IconStarFilled } from "@tabler/icons-react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { toggleFavorite, useFavorites } from "../utils/favorites";
|
||||
import { MAX_VIEW_QUERY, canonicalSearch, describeView, hasViewParams } from "../utils/savedViews";
|
||||
import { toast } from "../utils/toast";
|
||||
|
||||
/**
|
||||
* Pins the page as it is now — with its search words, status, tag and sort — to the top of the menu. It appears once something
|
||||
* narrows or orders the table; a page with nothing set is saved with the star in the menu itself.
|
||||
*/
|
||||
export default function SaveViewButton() {
|
||||
const { pathname, search } = useLocation();
|
||||
const favorites = useFavorites();
|
||||
if (!hasViewParams(search)) return null;
|
||||
|
||||
const view = canonicalSearch(search);
|
||||
const path = `${pathname}${view}`;
|
||||
const on = favorites.includes(path);
|
||||
const label = on ? "Remove this view from favourites" : "Save this view to favourites";
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-outline-secondary d-inline-flex align-items-center gap-1"
|
||||
aria-pressed={on}
|
||||
title={`${label}: ${describeView(view)}`}
|
||||
onClick={() => {
|
||||
if (!on && view.length - 1 > MAX_VIEW_QUERY) {
|
||||
toast.info("That view is too long to save. Shorten the search first.");
|
||||
return;
|
||||
}
|
||||
void toggleFavorite(path);
|
||||
}}
|
||||
>
|
||||
{on ? <IconStarFilled size={16} aria-hidden="true" /> : <IconStar size={16} aria-hidden="true" />}
|
||||
<span>{on ? "Saved view" : "Save view"}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { IconSearch } from "@tabler/icons-react";
|
||||
import SaveViewButton from "./SaveViewButton";
|
||||
|
||||
/** The search box every table uses, so they look and behave alike. Esc clears it. */
|
||||
export function SearchBox({
|
||||
@@ -67,6 +68,7 @@ export default function TableToolbar({
|
||||
{filters}
|
||||
{narrowed && <span className="text-secondary small">{shown} of {total}</span>}
|
||||
<div className="table-toolbar-actions">
|
||||
<SaveViewButton />
|
||||
{actions}
|
||||
{onExport && (
|
||||
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={onExport} disabled={exportDisabled}>
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { formatDate, formatTime } from "../utils/date";
|
||||
import { formatRemaining } from "../utils/duration";
|
||||
|
||||
export const REFRESH_MS = 30_000;
|
||||
|
||||
const TYPE_LABELS: Record<string, string> = {
|
||||
tailscale: "Tailscale",
|
||||
proxmox: "Proxmox",
|
||||
synology: "Synology",
|
||||
semaphore: "Semaphore",
|
||||
gitea: "Gitea",
|
||||
dockhand: "Docker",
|
||||
uptimekuma: "Uptime Kuma",
|
||||
phpipam: "phpIPAM",
|
||||
pbs: "Proxmox Backup",
|
||||
osticket: "osTicket",
|
||||
};
|
||||
|
||||
export type WallLevel = "critical" | "warning" | "ok" | "unsure";
|
||||
|
||||
/** Everything the board shows. A list that is null is not shown on this board (a share link that only gives numbers). */
|
||||
export interface WallData {
|
||||
level: WallLevel;
|
||||
headline: string;
|
||||
servers: { online: number; total: number } | null;
|
||||
alerts: { critical: number; warning: number } | null;
|
||||
maintenance: number;
|
||||
integrationsFailing: number | null;
|
||||
problems: { id: string; severity: "critical" | "warning"; message: string }[] | null;
|
||||
windows: { id: number; name: string; endsAt: string }[] | null;
|
||||
integrations: { id: number; name: string; type: string; status: "ok" | "failing" | "unknown" }[] | null;
|
||||
environmentName: string | null;
|
||||
updatedAt: Date | null;
|
||||
}
|
||||
|
||||
/** The headline in words for how many things need a look, or why there is no answer yet. */
|
||||
export function wallHeadline(level: WallLevel, count: number, state: { loaded: boolean; failed: boolean }): string {
|
||||
if (level === "critical" || level === "warning") return `${count} ${count === 1 ? "thing needs" : "things need"} attention`;
|
||||
if (level === "unsure") return state.loaded ? "No alerts — but some checks couldn't run" : state.failed ? "Can't reach the server" : "Checking…";
|
||||
return "All clear";
|
||||
}
|
||||
|
||||
function useClock(): Date {
|
||||
const [now, setNow] = useState(() => new Date());
|
||||
useEffect(() => {
|
||||
const t = setInterval(() => setNow(new Date()), 1000);
|
||||
return () => clearInterval(t);
|
||||
}, []);
|
||||
return now;
|
||||
}
|
||||
|
||||
/** Keeps the screen awake while the page is open, where the browser allows it. */
|
||||
function useWakeLock() {
|
||||
useEffect(() => {
|
||||
let lock: { release: () => Promise<void> } | null = null;
|
||||
let gone = false;
|
||||
const request = async () => {
|
||||
try {
|
||||
const nav = navigator as Navigator & { wakeLock?: { request: (type: "screen") => Promise<{ release: () => Promise<void> }> } };
|
||||
if (nav.wakeLock && !gone) lock = await nav.wakeLock.request("screen");
|
||||
} catch {
|
||||
// not allowed (battery saver, no permission): the screen may sleep like any other
|
||||
}
|
||||
};
|
||||
void request();
|
||||
const onVisible = () => document.visibilityState === "visible" && void request();
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => {
|
||||
gone = true;
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
void lock?.release().catch(() => {});
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* The board itself: a full-screen status picture in type big enough to read across a room. It only draws what it is given, so the
|
||||
* signed-in wall and the one a share link opens look the same and can't drift apart.
|
||||
*/
|
||||
export default function WallView({ data, idle, footerActions }: { data: WallData; idle: boolean; footerActions: ReactNode }) {
|
||||
const now = useClock();
|
||||
useWakeLock();
|
||||
const { level } = data;
|
||||
const offline = data.servers ? data.servers.total - data.servers.online : 0;
|
||||
const alertCount = data.alerts ? data.alerts.critical + data.alerts.warning : 0;
|
||||
const showsDetail = data.problems !== null || data.windows !== null || data.integrations !== null;
|
||||
|
||||
return (
|
||||
<div className={`wall ${idle ? "wall-idle" : ""}`} data-bs-theme="dark">
|
||||
<header className="wall-header">
|
||||
<img src="/logo.webp" alt="Homelab Manager" width={901} height={460} className="wall-logo" />
|
||||
{data.environmentName && <span className="badge env-badge">{data.environmentName}</span>}
|
||||
<div className="wall-clock" aria-label="Time">
|
||||
<div className="wall-time">{formatTime(now, false)}</div>
|
||||
<div className="wall-date">
|
||||
{now.toLocaleDateString([], { weekday: "long" })} {formatDate(now)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className={`wall-status wall-status-${level}`} role="status" aria-live="polite">
|
||||
<span className="wall-status-symbol" aria-hidden="true">
|
||||
{level === "critical" ? "✕" : level === "warning" ? "▲" : level === "ok" ? "✓" : "?"}
|
||||
</span>
|
||||
<span>{data.headline}</span>
|
||||
</section>
|
||||
|
||||
<section className="wall-tiles" aria-label="Summary">
|
||||
<div className={`wall-tile ${offline > 0 ? "wall-tile-bad" : ""}`}>
|
||||
<div className="wall-tile-figure">{data.servers ? (data.servers.total === 0 ? "—" : `${data.servers.online}/${data.servers.total}`) : "…"}</div>
|
||||
<div className="wall-tile-label">servers online</div>
|
||||
</div>
|
||||
<div className={`wall-tile ${(data.alerts?.critical ?? 0) > 0 ? "wall-tile-bad" : (data.alerts?.warning ?? 0) > 0 ? "wall-tile-warn" : ""}`}>
|
||||
<div className="wall-tile-figure">{data.alerts ? alertCount : "…"}</div>
|
||||
<div className="wall-tile-label">alerts{data.alerts && alertCount > 0 ? ` (${data.alerts.critical} critical, ${data.alerts.warning} warning)` : ""}</div>
|
||||
</div>
|
||||
<div className={`wall-tile ${data.maintenance > 0 ? "wall-tile-info" : ""}`}>
|
||||
<div className="wall-tile-figure">{data.maintenance}</div>
|
||||
<div className="wall-tile-label">in maintenance</div>
|
||||
</div>
|
||||
<div className={`wall-tile ${(data.integrationsFailing ?? 0) > 0 ? "wall-tile-bad" : ""}`}>
|
||||
<div className="wall-tile-figure">{data.integrationsFailing === null ? "…" : data.integrationsFailing}</div>
|
||||
<div className="wall-tile-label">integrations failing</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{showsDetail ? (
|
||||
<section className="wall-columns">
|
||||
<div>
|
||||
{data.problems && (
|
||||
<>
|
||||
<h2 className="wall-heading">Needs attention</h2>
|
||||
{data.problems.length === 0 ? (
|
||||
<div className="wall-empty">Nothing right now.</div>
|
||||
) : (
|
||||
<ul className="wall-list">
|
||||
{data.problems.slice(0, 7).map((a) => (
|
||||
<li key={a.id} className={a.severity === "critical" ? "wall-bad" : "wall-warn"}>
|
||||
<span aria-hidden="true">{a.severity === "critical" ? "✕" : "▲"}</span> <span className="visually-hidden">{a.severity}: </span>
|
||||
{a.message}
|
||||
</li>
|
||||
))}
|
||||
{alertCount > 7 && <li className="wall-more">and {alertCount - 7} more</li>}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{data.windows && data.windows.length > 0 && (
|
||||
<>
|
||||
<h2 className="wall-heading mt-4">In maintenance</h2>
|
||||
<ul className="wall-list wall-list-small">
|
||||
{data.windows.slice(0, 8).map((w) => (
|
||||
<li key={w.id}>
|
||||
{w.name} <span className="wall-dim">· {formatRemaining(w.endsAt, now.getTime())} left</span>
|
||||
</li>
|
||||
))}
|
||||
{data.maintenance > 8 && <li className="wall-more">and {data.maintenance - 8} more</li>}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
{data.integrations && (
|
||||
<>
|
||||
<h2 className="wall-heading">Integrations</h2>
|
||||
{data.integrations.length === 0 ? (
|
||||
<div className="wall-empty">None connected.</div>
|
||||
) : (
|
||||
<ul className="wall-list wall-list-small">
|
||||
{data.integrations.map((i) => (
|
||||
<li key={i.id} className={i.status === "failing" ? "wall-bad" : i.status === "ok" ? "wall-good" : "wall-dim"}>
|
||||
<span aria-hidden="true">{i.status === "failing" ? "✕" : i.status === "ok" ? "✓" : "·"}</span> {i.name}{" "}
|
||||
<span className="wall-dim">
|
||||
{TYPE_LABELS[i.type] ?? i.type} — {i.status === "failing" ? "failing" : i.status === "ok" ? "working" : "not checked yet"}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
) : (
|
||||
<section className="wall-columns">
|
||||
<div className="wall-empty">This board shows the numbers only.</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<footer className="wall-footer">
|
||||
<span>
|
||||
{data.updatedAt ? `Updated ${formatTime(data.updatedAt)}` : "Loading…"} · refreshes every {REFRESH_MS / 1000} s
|
||||
</span>
|
||||
<span className="wall-footer-actions">{footerActions}</span>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -13,7 +13,7 @@ function isTyping(target: EventTarget | null): boolean {
|
||||
|
||||
/**
|
||||
* Page shortcuts for anyone signed in: "g" then a letter goes to a page they are allowed to see, "/" jumps to the table's
|
||||
* search box, "?" shows the list. Ignored while typing, while a dialog is open, and with Ctrl/Alt/Cmd held (those are the
|
||||
* search box, "j" and "k" move down and up the table's rows (Enter then opens the one you are on), "?" shows the list. Ignored while typing, while a dialog is open, and with Ctrl/Alt/Cmd held (those are the
|
||||
* browser's and the command palette's).
|
||||
*/
|
||||
export function useShortcuts(user: CurrentUser): void {
|
||||
@@ -47,7 +47,16 @@ export function useShortcuts(user: CurrentUser): void {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (e.key === "g") {
|
||||
if (e.key === "j" || e.key === "k") {
|
||||
const rows = [...document.querySelectorAll<HTMLElement>("tr.row-clickable")].filter((r) => r.offsetParent !== null);
|
||||
if (rows.length === 0) return;
|
||||
const current = (document.activeElement as HTMLElement | null)?.closest<HTMLElement>("tr.row-clickable") ?? null;
|
||||
const at = current ? rows.indexOf(current) : -1;
|
||||
const next = e.key === "j" ? rows[Math.min(at + 1, rows.length - 1)] : rows[Math.max(at - 1, 0)];
|
||||
e.preventDefault();
|
||||
next.focus();
|
||||
next.scrollIntoView({ block: "nearest" });
|
||||
} else if (e.key === "g") {
|
||||
waitingForSecondKey = true;
|
||||
timer = setTimeout(reset, 1200);
|
||||
} else if (e.key === "[") {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
|
||||
export type SortDirection = "asc" | "desc";
|
||||
|
||||
@@ -28,18 +29,42 @@ export function sortItems<T>(items: T[], sortKey: keyof T | undefined, sortDir:
|
||||
* render it — so a formatted "1.2 GB" column still sorts by its raw byte
|
||||
* count, and a "5d 15h 2m" column sorts by its raw timestamp/seconds field.
|
||||
* Nulls/undefined always sort to the end regardless of direction.
|
||||
*
|
||||
* With `{ url: true }` the chosen column and direction live in the address (`?sort=name&dir=desc`) instead of in memory, so the
|
||||
* order survives a reload and goes into a saved view. Meant for the page's main table; the default order leaves the address clean.
|
||||
*/
|
||||
export function useSortable<T>(items: T[] | null | undefined, initialKey?: keyof T, initialDir: SortDirection = "asc") {
|
||||
const [sortKey, setSortKey] = useState<keyof T | undefined>(initialKey);
|
||||
const [sortDir, setSortDir] = useState<SortDirection>(initialDir);
|
||||
export function useSortable<T>(items: T[] | null | undefined, initialKey?: keyof T, initialDir: SortDirection = "asc", options?: { url?: boolean }) {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const [localKey, setLocalKey] = useState<keyof T | undefined>(initialKey);
|
||||
const [localDir, setLocalDir] = useState<SortDirection>(initialDir);
|
||||
|
||||
const useUrl = options?.url === true;
|
||||
const urlKey = params.get("sort");
|
||||
const fromUrl = useUrl && urlKey !== null && /^[A-Za-z0-9_.]{1,40}$/.test(urlKey);
|
||||
const sortKey: keyof T | undefined = fromUrl ? (urlKey as keyof T) : useUrl ? initialKey : localKey;
|
||||
const sortDir: SortDirection = fromUrl ? (params.get("dir") === "desc" ? "desc" : "asc") : useUrl ? initialDir : localDir;
|
||||
|
||||
function requestSort(key: keyof T) {
|
||||
if (sortKey === key) {
|
||||
setSortDir((d) => (d === "asc" ? "desc" : "asc"));
|
||||
} else {
|
||||
setSortKey(key);
|
||||
setSortDir("asc");
|
||||
const nextDir: SortDirection = sortKey === key ? (sortDir === "asc" ? "desc" : "asc") : "asc";
|
||||
if (!useUrl) {
|
||||
setLocalKey(key);
|
||||
setLocalDir(nextDir);
|
||||
return;
|
||||
}
|
||||
setParams(
|
||||
(prev) => {
|
||||
const next = new URLSearchParams(prev);
|
||||
if (key === initialKey && nextDir === initialDir) {
|
||||
next.delete("sort");
|
||||
next.delete("dir");
|
||||
} else {
|
||||
next.set("sort", String(key));
|
||||
next.set("dir", nextDir);
|
||||
}
|
||||
return next;
|
||||
},
|
||||
{ replace: true },
|
||||
);
|
||||
}
|
||||
|
||||
const sorted = useMemo(() => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
|
||||
const haystacks = new WeakMap<object, string>();
|
||||
|
||||
@@ -24,9 +25,26 @@ function haystackOf(row: unknown): string {
|
||||
/**
|
||||
* Text search over a table's rows. Several words must all appear (in any column, in any order), so "elsa running" finds a running
|
||||
* container on elsa. Returns the rows unchanged while the box is empty, and `null`/`undefined` as they came while loading.
|
||||
*
|
||||
* The words live in the address (`?q=elsa running`), so a search survives a reload, can be bookmarked or sent on, and can be pinned as
|
||||
* a saved view. A page has one searchable table, so one `q`; other things in the address are left alone.
|
||||
*/
|
||||
export function useTableSearch<T>(items: T[] | null | undefined) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [params, setParams] = useSearchParams();
|
||||
const query = params.get("q") ?? "";
|
||||
const setQuery = useCallback(
|
||||
(value: string) =>
|
||||
setParams(
|
||||
(prev) => {
|
||||
const next = new URLSearchParams(prev);
|
||||
if (value) next.set("q", value);
|
||||
else next.delete("q");
|
||||
return next;
|
||||
},
|
||||
{ replace: true },
|
||||
),
|
||||
[setParams],
|
||||
);
|
||||
const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
||||
const key = terms.join(" ");
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ 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 { initDashboardLayout } from "../utils/dashboardLayout";
|
||||
import { formatRemaining } from "../utils/duration";
|
||||
import { getTheme, setTheme, type Theme } from "../utils/theme";
|
||||
import { DENSITIES, getDensity, setDensity, type Density } from "../utils/density";
|
||||
@@ -56,6 +57,7 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
|
||||
// This person's pinned pages come with the user; load them before the menu is first drawn.
|
||||
useState(() => {
|
||||
initFavorites(user.favorites);
|
||||
initDashboardLayout(user.dashboard);
|
||||
return null;
|
||||
});
|
||||
// The narrow, icon-only sidebar: remembered per browser (a laptop wants it, a big monitor may not), and only on wide screens.
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { NavLink } from "react-router-dom";
|
||||
import { NavLink, useLocation } 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";
|
||||
import { canonicalSearch, describeView, splitView } from "../utils/savedViews";
|
||||
|
||||
export interface NavBadge {
|
||||
text: string;
|
||||
@@ -40,6 +41,7 @@ export default function SidebarNav({
|
||||
onNavigate: () => void;
|
||||
}) {
|
||||
const favorites = useFavorites();
|
||||
const location = useLocation();
|
||||
const [flyout, setFlyout] = useState<Flyout | null>(null);
|
||||
const flyoutRef = useRef<HTMLDivElement>(null);
|
||||
const opener = useRef<HTMLElement | null>(null);
|
||||
@@ -50,7 +52,12 @@ export default function SidebarNav({
|
||||
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);
|
||||
// A pinned page, or a pinned view of one ("/servers?status=offline"), which is shown under the page's name and what narrows it.
|
||||
const pinned = favorites.flatMap((path) => {
|
||||
const [base, search] = splitView(path);
|
||||
const leaf = leaves.get(base);
|
||||
return leaf ? [{ leaf, path, search }] : [];
|
||||
});
|
||||
|
||||
// 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]);
|
||||
@@ -85,16 +92,33 @@ export default function SidebarNav({
|
||||
) : null;
|
||||
};
|
||||
|
||||
const star = (leaf: NavLeaf) => {
|
||||
const on = favorites.includes(leaf.to);
|
||||
const label = on ? `Remove ${leaf.label} from favourites` : `Add ${leaf.label} to favourites`;
|
||||
const star = (leaf: NavLeaf, path: string = leaf.to, name: string = leaf.label) => {
|
||||
const on = favorites.includes(path);
|
||||
const label = on ? `Remove ${name} from favourites` : `Add ${name} to favourites`;
|
||||
return (
|
||||
<button type="button" className="fav-star" aria-pressed={on} aria-label={label} title={label} onClick={() => void toggleFavorite(leaf.to)}>
|
||||
<button type="button" className="fav-star" aria-pressed={on} aria-label={label} title={label} onClick={() => void toggleFavorite(path)}>
|
||||
{on ? <IconStarFilled size={16} /> : <IconStar size={16} />}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
const viewRow = (leaf: NavLeaf, path: string, search: string) => {
|
||||
const words = describeView(search);
|
||||
const name = `${leaf.label}: ${words}`;
|
||||
const here = location.pathname === leaf.to && canonicalSearch(location.search) === search;
|
||||
return (
|
||||
<li className="nav-item nav-row" key={`fav-${path}`}>
|
||||
<NavLink to={path} className={() => `nav-link ${here ? "active" : ""}`} title={rail ? name : undefined} aria-current={here ? "page" : 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 className="nav-view">{words}</span>
|
||||
</span>
|
||||
</NavLink>
|
||||
{star(leaf, path, name)}
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
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}>
|
||||
@@ -125,7 +149,7 @@ export default function SidebarNav({
|
||||
Favourites
|
||||
</div>
|
||||
<ul className="navbar-nav" aria-labelledby="nav-favourites-heading">
|
||||
{pinned.map((leaf) => leafRow(leaf, `fav-${leaf.to}`))}
|
||||
{pinned.map((p) => (p.search ? viewRow(p.leaf, p.path, p.search) : leafRow(p.leaf, `fav-${p.leaf.to}`)))}
|
||||
</ul>
|
||||
</li>
|
||||
)}
|
||||
|
||||
@@ -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: "j / k", label: "Move down or up the rows of the table on this page (Enter opens the row)" },
|
||||
{ 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" },
|
||||
|
||||
@@ -54,7 +54,7 @@ export default function AuditLog() {
|
||||
}, []);
|
||||
|
||||
const tableSearch = useTableSearch(entries);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "createdAt", "desc");
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "createdAt", "desc", { url: true });
|
||||
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
||||
|
||||
function exportCsv() {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { IconArrowLeft, IconArrowRight, IconEye, IconEyeOff } from "@tabler/icons-react";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import WhatChanged from "../components/WhatChanged";
|
||||
import { UNPLACED, moveCard, resetDashboardLayout, setCardHidden, setEditingDashboard, useDashboardLayout } from "../utils/dashboardLayout";
|
||||
import { Link } from "react-router-dom";
|
||||
import {
|
||||
api,
|
||||
@@ -187,10 +189,30 @@ function MiniStat({ label, value, accent }: { label: string; value: ReactNode; a
|
||||
|
||||
/** The single card shape shared by every dashboard widget — DNS, Secrets, and each integration — so they all read as one family: a label + status badge, then whatever stats/breakdown that widget has. */
|
||||
function WidgetCard({ label, badge, hide, children }: { label: string; badge?: ReactNode; /** Nothing is set up for this yet: it is listed under "Not set up yet" instead of taking a card. */ hide?: boolean; children: ReactNode }) {
|
||||
const { layout, editing } = useDashboardLayout();
|
||||
if (hide) return null;
|
||||
// The person's own arrangement: cards they hid are gone (shown dimmed while arranging, so they can be brought back), and the
|
||||
// rest follow the order they chose — a card nobody has placed goes last, in the order it was drawn.
|
||||
const hidden = layout.hidden.includes(label);
|
||||
if (hidden && !editing) return null;
|
||||
return (
|
||||
<div className="col-md-6">
|
||||
<div className="card h-100">
|
||||
<div className="col-md-6" data-card={label} style={{ order: layout.order[label] ?? UNPLACED }}>
|
||||
<div className={`card h-100 ${hidden ? "card-hidden" : ""}`}>
|
||||
{editing && (
|
||||
<div className="card-customise">
|
||||
<button type="button" className="btn btn-sm btn-icon" aria-label={`Move ${label} earlier`} title="Move earlier" onClick={(e) => void moveCard(e.currentTarget.closest<HTMLElement>("[data-card]")!, -1)}>
|
||||
<IconArrowLeft size={16} aria-hidden="true" />
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-icon" aria-label={`Move ${label} later`} title="Move later" onClick={(e) => void moveCard(e.currentTarget.closest<HTMLElement>("[data-card]")!, 1)}>
|
||||
<IconArrowRight size={16} aria-hidden="true" />
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm ms-auto d-inline-flex align-items-center gap-1" aria-pressed={hidden} onClick={() => void setCardHidden(label, !hidden)}>
|
||||
{hidden ? <IconEye size={16} aria-hidden="true" /> : <IconEyeOff size={16} aria-hidden="true" />}
|
||||
{hidden ? "Show" : "Hide"}
|
||||
<span className="visually-hidden"> {label}</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="card-body">
|
||||
<div className="d-flex align-items-center mb-2">
|
||||
<div className="subheader">{label}</div>
|
||||
@@ -291,6 +313,7 @@ function formatBytes(bytes: number | null): string {
|
||||
}
|
||||
|
||||
export default function Dashboard({ user }: { user: CurrentUser }) {
|
||||
const { editing } = useDashboardLayout();
|
||||
const [integrations, setIntegrations] = useState<IntegrationSummary[] | null>(null);
|
||||
const [tailscaleSummary, setTailscaleSummary] = useState<TailscaleDevicesResponse["summary"] | null>(null);
|
||||
const [tailscaleExtra, setTailscaleExtra] = useState<TailscaleExtra | null>(null);
|
||||
@@ -588,10 +611,23 @@ export default function Dashboard({ user }: { user: CurrentUser }) {
|
||||
<div className="col-12">
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-3">
|
||||
<h2 className="page-title mb-0">Dashboard</h2>
|
||||
<Link to="/wall" className="btn btn-sm btn-outline-secondary ms-auto" title="A full-screen status board for a spare monitor or tablet">
|
||||
Wall display
|
||||
</Link>
|
||||
<div className="ms-auto d-flex gap-2">
|
||||
<button type="button" className={`btn btn-sm ${editing ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={editing} onClick={() => setEditingDashboard(!editing)}>
|
||||
{editing ? "Done" : "Customise"}
|
||||
</button>
|
||||
<Link to="/wall" className="btn btn-sm btn-outline-secondary" title="A full-screen status board for a spare monitor or tablet">
|
||||
Wall display
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
{editing && (
|
||||
<div className="alert alert-info d-flex flex-wrap align-items-center gap-2" role="status">
|
||||
<span>Move the cards with the arrows and hide the ones you don't use. It saves as you go, for you only, and follows you to other browsers.</span>
|
||||
<button type="button" className="btn btn-sm ms-auto" onClick={() => void resetDashboardLayout()}>
|
||||
Reset to default
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-secondary">
|
||||
Welcome back, {user.name ?? user.email ?? user.sub}.
|
||||
</p>
|
||||
@@ -760,7 +796,12 @@ export default function Dashboard({ user }: { user: CurrentUser }) {
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
{serverSummary.offline.length > 3 && <span className="text-secondary"> +{serverSummary.offline.length - 3} more</span>}
|
||||
{serverSummary.offline.length > 3 && (
|
||||
<>
|
||||
{" "}
|
||||
<Link to="/servers?status=offline">+{serverSummary.offline.length - 3} more</Link>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{serverSummary.fullDisks.length > 0 && (
|
||||
|
||||
@@ -98,7 +98,7 @@ export default function Docker({ user }: { user: CurrentUser }) {
|
||||
const filteredContainers = (data?.containers ?? []).filter((c) => !hostFilter || c.environmentName === hostFilter);
|
||||
|
||||
const tableSearch = useTableSearch(filteredContainers);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, undefined, "asc", { url: true });
|
||||
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
||||
const detail = useRowDetail<NonNullable<typeof pageItems>[number]>();
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ export default function Domains({ user }: { user: CurrentUser }) {
|
||||
}, []);
|
||||
|
||||
const tableSearch = useTableSearch(data?.domains);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "expiresAt");
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "expiresAt", "asc", { url: true });
|
||||
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
||||
|
||||
async function add(e: React.FormEvent) {
|
||||
|
||||
@@ -99,7 +99,7 @@ export default function Gitea({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
|
||||
const tableSearch = useTableSearch(repos);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, undefined, "asc", { url: true });
|
||||
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
||||
const detail = useRowDetail<NonNullable<typeof pageItems>[number]>();
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ function typeBadgeStyle(colors: Record<string, string>, type: IntegrationType):
|
||||
|
||||
export default function Integrations({ user }: { user: CurrentUser }) {
|
||||
const isAdmin = user.role === "admin";
|
||||
const [searchParams] = useSearchParams();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const [integrations, setIntegrations] = useState<IntegrationSummary[] | null>(null);
|
||||
const [adding, setAdding] = useState(false);
|
||||
@@ -137,7 +137,12 @@ export default function Integrations({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
|
||||
const tableSearch = useTableSearch(integrations);
|
||||
const sortedIntegrations = tableSearch.filtered ? [...tableSearch.filtered].sort((a, b) => a.name.localeCompare(b.name)) : null;
|
||||
const statusParam = searchParams.get("status");
|
||||
const statusFilter = statusParam === "failing" || statusParam === "working" || statusParam === "disabled" ? statusParam : "";
|
||||
const matchesStatus = (i: IntegrationSummary) =>
|
||||
statusFilter === "" ||
|
||||
(statusFilter === "disabled" ? !i.enabled : statusFilter === "failing" ? i.enabled && i.health?.status === "failing" : i.enabled && i.health?.status === "ok");
|
||||
const sortedIntegrations = tableSearch.filtered ? [...tableSearch.filtered].filter(matchesStatus).sort((a, b) => a.name.localeCompare(b.name)) : null;
|
||||
|
||||
function exportCsv() {
|
||||
if (!sortedIntegrations) return;
|
||||
@@ -192,6 +197,29 @@ export default function Integrations({ user }: { user: CurrentUser }) {
|
||||
search={tableSearch.query}
|
||||
onSearch={tableSearch.setQuery}
|
||||
placeholder="Search integrations…"
|
||||
filters={
|
||||
<select
|
||||
className="form-select form-select-sm w-auto"
|
||||
aria-label="Show integrations that are"
|
||||
value={statusFilter}
|
||||
onChange={(e) =>
|
||||
setSearchParams(
|
||||
(prev) => {
|
||||
const next = new URLSearchParams(prev);
|
||||
if (e.target.value) next.set("status", e.target.value);
|
||||
else next.delete("status");
|
||||
return next;
|
||||
},
|
||||
{ replace: true },
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Any status</option>
|
||||
<option value="failing">Failing</option>
|
||||
<option value="working">Working</option>
|
||||
<option value="disabled">Disabled</option>
|
||||
</select>
|
||||
}
|
||||
shown={sortedIntegrations?.length}
|
||||
total={integrations?.length}
|
||||
onExport={exportCsv}
|
||||
@@ -262,8 +290,8 @@ export default function Integrations({ user }: { user: CurrentUser }) {
|
||||
<div className="col-12">
|
||||
<div className="card">
|
||||
<div className="card-body text-secondary text-center">
|
||||
{tableSearch.active ? "Nothing matches that search." : "No integrations configured yet."}
|
||||
{isAdmin && !tableSearch.active && (
|
||||
{tableSearch.active || statusFilter ? "Nothing matches that." : "No integrations configured yet."}
|
||||
{isAdmin && !tableSearch.active && !statusFilter && (
|
||||
<>
|
||||
{" "}
|
||||
<button className="btn btn-link p-0 align-baseline" onClick={() => setAdding(true)}>
|
||||
|
||||
@@ -62,7 +62,7 @@ export default function OsTicket({ user: _user }: { user: CurrentUser }) {
|
||||
}, [selectedId]);
|
||||
|
||||
const tableSearch = useTableSearch(data?.tickets);
|
||||
const { sorted: sortedTickets, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered);
|
||||
const { sorted: sortedTickets, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, undefined, "asc", { url: true });
|
||||
|
||||
function exportCsv() {
|
||||
if (!sortedTickets) return;
|
||||
|
||||
@@ -199,7 +199,7 @@ export default function Proxmox({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
|
||||
const tableSearch = useTableSearch(data?.guests);
|
||||
const { sorted: sortedGuests, sortKey: guestSortKey, sortDir: guestSortDir, requestSort: requestGuestSort } = useSortable(tableSearch.filtered);
|
||||
const { sorted: sortedGuests, sortKey: guestSortKey, sortDir: guestSortDir, requestSort: requestGuestSort } = useSortable(tableSearch.filtered, undefined, "asc", { url: true });
|
||||
const { pageItems: guestPageItems, page: guestPage, setPage: setGuestPage, pageCount: guestPageCount, totalCount: guestTotalCount } =
|
||||
usePagination(sortedGuests);
|
||||
const detail = useRowDetail<NonNullable<typeof guestPageItems>[number]>();
|
||||
|
||||
@@ -107,7 +107,7 @@ export default function Semaphore({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
|
||||
const tableSearch = useTableSearch(data?.templates);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, undefined, "asc", { url: true });
|
||||
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
||||
const detail = useRowDetail<NonNullable<typeof pageItems>[number]>();
|
||||
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { api, type ServerMetricSeries, type ServerRecord } from "../api/client";
|
||||
import MultiLineChart, { type ChartSeries } from "../components/MultiLineChart";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
|
||||
const MAX_SERVERS = 4;
|
||||
const RANGES = [
|
||||
{ days: 1, label: "24 hours" },
|
||||
{ days: 7, label: "7 days" },
|
||||
{ days: 30, label: "30 days" },
|
||||
];
|
||||
// A colour and a dash pattern for each line, so they can be told apart by either.
|
||||
const LOOKS = [
|
||||
{ color: "#4299e1", dash: "" },
|
||||
{ color: "#f59f00", dash: "7 4" },
|
||||
{ color: "#2fb344", dash: "2 4" },
|
||||
{ color: "#ae3ec9", dash: "9 3 2 3" },
|
||||
];
|
||||
|
||||
interface Loaded {
|
||||
server: ServerRecord;
|
||||
series: ServerMetricSeries[] | null;
|
||||
}
|
||||
|
||||
function percent(v: number | null | undefined): string {
|
||||
return v === null || v === undefined ? "—" : `${Math.round(v)}%`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Two to four servers' load, memory or a disk on one chart, so "which of them is the busy one" and "did they spike together" are
|
||||
* answered at a glance. Uses the same history as each server's own Trends card; servers without an agent have none to draw.
|
||||
*/
|
||||
export default function ServerCompare() {
|
||||
const [params] = useSearchParams();
|
||||
const ids = useMemo(() => {
|
||||
const seen = new Set<number>();
|
||||
for (const part of (params.get("ids") ?? "").split(",")) {
|
||||
const n = Number(part);
|
||||
if (Number.isInteger(n) && n > 0) seen.add(n);
|
||||
}
|
||||
return [...seen].slice(0, MAX_SERVERS);
|
||||
}, [params]);
|
||||
|
||||
const [days, setDays] = useState(7);
|
||||
const [metric, setMetric] = useState("cpu");
|
||||
const [loaded, setLoaded] = useState<Loaded[] | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [to, setTo] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
if (ids.length < 2) return;
|
||||
let alive = true;
|
||||
setFailed(false);
|
||||
setLoaded(null);
|
||||
Promise.all([api.servers.list(), ...ids.map((id) => api.servers.metrics(id, days).catch(() => null))])
|
||||
.then(([list, ...metrics]) => {
|
||||
if (!alive) return;
|
||||
const byId = new Map((list as { servers: ServerRecord[] }).servers.map((s) => [s.id, s]));
|
||||
setTo(Date.now());
|
||||
setLoaded(
|
||||
ids.flatMap((id, i) => {
|
||||
const server = byId.get(id);
|
||||
const m = metrics[i] as { series: ServerMetricSeries[] } | null;
|
||||
return server ? [{ server, series: m ? m.series : null }] : [];
|
||||
}),
|
||||
);
|
||||
})
|
||||
.catch(() => alive && setFailed(true));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [ids, days]);
|
||||
|
||||
// Every measure at least one of them has: load, memory, and each disk by its mount.
|
||||
const metrics = useMemo(() => {
|
||||
const found = new Map<string, string>([
|
||||
["cpu", "CPU load"],
|
||||
["mem", "Memory"],
|
||||
]);
|
||||
for (const l of loaded ?? []) for (const s of l.series ?? []) if (s.kind === "disk") found.set(s.metric, s.label);
|
||||
return [...found.entries()];
|
||||
}, [loaded]);
|
||||
const metricName = metrics.find(([key]) => key === metric)?.[1] ?? "CPU load";
|
||||
|
||||
const rows = (loaded ?? []).map((l, i) => {
|
||||
const s = l.series?.find((x) => x.metric === metric) ?? null;
|
||||
const values = s?.points.map((p) => p.v) ?? [];
|
||||
return {
|
||||
server: l.server,
|
||||
look: LOOKS[i % LOOKS.length],
|
||||
series: s,
|
||||
now: s?.latest ?? null,
|
||||
average: values.length ? values.reduce((a, b) => a + b, 0) / values.length : null,
|
||||
peak: values.length ? Math.max(...values) : null,
|
||||
hasAgent: l.series !== null,
|
||||
};
|
||||
});
|
||||
const chart: ChartSeries[] = rows.filter((r) => r.series).map((r) => ({ name: r.server.name, color: r.look.color, dash: r.look.dash, points: r.series!.points }));
|
||||
const summary = `${metricName} over the last ${RANGES.find((r) => r.days === days)?.label}: ${rows.map((r) => `${r.server.name} ${percent(r.now)} now`).join(", ")}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-3">
|
||||
<h2 className="page-title mb-0">Compare servers</h2>
|
||||
<Link to="/servers" className="btn btn-sm btn-outline-secondary ms-auto">
|
||||
Pick different servers
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{ids.length < 2 ? (
|
||||
<div className="card">
|
||||
<div className="card-body text-secondary">
|
||||
Pick two to {MAX_SERVERS} servers to compare. On the <Link to="/servers">Servers</Link> page, press Compare and choose them.
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header d-flex flex-wrap gap-2">
|
||||
<h3 className="card-title me-auto">{metricName}</h3>
|
||||
<select className="form-select form-select-sm w-auto" aria-label="What to compare" value={metric} onChange={(e) => setMetric(e.target.value)}>
|
||||
{metrics.map(([key, name]) => (
|
||||
<option key={key} value={key}>
|
||||
{name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select className="form-select form-select-sm w-auto" aria-label="Time range" value={days} onChange={(e) => setDays(Number(e.target.value))}>
|
||||
{RANGES.map((r) => (
|
||||
<option key={r.days} value={r.days}>
|
||||
Last {r.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
{failed ? (
|
||||
<div className="text-secondary">Couldn't load the history.</div>
|
||||
) : loaded === null ? (
|
||||
<BlockSkeleton lines={5} />
|
||||
) : (
|
||||
<>
|
||||
{chart.length === 0 ? (
|
||||
<div className="text-secondary mb-3">None of these servers has a history for this yet. A sample is kept about every ten minutes once an agent has reported.</div>
|
||||
) : (
|
||||
<MultiLineChart series={chart} from={to - days * 86_400_000} to={to} label={summary} />
|
||||
)}
|
||||
<div className="table-responsive mt-3">
|
||||
<table className="table table-vcenter">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Server</th>
|
||||
<th>Now</th>
|
||||
<th>Average</th>
|
||||
<th>Peak</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
<tr key={r.server.id}>
|
||||
<td>
|
||||
<svg width="34" height="10" aria-hidden="true" className="me-2">
|
||||
<line x1="1" x2="33" y1="5" y2="5" stroke={r.look.color} strokeWidth="3" strokeDasharray={r.look.dash || undefined} strokeLinecap="round" />
|
||||
</svg>
|
||||
<Link to={`/servers/${r.server.id}`}>{r.server.name}</Link>
|
||||
</td>
|
||||
{r.series ? (
|
||||
<>
|
||||
<td>{percent(r.now)}</td>
|
||||
<td>{percent(r.average)}</td>
|
||||
<td>{percent(r.peak)}</td>
|
||||
</>
|
||||
) : (
|
||||
<td colSpan={3} className="text-secondary">
|
||||
{r.hasAgent ? "No history for this" : "No agent history (not reported by an agent)"}
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+150
-36
@@ -18,6 +18,7 @@ import { ErrorNotice } from "../components/Notice";
|
||||
import { toast } from "../utils/toast";
|
||||
import { SearchBox } from "../components/TableToolbar";
|
||||
import { useTableSearch } from "../hooks/useTableSearch";
|
||||
import SaveViewButton from "../components/SaveViewButton";
|
||||
|
||||
function typeBadgeStyle(colors: Record<string, string>, type: string): CSSProperties {
|
||||
const color = colors[type];
|
||||
@@ -36,8 +37,22 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
// The active tag filter lives in the URL, so a tag chip on a server's page can link straight to "everything with this tag".
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const selectedTags = searchParams.getAll("tag");
|
||||
// So is the status chosen ("?status=offline"), which the dashboard links to.
|
||||
const statusParam = searchParams.get("status");
|
||||
const status: "offline" | "online" | null = statusParam === "offline" || statusParam === "online" ? statusParam : null;
|
||||
const [offlineIds, setOfflineIds] = useState<Set<number> | null>(null);
|
||||
// Picking servers to compare their trends side by side.
|
||||
const [comparing, setComparing] = useState(false);
|
||||
const [picked, setPicked] = useState<number[]>([]);
|
||||
const tagColors = useTagColors();
|
||||
|
||||
useEffect(() => {
|
||||
api.servers
|
||||
.summary()
|
||||
.then((res) => setOfflineIds(new Set(res.offline.map((o) => o.id))))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
api.settings.integrationColors().then((res) => setIntegrationColors(res.integrationColors)).catch(() => {});
|
||||
}, []);
|
||||
@@ -104,7 +119,7 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
|
||||
const tableSearch = useTableSearch(servers);
|
||||
const { sorted: sortedServers, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered);
|
||||
const { sorted: sortedServers, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, undefined, "asc", { url: true });
|
||||
const { pageItems: serverPageItems, page: serverPage, setPage: setServerPage, pageCount: serverPageCount, totalCount: serverTotalCount } =
|
||||
usePagination(sortedServers);
|
||||
|
||||
@@ -113,13 +128,81 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
// A tag from the URL that no server has (any more) stays listed, so it can still be switched off.
|
||||
for (const t of selectedTags) if (!tagCounts.has(t)) tagCounts.set(t, 0);
|
||||
const allTags = [...tagCounts.keys()].sort((a, b) => a.localeCompare(b, "sv"));
|
||||
const visibleServers = servers.filter((s) => selectedTags.every((t) => s.tags.includes(t)));
|
||||
const matchesSearch = new Set((tableSearch.filtered ?? servers).map((s) => s.id));
|
||||
const visibleServers = servers.filter((s) => {
|
||||
if (!selectedTags.every((t) => s.tags.includes(t))) return false;
|
||||
if (!matchesSearch.has(s.id)) return false;
|
||||
if (status === "offline") return offlineIds?.has(s.id) ?? false;
|
||||
if (status === "online") return !!s.lastSeenAt && !(offlineIds?.has(s.id) ?? false);
|
||||
return true;
|
||||
});
|
||||
const offlineCount = servers.filter((s) => offlineIds?.has(s.id)).length;
|
||||
const onlineCount = servers.filter((s) => s.lastSeenAt && !offlineIds?.has(s.id)).length;
|
||||
|
||||
// Change one part of the address and keep the rest (the search words, the sort).
|
||||
function changeParams(change: (next: URLSearchParams) => void) {
|
||||
setSearchParams(
|
||||
(prev) => {
|
||||
const next = new URLSearchParams(prev);
|
||||
change(next);
|
||||
return next;
|
||||
},
|
||||
{ replace: true },
|
||||
);
|
||||
}
|
||||
|
||||
function toggleTag(tag: string) {
|
||||
const next = selectedTags.includes(tag) ? selectedTags.filter((t) => t !== tag) : [...selectedTags, tag];
|
||||
setSearchParams(next.length > 0 ? { tag: next } : {}, { replace: true });
|
||||
changeParams((next) => {
|
||||
const current = next.getAll("tag");
|
||||
next.delete("tag");
|
||||
for (const t of current.includes(tag) ? current.filter((x) => x !== tag) : [...current, tag]) next.append("tag", t);
|
||||
});
|
||||
}
|
||||
|
||||
function setStatus(value: "offline" | "online" | null) {
|
||||
changeParams((next) => (value ? next.set("status", value) : next.delete("status")));
|
||||
}
|
||||
|
||||
const MAX_COMPARE = 4;
|
||||
function togglePicked(id: number) {
|
||||
setPicked((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : prev.length >= MAX_COMPARE ? prev : [...prev, id]));
|
||||
}
|
||||
function stopComparing() {
|
||||
setComparing(false);
|
||||
setPicked([]);
|
||||
}
|
||||
|
||||
const cardBody = (s: ServerRecord) => (
|
||||
<div className="card-body">
|
||||
<div className="d-flex align-items-center">
|
||||
<div className="flex-fill">
|
||||
<div className="font-weight-medium">{s.name}</div>
|
||||
<div className="text-secondary small">{s.hostname ?? "no hostname reported"}</div>
|
||||
</div>
|
||||
{s.proxmoxIntegrationId ? (
|
||||
<span className="badge" style={typeBadgeStyle(integrationColors, "proxmox")}>
|
||||
Proxmox
|
||||
</span>
|
||||
) : s.lastSeenAt ? (
|
||||
<span className="badge bg-green-lt text-green">Agent</span>
|
||||
) : (
|
||||
<span className="badge bg-secondary-lt text-secondary">No data</span>
|
||||
)}
|
||||
</div>
|
||||
{s.tags.length > 0 && (
|
||||
<div className="d-flex flex-wrap gap-1 mt-2">
|
||||
<TagBadges tags={s.tags} />
|
||||
</div>
|
||||
)}
|
||||
<div className="text-secondary small mt-2">
|
||||
{s.lastSeenAt ? <>Last seen <TimeAgo value={s.lastSeenAt} /></> : "Never reported"}
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<UptimeRibbon kind="servers" id={s.id} name={s.name} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
function exportCsv() {
|
||||
if (!sortedServers) return;
|
||||
downloadCsv(
|
||||
@@ -359,6 +442,49 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-3">
|
||||
<SearchBox value={tableSearch.query} onChange={tableSearch.setQuery} placeholder="Search servers…" />
|
||||
<div className="btn-group btn-group-sm" role="group" aria-label="Show servers that are">
|
||||
<button type="button" className={`btn btn-sm ${status === null ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={status === null} onClick={() => setStatus(null)}>
|
||||
All
|
||||
</button>
|
||||
<button type="button" className={`btn btn-sm ${status === "offline" ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={status === "offline"} onClick={() => setStatus("offline")}>
|
||||
Not reporting{offlineIds ? ` (${offlineCount})` : ""}
|
||||
</button>
|
||||
<button type="button" className={`btn btn-sm ${status === "online" ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={status === "online"} onClick={() => setStatus("online")}>
|
||||
Reporting{offlineIds ? ` (${onlineCount})` : ""}
|
||||
</button>
|
||||
</div>
|
||||
<div className="ms-auto d-flex flex-wrap gap-2">
|
||||
<SaveViewButton />
|
||||
{servers.length > 1 && (
|
||||
<button type="button" className={`btn btn-sm ${comparing ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={comparing} onClick={() => (comparing ? stopComparing() : setComparing(true))}>
|
||||
Compare
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{comparing && (
|
||||
<div className="alert alert-info d-flex flex-wrap align-items-center gap-2" role="status">
|
||||
<span>
|
||||
Pick two to {MAX_COMPARE} servers to compare their load, memory and disks side by side. {picked.length} picked.
|
||||
</span>
|
||||
<div className="ms-auto d-flex gap-2">
|
||||
{picked.length >= 2 ? (
|
||||
<Link to={`/servers/compare?ids=${picked.join(",")}`} className="btn btn-sm btn-primary">
|
||||
Compare {picked.length} servers
|
||||
</Link>
|
||||
) : (
|
||||
<button type="button" className="btn btn-sm btn-primary" disabled>
|
||||
Compare
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn btn-sm" onClick={stopComparing}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{allTags.length > 0 && (
|
||||
<div className="d-flex flex-wrap align-items-center gap-1 mb-3">
|
||||
<span className="text-secondary small me-1">Tags</span>
|
||||
@@ -379,7 +505,7 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
);
|
||||
})}
|
||||
{selectedTags.length > 0 && (
|
||||
<button type="button" className="btn btn-link btn-sm p-0 ms-1" onClick={() => setSearchParams({}, { replace: true })}>
|
||||
<button type="button" className="btn btn-link btn-sm p-0 ms-1" onClick={() => changeParams((next) => next.delete("tag"))}>
|
||||
Clear
|
||||
</button>
|
||||
)}
|
||||
@@ -387,42 +513,30 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
)}
|
||||
{visibleServers.length === 0 && (
|
||||
<div className="card">
|
||||
<div className="card-body text-secondary">No server has {selectedTags.length > 1 ? "all of those tags" : "that tag"}.</div>
|
||||
<div className="card-body text-secondary">
|
||||
{selectedTags.length > 0 && !status && !tableSearch.active
|
||||
? `No server has ${selectedTags.length > 1 ? "all of those tags" : "that tag"}.`
|
||||
: "No server matches that."}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="row row-cards">
|
||||
{visibleServers.map((s) => (
|
||||
<div className="col-sm-6 col-lg-3" key={s.id}>
|
||||
<Link to={`/servers/${s.id}`} className="card card-sm text-reset text-decoration-none">
|
||||
<div className="card-body">
|
||||
<div className="d-flex align-items-center">
|
||||
<div className="flex-fill">
|
||||
<div className="font-weight-medium">{s.name}</div>
|
||||
<div className="text-secondary small">{s.hostname ?? "no hostname reported"}</div>
|
||||
</div>
|
||||
{s.proxmoxIntegrationId ? (
|
||||
<span className="badge" style={typeBadgeStyle(integrationColors, "proxmox")}>
|
||||
Proxmox
|
||||
</span>
|
||||
) : s.lastSeenAt ? (
|
||||
<span className="badge bg-green-lt text-green">Agent</span>
|
||||
) : (
|
||||
<span className="badge bg-secondary-lt text-secondary">No data</span>
|
||||
)}
|
||||
</div>
|
||||
{s.tags.length > 0 && (
|
||||
<div className="d-flex flex-wrap gap-1 mt-2">
|
||||
<TagBadges tags={s.tags} />
|
||||
</div>
|
||||
)}
|
||||
<div className="text-secondary small mt-2">
|
||||
{s.lastSeenAt ? <>Last seen <TimeAgo value={s.lastSeenAt} /></> : "Never reported"}
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<UptimeRibbon kind="servers" id={s.id} name={s.name} />
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
{comparing ? (
|
||||
<button
|
||||
type="button"
|
||||
className={`card card-sm text-reset text-start w-100 compare-card ${picked.includes(s.id) ? "compare-card-on" : ""}`}
|
||||
aria-pressed={picked.includes(s.id)}
|
||||
onClick={() => togglePicked(s.id)}
|
||||
>
|
||||
{cardBody(s)}
|
||||
</button>
|
||||
) : (
|
||||
<Link to={`/servers/${s.id}`} className="card card-sm text-reset text-decoration-none">
|
||||
{cardBody(s)}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -77,7 +77,7 @@ export default function Sessions() {
|
||||
}
|
||||
|
||||
const tableSearch = useTableSearch(sessions);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, undefined, "asc", { url: true });
|
||||
|
||||
function exportCsv() {
|
||||
if (!sorted) return;
|
||||
|
||||
@@ -8,6 +8,7 @@ const SUB_NAV = [
|
||||
{ to: "/settings/tags", label: "Tags" },
|
||||
{ to: "/settings/alert-tickets", label: "Alert tickets" },
|
||||
{ to: "/settings/names", label: "Names" },
|
||||
{ to: "/settings/share", label: "Share links" },
|
||||
{ to: "/settings/cache", label: "Cache" },
|
||||
{ to: "/settings/logs", label: "Logs" },
|
||||
{ to: "/settings/backup", label: "Backup" },
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { api, type PublicWall } from "../api/client";
|
||||
import WallView, { REFRESH_MS, wallHeadline, type WallData } from "../components/WallView";
|
||||
import { setDateTimeSettings } from "../utils/date";
|
||||
|
||||
/**
|
||||
* The wall display behind a share link: the same board, read-only and without signing in. The address carries the secret, and the
|
||||
* server decides how much it may show — this only draws what comes back. A link that doesn't work (never made, ended, taken back)
|
||||
* says so and stops asking.
|
||||
*/
|
||||
export default function SharedWall() {
|
||||
const { token = "" } = useParams();
|
||||
const [wall, setWall] = useState<PublicWall | null>(null);
|
||||
const [state, setState] = useState<"loading" | "ok" | "dead" | "unreachable">("loading");
|
||||
const [updatedAt, setUpdatedAt] = useState<Date | null>(null);
|
||||
const [idle, setIdle] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
const load = () =>
|
||||
api.publicWall
|
||||
.get(token)
|
||||
.then((w) => {
|
||||
if (!alive) return;
|
||||
setDateTimeSettings({ dateFormat: w.display.dateFormat as "ymd" | "dmy" | "mdy", timeFormat: w.display.timeFormat as "24h" | "12h" });
|
||||
setWall(w);
|
||||
setUpdatedAt(new Date());
|
||||
setState("ok");
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!alive) return;
|
||||
const status = (err as { status?: number }).status;
|
||||
if (status === 404 || status === 429) {
|
||||
// 404: this link doesn't work (any more). Asking again would only repeat that.
|
||||
if (status === 404) {
|
||||
setState("dead");
|
||||
if (timer) clearInterval(timer);
|
||||
}
|
||||
return;
|
||||
}
|
||||
setState((s) => (s === "ok" ? "ok" : "unreachable"));
|
||||
});
|
||||
void load();
|
||||
timer = setInterval(load, REFRESH_MS);
|
||||
return () => {
|
||||
alive = false;
|
||||
if (timer) clearInterval(timer);
|
||||
};
|
||||
}, [token]);
|
||||
|
||||
// The pointer hides itself when nobody is using it.
|
||||
useEffect(() => {
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const onMove = () => {
|
||||
setIdle(false);
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => setIdle(true), 5000);
|
||||
};
|
||||
onMove();
|
||||
window.addEventListener("mousemove", onMove);
|
||||
return () => {
|
||||
window.removeEventListener("mousemove", onMove);
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (state === "dead") {
|
||||
return (
|
||||
<div className="wall" data-bs-theme="dark">
|
||||
<section className="wall-status wall-status-unsure" role="alert">
|
||||
<span className="wall-status-symbol" aria-hidden="true">
|
||||
?
|
||||
</span>
|
||||
<span>This link doesn't work any more</span>
|
||||
</section>
|
||||
<div className="wall-empty">It may have ended or been taken back. Ask whoever gave it to you for a new one.</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const count = wall ? wall.alerts.critical + wall.alerts.warning : 0;
|
||||
const data: WallData = {
|
||||
level: wall?.level ?? "unsure",
|
||||
headline: wallHeadline(wall?.level ?? "unsure", count, { loaded: !!wall, failed: state === "unreachable" }),
|
||||
servers: wall ? { online: wall.servers.online, total: wall.servers.online + wall.servers.offline } : null,
|
||||
alerts: wall ? wall.alerts : null,
|
||||
maintenance: wall?.maintenance ?? 0,
|
||||
integrationsFailing: wall ? wall.integrationsFailing : null,
|
||||
problems: wall?.problems ?? null,
|
||||
windows: wall?.maintenanceWindows ?? null,
|
||||
integrations: (wall?.integrations as WallData["integrations"]) ?? null,
|
||||
environmentName: wall?.environment ?? null,
|
||||
updatedAt,
|
||||
};
|
||||
|
||||
return (
|
||||
<WallView
|
||||
data={data}
|
||||
idle={idle}
|
||||
footerActions={
|
||||
<button type="button" className="wall-link" onClick={() => void document.documentElement.requestFullscreen?.().catch(() => {})}>
|
||||
Full screen
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -144,7 +144,7 @@ export default function Tailscale({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
|
||||
const tableSearch = useTableSearch(data?.devices);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, undefined, "asc", { url: true });
|
||||
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
||||
const detail = useRowDetail<NonNullable<typeof pageItems>[number]>();
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ export default function UptimeKuma({ user: _user }: { user: CurrentUser }) {
|
||||
}, [selectedId]);
|
||||
|
||||
const tableSearch = useTableSearch(data?.monitors);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "name");
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "name", "asc", { url: true });
|
||||
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
||||
const detail = useRowDetail<NonNullable<typeof pageItems>[number]>();
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ export default function Users() {
|
||||
}
|
||||
|
||||
const tableSearch = useTableSearch(users);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, undefined, "asc", { url: true });
|
||||
|
||||
function exportCsv() {
|
||||
if (!sorted) return;
|
||||
|
||||
+26
-165
@@ -3,56 +3,7 @@ import { Link, useNavigate } from "react-router-dom";
|
||||
import { api, type IntegrationSummary, type MaintenanceWindow, type ServerSummary } from "../api/client";
|
||||
import { alertBadge, useAlertsReport } from "../hooks/useAlertsReport";
|
||||
import { useEnvironment } from "../utils/environment";
|
||||
import { formatRemaining } from "../utils/duration";
|
||||
import { formatDate, formatTime } from "../utils/date";
|
||||
|
||||
const REFRESH_MS = 30_000;
|
||||
|
||||
const TYPE_LABELS: Record<IntegrationSummary["type"], string> = {
|
||||
tailscale: "Tailscale",
|
||||
proxmox: "Proxmox",
|
||||
synology: "Synology",
|
||||
semaphore: "Semaphore",
|
||||
gitea: "Gitea",
|
||||
dockhand: "Docker",
|
||||
uptimekuma: "Uptime Kuma",
|
||||
phpipam: "phpIPAM",
|
||||
pbs: "Proxmox Backup",
|
||||
osticket: "osTicket",
|
||||
};
|
||||
|
||||
function useClock(): Date {
|
||||
const [now, setNow] = useState(() => new Date());
|
||||
useEffect(() => {
|
||||
const t = setInterval(() => setNow(new Date()), 1000);
|
||||
return () => clearInterval(t);
|
||||
}, []);
|
||||
return now;
|
||||
}
|
||||
|
||||
/** Keeps the screen awake while the page is open, where the browser allows it. */
|
||||
function useWakeLock() {
|
||||
useEffect(() => {
|
||||
let lock: { release: () => Promise<void> } | null = null;
|
||||
let gone = false;
|
||||
const request = async () => {
|
||||
try {
|
||||
const nav = navigator as Navigator & { wakeLock?: { request: (type: "screen") => Promise<{ release: () => Promise<void> }> } };
|
||||
if (nav.wakeLock && !gone) lock = await nav.wakeLock.request("screen");
|
||||
} catch {
|
||||
// not allowed (battery saver, no permission): the screen may sleep like any other
|
||||
}
|
||||
};
|
||||
void request();
|
||||
const onVisible = () => document.visibilityState === "visible" && void request();
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => {
|
||||
gone = true;
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
void lock?.release().catch(() => {});
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
import WallView, { REFRESH_MS, wallHeadline, type WallData } from "../components/WallView";
|
||||
|
||||
/**
|
||||
* A full-screen status board for a spare monitor or tablet: how things are, in type big enough to read across a room, refreshing
|
||||
@@ -61,14 +12,12 @@ function useWakeLock() {
|
||||
export default function Wall() {
|
||||
const navigate = useNavigate();
|
||||
const environment = useEnvironment();
|
||||
const now = useClock();
|
||||
const { report, failed, reload } = useAlertsReport();
|
||||
const [servers, setServers] = useState<ServerSummary | null>(null);
|
||||
const [integrations, setIntegrations] = useState<IntegrationSummary[] | null>(null);
|
||||
const [windows, setWindows] = useState<MaintenanceWindow[]>([]);
|
||||
const [updatedAt, setUpdatedAt] = useState<Date | null>(null);
|
||||
const [idle, setIdle] = useState(false);
|
||||
useWakeLock();
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
@@ -112,129 +61,41 @@ export default function Wall() {
|
||||
|
||||
const badge = alertBadge(report);
|
||||
const blind = report?.couldntCheck.length ?? 0;
|
||||
const level: "critical" | "warning" | "ok" | "unsure" = !report ? "unsure" : badge ? badge.level : blind > 0 ? "unsure" : "ok";
|
||||
const level: WallData["level"] = !report ? "unsure" : badge ? badge.level : blind > 0 ? "unsure" : "ok";
|
||||
const active = (report?.alerts ?? []).filter((a) => !a.silenced && a.severity !== "info").sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "critical" ? -1 : 1));
|
||||
const failing = (integrations ?? []).filter((i) => i.enabled && i.health?.status === "failing");
|
||||
const offline = servers?.offline.length ?? 0;
|
||||
|
||||
const headline =
|
||||
level === "critical" || level === "warning"
|
||||
? `${badge!.count} ${badge!.count === 1 ? "thing needs" : "things need"} attention`
|
||||
: level === "unsure"
|
||||
? report
|
||||
? "No alerts — but some checks couldn't run"
|
||||
: failed
|
||||
? "Can't reach the server"
|
||||
: "Checking…"
|
||||
: "All clear";
|
||||
const data: WallData = {
|
||||
level,
|
||||
headline: wallHeadline(level, badge?.count ?? 0, { loaded: !!report, failed }),
|
||||
servers: servers ? { online: servers.online, total: servers.online + servers.offline.length } : null,
|
||||
alerts: report ? { critical: report.counts.critical, warning: report.counts.warning } : null,
|
||||
maintenance: windows.length,
|
||||
integrationsFailing: integrations ? failing.length : null,
|
||||
problems: active.map((a) => ({ id: a.id, severity: a.severity as "critical" | "warning", message: a.message })),
|
||||
windows: windows.map((w) => ({ id: w.id, name: w.targetName, endsAt: w.endsAt })),
|
||||
integrations: (integrations ?? [])
|
||||
.filter((i) => i.enabled)
|
||||
.sort((a, b) => Number(b.health?.status === "failing") - Number(a.health?.status === "failing") || a.name.localeCompare(b.name))
|
||||
.map((i) => ({ id: i.id, name: i.name, type: i.type, status: i.health?.status === "failing" ? "failing" : i.health?.status === "ok" ? "ok" : "unknown" })),
|
||||
environmentName: environment?.name || null,
|
||||
updatedAt,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`wall ${idle ? "wall-idle" : ""}`} data-bs-theme="dark">
|
||||
<header className="wall-header">
|
||||
<img src="/logo.webp" alt="Homelab Manager" width={901} height={460} className="wall-logo" />
|
||||
{environment?.name && <span className="badge env-badge">{environment.name}</span>}
|
||||
<div className="wall-clock" aria-label="Time">
|
||||
<div className="wall-time">{formatTime(now, false)}</div>
|
||||
<div className="wall-date">{now.toLocaleDateString([], { weekday: "long" })} {formatDate(now)}</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className={`wall-status wall-status-${level}`} role="status" aria-live="polite">
|
||||
<span className="wall-status-symbol" aria-hidden="true">
|
||||
{level === "critical" ? "✕" : level === "warning" ? "▲" : level === "ok" ? "✓" : "?"}
|
||||
</span>
|
||||
<span>{headline}</span>
|
||||
</section>
|
||||
|
||||
<section className="wall-tiles" aria-label="Summary">
|
||||
<div className={`wall-tile ${offline > 0 ? "wall-tile-bad" : ""}`}>
|
||||
<div className="wall-tile-figure">{servers ? (servers.online + offline === 0 ? "—" : `${servers.online}/${servers.online + offline}`) : "…"}</div>
|
||||
<div className="wall-tile-label">servers online</div>
|
||||
</div>
|
||||
<div className={`wall-tile ${(report?.counts.critical ?? 0) > 0 ? "wall-tile-bad" : (report?.counts.warning ?? 0) > 0 ? "wall-tile-warn" : ""}`}>
|
||||
<div className="wall-tile-figure">{report ? report.counts.critical + report.counts.warning : "…"}</div>
|
||||
<div className="wall-tile-label">
|
||||
alerts{report && report.counts.critical + report.counts.warning > 0 ? ` (${report.counts.critical} critical, ${report.counts.warning} warning)` : ""}
|
||||
</div>
|
||||
</div>
|
||||
<div className={`wall-tile ${windows.length > 0 ? "wall-tile-info" : ""}`}>
|
||||
<div className="wall-tile-figure">{windows.length}</div>
|
||||
<div className="wall-tile-label">in maintenance</div>
|
||||
</div>
|
||||
<div className={`wall-tile ${failing.length > 0 ? "wall-tile-bad" : ""}`}>
|
||||
<div className="wall-tile-figure">{integrations ? failing.length : "…"}</div>
|
||||
<div className="wall-tile-label">integrations failing</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="wall-columns">
|
||||
<div>
|
||||
<h2 className="wall-heading">Needs attention</h2>
|
||||
{active.length === 0 ? (
|
||||
<div className="wall-empty">Nothing right now.</div>
|
||||
) : (
|
||||
<ul className="wall-list">
|
||||
{active.slice(0, 7).map((a) => (
|
||||
<li key={a.id} className={a.severity === "critical" ? "wall-bad" : "wall-warn"}>
|
||||
<span aria-hidden="true">{a.severity === "critical" ? "✕" : "▲"}</span> <span className="visually-hidden">{a.severity}: </span>
|
||||
{a.message}
|
||||
</li>
|
||||
))}
|
||||
{active.length > 7 && <li className="wall-more">and {active.length - 7} more</li>}
|
||||
</ul>
|
||||
)}
|
||||
{windows.length > 0 && (
|
||||
<>
|
||||
<h2 className="wall-heading mt-4">In maintenance</h2>
|
||||
<ul className="wall-list wall-list-small">
|
||||
{windows.slice(0, 8).map((w) => (
|
||||
<li key={w.id}>
|
||||
{w.targetName} <span className="wall-dim">· {formatRemaining(w.endsAt, now.getTime())} left</span>
|
||||
</li>
|
||||
))}
|
||||
{windows.length > 8 && <li className="wall-more">and {windows.length - 8} more</li>}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="wall-heading">Integrations</h2>
|
||||
{(integrations ?? []).filter((i) => i.enabled).length === 0 ? (
|
||||
<div className="wall-empty">None connected.</div>
|
||||
) : (
|
||||
<ul className="wall-list wall-list-small">
|
||||
{[...(integrations ?? [])]
|
||||
.filter((i) => i.enabled)
|
||||
.sort((a, b) => Number(b.health?.status === "failing") - Number(a.health?.status === "failing") || a.name.localeCompare(b.name))
|
||||
.map((i) => {
|
||||
const status = i.health?.status;
|
||||
return (
|
||||
<li key={i.id} className={status === "failing" ? "wall-bad" : status === "ok" ? "wall-good" : "wall-dim"}>
|
||||
<span aria-hidden="true">{status === "failing" ? "✕" : status === "ok" ? "✓" : "·"}</span> {i.name}{" "}
|
||||
<span className="wall-dim">
|
||||
{TYPE_LABELS[i.type]} — {status === "failing" ? "failing" : status === "ok" ? "working" : "not checked yet"}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<footer className="wall-footer">
|
||||
<span>
|
||||
{updatedAt ? `Updated ${formatTime(updatedAt)}` : "Loading…"} · refreshes every {REFRESH_MS / 1000} s
|
||||
</span>
|
||||
<span className="wall-footer-actions">
|
||||
<WallView
|
||||
data={data}
|
||||
idle={idle}
|
||||
footerActions={
|
||||
<>
|
||||
<button type="button" className="wall-link" onClick={() => void document.documentElement.requestFullscreen?.().catch(() => {})}>
|
||||
Full screen
|
||||
</button>
|
||||
<Link to="/" className="wall-link">
|
||||
Exit (Esc)
|
||||
</Link>
|
||||
</span>
|
||||
</footer>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, type ShareLink, type ShareLinkDetail } from "../../api/client";
|
||||
import CopyButton from "../../components/CopyButton";
|
||||
import TimeAgo from "../../components/TimeAgo";
|
||||
import { ErrorNotice } from "../../components/Notice";
|
||||
import { confirmDialog } from "../../utils/dialogs";
|
||||
import { formatDateTime } from "../../utils/date";
|
||||
import { readableError } from "../../utils/errors";
|
||||
import { toast } from "../../utils/toast";
|
||||
|
||||
const LASTS: { days: number | null; label: string }[] = [
|
||||
{ days: null, label: "Until I remove it" },
|
||||
{ days: 7, label: "7 days" },
|
||||
{ days: 30, label: "30 days" },
|
||||
{ days: 90, label: "90 days" },
|
||||
{ days: 365, label: "1 year" },
|
||||
];
|
||||
|
||||
const DETAIL_WORDS: Record<ShareLinkDetail, string> = {
|
||||
summary: "Numbers only",
|
||||
names: "With names",
|
||||
};
|
||||
|
||||
export default function ShareSettings() {
|
||||
const [links, setLinks] = useState<ShareLink[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [label, setLabel] = useState("");
|
||||
const [detail, setDetail] = useState<ShareLinkDetail>("summary");
|
||||
const [days, setDays] = useState<number | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [created, setCreated] = useState<{ label: string; url: string } | null>(null);
|
||||
|
||||
function load() {
|
||||
api.shareLinks
|
||||
.list()
|
||||
.then((res) => setLinks(res.links))
|
||||
.catch((err) => setError(readableError(err)));
|
||||
}
|
||||
useEffect(load, []);
|
||||
|
||||
async function create(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.shareLinks.create({ label: label.trim(), detail, expiresInDays: days });
|
||||
setCreated({ label: res.link.label, url: `${window.location.origin}${res.path}` });
|
||||
setLabel("");
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(link: ShareLink) {
|
||||
if (!(await confirmDialog({ title: "Remove share link", message: `Remove "${link.label}"? Any screen showing it stops working at once.`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.shareLinks.remove(link.id);
|
||||
toast.success(`Removed ${link.label}.`);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3 className="mb-3">Share links</h3>
|
||||
<p className="text-secondary">
|
||||
A share link opens the wall display — how things are, on one screen — <strong>without signing in</strong>, for a TV in the hall or someone who only wants to know whether things are up. It can only look; it can't change anything.
|
||||
</p>
|
||||
<div className="alert alert-warning">
|
||||
Anyone who has the address can open it, so treat it like a password: give it only to people and screens you trust, and remove it when it isn't needed. The address is shown once, when you make it.
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
|
||||
{created && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Address for {created.label}</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<p className="text-secondary">Copy it now — it can't be shown again. If it's lost, remove the link and make a new one.</p>
|
||||
<div className="input-group">
|
||||
<input className="form-control" readOnly value={created.url} aria-label="The share link address" onFocus={(e) => e.currentTarget.select()} />
|
||||
<CopyButton text={created.url} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-footer">
|
||||
<button className="btn" onClick={() => setCreated(null)}>
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Make a link</h3>
|
||||
</div>
|
||||
<form onSubmit={create}>
|
||||
<div className="card-body row g-3">
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="share-label">
|
||||
What it is for
|
||||
</label>
|
||||
<input id="share-label" className="form-control" required maxLength={60} placeholder="e.g. Hall TV" value={label} onChange={(e) => setLabel(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="share-detail">
|
||||
What it shows
|
||||
</label>
|
||||
<select id="share-detail" className="form-select" value={detail} onChange={(e) => setDetail(e.target.value as ShareLinkDetail)}>
|
||||
<option value="summary">Numbers only — servers online, alerts, maintenance</option>
|
||||
<option value="names">With names — also what is wrong, and the integrations</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="share-lasts">
|
||||
How long it works
|
||||
</label>
|
||||
<select id="share-lasts" className="form-select" value={days ?? ""} onChange={(e) => setDays(e.target.value === "" ? null : Number(e.target.value))}>
|
||||
{LASTS.map((l) => (
|
||||
<option key={l.label} value={l.days ?? ""}>
|
||||
{l.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-12 text-secondary small">
|
||||
“Numbers only” never shows a name. “With names” shows the text of the alerts (which can mention server names, disks and secrets), what is in maintenance, and the names of your integrations — never addresses, tokens or settings.
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-footer">
|
||||
<button type="submit" className="btn btn-primary" disabled={busy || label.trim() === ""}>
|
||||
{busy ? "Making…" : "Make link"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Links</h3>
|
||||
</div>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Shows</th>
|
||||
<th>Made</th>
|
||||
<th>Works until</th>
|
||||
<th>Last opened</th>
|
||||
<th className="w-1">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{links?.map((l) => (
|
||||
<tr key={l.id}>
|
||||
<td>
|
||||
{l.label} <span className="text-secondary small">{l.tokenPrefix}…</span>
|
||||
</td>
|
||||
<td>{DETAIL_WORDS[l.detail]}</td>
|
||||
<td className="text-secondary">
|
||||
{l.createdBy ?? "—"}, <TimeAgo value={l.createdAt} fromDb />
|
||||
</td>
|
||||
<td>{l.expired ? <span className="badge bg-red-lt text-red">Ended</span> : l.expiresAt ? formatDateTime(new Date(l.expiresAt)) : "Until removed"}</td>
|
||||
<td className="text-secondary">{l.lastUsedAt ? <TimeAgo value={l.lastUsedAt} /> : "Never"}</td>
|
||||
<td>
|
||||
<button className="btn btn-sm btn-outline-danger" onClick={() => remove(l)}>
|
||||
Remove
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{links?.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={6} className="text-secondary text-center">
|
||||
No share links yet.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{links === null && !error && (
|
||||
<tr>
|
||||
<td colSpan={6} className="text-secondary text-center">
|
||||
Loading…
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -395,6 +395,15 @@ main:focus {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.row-clickable:focus-visible {
|
||||
outline: 2px solid var(--tblr-primary);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.row-clickable:focus-visible > td {
|
||||
background-color: color-mix(in srgb, var(--tblr-primary) 10%, transparent);
|
||||
}
|
||||
|
||||
.row-clickable:hover > td {
|
||||
background-color: color-mix(in srgb, currentColor 5%, transparent);
|
||||
}
|
||||
@@ -473,6 +482,23 @@ main:focus {
|
||||
}
|
||||
}
|
||||
|
||||
/* Picking servers to compare: the cards become tick-boxes. */
|
||||
.compare-card {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.compare-card-on {
|
||||
outline: 2px solid var(--tblr-primary);
|
||||
outline-offset: -2px;
|
||||
background-color: color-mix(in srgb, var(--tblr-primary) 10%, transparent);
|
||||
}
|
||||
|
||||
/* The filters of a pinned view, after the page's name in the menu. */
|
||||
.nav-view {
|
||||
opacity: 0.75;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
/* ── A server's activity: an icon, what happened, and when. ── */
|
||||
.activity-list {
|
||||
margin: 0;
|
||||
@@ -1398,3 +1424,24 @@ html[data-density="roomy"] .table > :not(caption) > * > * {
|
||||
gap: 0.25rem;
|
||||
padding: 0.4rem 0.5rem;
|
||||
}
|
||||
|
||||
/* ── Arranging the dashboard: each card gets a row of buttons, and a hidden one is dimmed. ── */
|
||||
.card-customise {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
padding: 0.35rem 0.5rem;
|
||||
border-bottom: 1px dashed var(--tblr-border-color);
|
||||
}
|
||||
|
||||
.card-hidden > :not(.card-customise) {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* ── Comparing servers: the chart fills its card and takes the text colour for its axes. ── */
|
||||
.multi-chart {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
color: var(--tblr-body-color);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { api, type DashboardLayout } from "../api/client";
|
||||
import { readableError } from "./errors";
|
||||
import { toast } from "./toast";
|
||||
|
||||
// How this person arranged the dashboard cards. It is kept on their user record on the server, so it follows them to any browser;
|
||||
// here it is kept in step so every card, and the Customise bar, see the same layout at once.
|
||||
|
||||
const EMPTY: DashboardLayout = { hidden: [], order: {} };
|
||||
|
||||
/** Where a card goes when nothing has been said about it: after every card that has been placed, in the order it was drawn. */
|
||||
export const UNPLACED = 1000;
|
||||
|
||||
interface State {
|
||||
layout: DashboardLayout;
|
||||
/** The person is arranging the cards: hidden ones show (dimmed) and each card has its buttons. */
|
||||
editing: boolean;
|
||||
}
|
||||
|
||||
let state: State = { layout: EMPTY, editing: false };
|
||||
const listeners = new Set<() => void>();
|
||||
/** Only the answer to the latest change may overwrite the layout, however the replies are ordered. */
|
||||
let latest = 0;
|
||||
|
||||
function set(next: State) {
|
||||
state = next;
|
||||
for (const l of listeners) l();
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/** Loads the layout the server sent with the signed-in user. */
|
||||
export function initDashboardLayout(layout: DashboardLayout | undefined): void {
|
||||
set({ ...state, layout: layout ? { hidden: [...layout.hidden], order: { ...layout.order } } : EMPTY });
|
||||
}
|
||||
|
||||
export function useDashboardLayout(): State {
|
||||
return useSyncExternalStore(subscribe, () => state);
|
||||
}
|
||||
|
||||
export function setEditingDashboard(editing: boolean): void {
|
||||
set({ ...state, editing });
|
||||
}
|
||||
|
||||
/** Shown at once; put back, with a message, if the server can't save it. */
|
||||
async function save(next: DashboardLayout): Promise<void> {
|
||||
const before = state.layout;
|
||||
set({ ...state, layout: next });
|
||||
const mine = ++latest;
|
||||
try {
|
||||
const res = await api.me.setDashboard(next);
|
||||
if (mine === latest) set({ ...state, layout: res.dashboard });
|
||||
} catch (err) {
|
||||
if (mine === latest) {
|
||||
set({ ...state, layout: before });
|
||||
toast.error(`Couldn't save the dashboard layout: ${readableError(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function setCardHidden(label: string, hidden: boolean): Promise<void> {
|
||||
const { layout } = state;
|
||||
const rest = layout.hidden.filter((l) => l !== label);
|
||||
return save({ ...layout, hidden: hidden ? [...rest, label] : rest });
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a card one place earlier or later among the cards beside it (the ones in the same row). Every card of that row is given its
|
||||
* place at the same time — a card is only ever swapped with its neighbour — so a row is either left as drawn or fully placed.
|
||||
*/
|
||||
export function moveCard(card: HTMLElement, direction: -1 | 1): Promise<void> {
|
||||
const row = card.closest(".row");
|
||||
if (!row) return Promise.resolve();
|
||||
const cards = [...row.children].filter((el): el is HTMLElement => el instanceof HTMLElement && el.dataset.card !== undefined);
|
||||
const placed = cards
|
||||
.map((el, index) => ({ label: el.dataset.card!, index }))
|
||||
.sort((a, b) => (state.layout.order[a.label] ?? UNPLACED) - (state.layout.order[b.label] ?? UNPLACED) || a.index - b.index)
|
||||
.map((c) => c.label);
|
||||
const at = placed.indexOf(card.dataset.card!);
|
||||
const to = at + direction;
|
||||
if (at === -1 || to < 0 || to >= placed.length) return Promise.resolve();
|
||||
[placed[at], placed[to]] = [placed[to], placed[at]];
|
||||
const order = { ...state.layout.order };
|
||||
placed.forEach((label, i) => (order[label] = i));
|
||||
return save({ ...state.layout, order });
|
||||
}
|
||||
|
||||
export function resetDashboardLayout(): Promise<void> {
|
||||
return save(EMPTY);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// A "saved view" is a page with its filters, pinned like a favourite: "/servers?status=offline". The address is the whole of it — the
|
||||
// search words, the status or tag chosen, the sort — so a view can also be bookmarked or sent to someone, and it needs no storage of its own.
|
||||
|
||||
/** The address parts that narrow or order a table. Anything else in an address (an id to edit, say) is not part of a view. */
|
||||
const VIEW_PARAMS = ["q", "status", "tag", "sort", "dir"] as const;
|
||||
|
||||
/** Only these make a page worth saving as a view: sorting alone does, a lone `dir` doesn't. */
|
||||
const NARROWING = new Set(["q", "status", "tag", "sort"]);
|
||||
|
||||
/** "/servers?q=elsa" → ["/servers", "?q=elsa"]; a plain page has an empty second part. */
|
||||
export function splitView(path: string): [string, string] {
|
||||
const at = path.indexOf("?");
|
||||
return at === -1 ? [path, ""] : [path.slice(0, at), path.slice(at)];
|
||||
}
|
||||
|
||||
export function isSavedView(path: string): boolean {
|
||||
return path.includes("?");
|
||||
}
|
||||
|
||||
/** The part of an address that makes up a view, in a fixed order, so the same view always comes out as the same text. */
|
||||
export function canonicalSearch(search: string): string {
|
||||
const from = new URLSearchParams(search);
|
||||
const to = new URLSearchParams();
|
||||
for (const key of VIEW_PARAMS) for (const value of from.getAll(key)) if (value !== "") to.append(key, value);
|
||||
const text = to.toString();
|
||||
return text ? `?${text}` : "";
|
||||
}
|
||||
|
||||
/** Whether an address has anything that narrows or orders the table, i.e. is worth saving. */
|
||||
export function hasViewParams(search: string): boolean {
|
||||
const from = new URLSearchParams(search);
|
||||
return [...from.keys()].some((k) => NARROWING.has(k) && from.get(k) !== "");
|
||||
}
|
||||
|
||||
const STATUS_WORDS: Record<string, string> = { offline: "not reporting", online: "reporting", failing: "failing", working: "working", disabled: "disabled" };
|
||||
|
||||
/** A short phrase for the menu: `“elsa” · not reporting · tag backup · by name ↓`. */
|
||||
export function describeView(search: string): string {
|
||||
const p = new URLSearchParams(search);
|
||||
const parts: string[] = [];
|
||||
const q = p.get("q");
|
||||
if (q) parts.push(`“${q}”`);
|
||||
const status = p.get("status");
|
||||
if (status) parts.push(STATUS_WORDS[status] ?? status);
|
||||
for (const t of p.getAll("tag")) parts.push(`tag ${t}`);
|
||||
const sort = p.get("sort");
|
||||
if (sort) parts.push(`by ${sort.replace(/([A-Z])/g, " $1").toLowerCase()} ${p.get("dir") === "desc" ? "↓" : "↑"}`);
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
/** The longest view that can be pinned: the same limit the server keeps. */
|
||||
export const MAX_VIEW_QUERY = 160;
|
||||
Reference in new issue
Block a user