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:
bobbanandClaude Sonnet 5.5 committed 2026-10-16 22:15:29 +02:00
1 parent 906220040e
commit 44e393f172
50 files changed
+6114 -258

No files matched your search

+24 -6
View File
@@ -23,8 +23,8 @@ what the app actually creates.
|---|---|
| **File** | `DATABASE_PATH`, default `../data/homelab-manager.sqlite` (relative to `server/`; `/app/data/...` in Docker). The folder is created if missing. |
| **Foreign keys** | Switched on for every connection (`PRAGMA foreign_keys = ON`), so the `ON DELETE` rules below are enforced. |
| **Migrations** | SQL files in [`server/drizzle/`](server/drizzle) (`0000` … `0014`), applied automatically when the server starts. Which ones have run is recorded in the table `__drizzle_migrations`. |
| **Tables** | 24 application tables, plus drizzle's own `__drizzle_migrations`. |
| **Migrations** | SQL files in [`server/drizzle/`](server/drizzle) (`0000` … `0023`), applied automatically when the server starts. Which ones have run is recorded in the table `__drizzle_migrations`. |
| **Tables** | 25 application tables, plus drizzle's own `__drizzle_migrations`. |
**Not in the database:**
@@ -62,9 +62,9 @@ erDiagram
integrations ||--o{ alert_tickets : "osTicket used (set null)"
```
Eight tables stand alone, with no foreign keys: `settings`, `secrets`,
Nine tables stand alone, with no foreign keys: `settings`, `secrets`,
`ipam_entries`, `domains`, `diag_log`, `notification_queue`,
`consistency_ignores`, `tag_definitions`. `maintenance_windows` and `maintenance_aliases` also have no
`consistency_ignores`, `tag_definitions`, `share_links`. `maintenance_windows` and `maintenance_aliases` also have no
foreign key — see [soft references](#soft-references-not-foreign-keys).
## Tables
@@ -86,7 +86,8 @@ Everyone who has signed in through Authentik. The first one becomes admin.
| `role` | text NOT NULL, default `viewer` | `admin` \| `operator` \| `viewer`. |
| `created_at` | text NOT NULL | SQLite UTC. |
| `last_login_at` | text | ISO. |
| `favorites` | text | JSON array of the page paths this person pinned to the top of their menu (`["/servers","/alerts"]`), up to 24. Follows them to any browser. |
| `favorites` | text | JSON array of the page paths this person pinned to the top of their menu (`["/servers","/alerts"]`), up to 24. A path may carry a short query for a saved view of a page (`"/servers?status=offline"`). Follows them to any browser. |
| `dashboard_layout` | text | JSON object `{"hidden":["Gitea"],"order":{"Secrets":0,"DNS":1}}`: the dashboard cards this person hid and the order of the rest (lower first; a card with no entry goes last). Null = the default layout. Follows them to any browser. |
| `last_looked_at` | text | ISO time this person last pressed "Got it" on the dashboard's "Since you last looked" card; the next summary starts there (null = never: the last day is shown). |
#### `audit_log`
@@ -99,7 +100,7 @@ Who changed what. Written by the app on every change (see
| `id` | integer PK | |
| `actor_user_id` | integer → `users.id`, **set null** on delete | Null for automatic actions, and for entries whose user was deleted. |
| `actor_label` | text | The user's name/email as it was at the time (or `system`), so an entry still reads correctly after the account is gone. |
| `category` | text NOT NULL | Free text. In use: `server` (including the health check's own `went_offline`, `back_online`, `disk_full` and `disk_ok`, written as `system` and shown on a server's Activity card), `integration` (including the health check's `went_failing` / `recovered` for a kind of service, with `target_type` `integration_type` and the service type as `target_id`, which the dashboard summary and the uptime ribbons read), `dns`, `settings`, `ipam`, `secret`, `domain`, `tag`, `task`, `session`, `network`, `maintenance`, `consistency`, `user`, `privacy`, `diag_log`, `alert_ticket`. |
| `category` | text NOT NULL | Free text. In use: `server` (including the health check's own `went_offline`, `back_online`, `disk_full` and `disk_ok`, written as `system` and shown on a server's Activity card), `integration` (including the health check's `went_failing` / `recovered` for a kind of service, with `target_type` `integration_type` and the service type as `target_id`, which the dashboard summary and the uptime ribbons read), `dns`, `settings`, `ipam`, `secret`, `domain`, `tag`, `task`, `session`, `network`, `maintenance`, `consistency`, `user`, `privacy`, `diag_log`, `alert_ticket`, `share_link` (a link made or removed — never the secret). |
| `action` | text NOT NULL | `create`, `update`, `delete`, `start`, `stop`, … — free text. |
| `target_type`, `target_id` | text | What it happened to. `target_id` is text so it can hold any kind of ID; there's no foreign key. |
| `detail` | text | JSON, free-form context (what changed, names, counts). Secrets are never put here. |
@@ -461,6 +462,23 @@ checks see it. A row is one *occurrence*: when an alert clears and later returns
| `ticketed_at` | text | ISO; when the ticket was opened. |
| `cleared_at` | text | ISO; null while the alert is still active. Rows cleared more than 180 days ago are deleted. |
#### `share_links`
Addresses that open a read-only wall display without signing in (Settings → Share
links). Only a hash of the secret is stored.
| Column | Type | Notes |
|---|---|---|
| `id` | integer PK | |
| `label` | text NOT NULL | What it is for, e.g. "Hall TV". |
| `token_hash` | text NOT NULL, unique | SHA-256 of the secret in the address; the secret itself is shown once and never stored. |
| `token_prefix` | text NOT NULL | The first characters of the secret, to tell links apart in the list. |
| `detail` | text NOT NULL, default `summary` | `summary` (numbers only) or `names` (also the names of what is wrong, in maintenance, and the integrations). |
| `created_by` | text | The administrator's name at the time. |
| `created_at` | text NOT NULL | |
| `expires_at` | text | ISO; null = until removed. |
| `last_used_at` | text | ISO; updated at most once a minute. |
## What's stored inside the JSON columns
| Column | Shape |
+34 -3
View File
@@ -363,7 +363,11 @@ maintenance this moment and starts a window for a duration you choose.
click its star to pin it: pinned pages are listed under "Favourites" at the top
of the menu, are offered first in the search box, and follow you to any
browser, because they are saved with your user (the search box can also pin or
unpin the page you are on). A button at the foot of the sidebar — or the `[` key
unpin the page you are on). A table's search words, status, tag and sort live
in the address (`/servers?status=offline`), so they survive a reload and can be
bookmarked; once something narrows the table a **Save view** button pins that
view too, listed under Favourites by its filters ("Servers not reporting"). A
button at the foot of the sidebar — or the `[` key
— narrows it to a strip of icons for more room on a laptop screen: a group's
pages then open in a small menu beside its icon, the alert and maintenance
counts stay visible, and your choice is remembered in that browser. On a phone
@@ -375,8 +379,9 @@ a server, integration or DNS provider ("silence elsa"), open the wall display,
sign out. "g" then a letter goes to a page (`g d` dashboard, `g a` alerts,
`g s` servers, `g m` maintenance, `g i` integrations, `g k` secrets, `g p` map,
`g w` wall display), "/" jumps to the page's table search, and "?" lists them
all. Shortcuts for pages your role can't open are ignored, and none fire while
you are typing. On a table of Proxmox guests, Docker containers, Tailscale
all, and "j" / "k" move down and up the rows of a table that opens a panel (Enter
opens the row you are on). Shortcuts for pages your role can't open are ignored,
and none fire while you are typing. On a table of Proxmox guests, Docker containers, Tailscale
devices, Uptime Kuma monitors, Gitea repositories or Semaphore templates, a
click (or Enter) on a row opens a panel with everything known about it, without
leaving the table.
@@ -395,6 +400,32 @@ the problems themselves, and each integration's status, refreshing every 30
seconds with the screen kept awake where the browser allows. Esc returns to the
app.
**Customising the dashboard.** Customise (top of the dashboard) lets you move each
card earlier or later among its neighbours and hide the ones you don't use —
hidden cards stay listed, dimmed, while you arrange so they can be brought back,
and Reset returns the default. It is saved with your user, so it follows you to
any browser, and it is yours alone.
**Comparing servers.** On the Servers page, Compare lets you pick two to four
servers and open their load, memory or a disk on one chart (24 hours, 7 or 30
days), each line with its own colour and dash pattern and a table of now, average
and peak beside it. Servers that don't report through an agent have no history
to draw. The Servers page also has a search box and a "not reporting /
reporting" filter, and the dashboard links to the not-reporting ones.
**Share links** (Settings → Share links, administrators only) make an address
that opens a read-only wall display **without signing in**, for a TV or someone
who only wants to know if things are up. Each link has a name, how long it works
(until removed, 7 days … a year) and how much it shows: *numbers only* (servers
online, alert counts, what is in maintenance, integrations failing — never a
name) or *with names* (also the text of the alerts, what is in maintenance and
the integrations' names — never addresses, tokens or settings). The picture is
built on the server, so nothing else leaves it. The secret in the address is
shown once; only a hash is stored, a link that never existed, ended or was
removed answers the same way, and making and removing links are in the audit log
(without the secret). It is as private as the address: remove it when it isn't
needed.
**Since you last looked.** The dashboard opens with a card on what happened
since you last pressed "Got it" (the first time, the last day; never more than
two weeks): servers that stopped reporting or filled a disk, services that
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `users` ADD `dashboard_layout` text;
+13
View File
@@ -0,0 +1,13 @@
CREATE TABLE `share_links` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`label` text NOT NULL,
`token_hash` text NOT NULL,
`token_prefix` text NOT NULL,
`detail` text DEFAULT 'summary' NOT NULL,
`created_by` text,
`created_at` text DEFAULT (current_timestamp) NOT NULL,
`expires_at` text,
`last_used_at` text
);
--> statement-breakpoint
CREATE UNIQUE INDEX `share_links_token_hash_unique` ON `share_links` (`token_hash`);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+14
View File
@@ -155,6 +155,20 @@
"when": 1792177953255,
"tag": "0021_conscious_snowbird",
"breakpoints": true
},
{
"idx": 22,
"version": "6",
"when": 1792180939809,
"tag": "0022_elite_kabuki",
"breakpoints": true
},
{
"idx": 23,
"version": "6",
"when": 1792181083723,
"tag": "0023_premium_cyclops",
"breakpoints": true
}
]
}
+4
View File
@@ -9,6 +9,8 @@ import { resolveDataPath } from "./paths.js";
import { authRouter } from "./auth/router.js";
import { meRouter } from "./routes/me.js";
import { uptimeRouter } from "./routes/uptime.js";
import { shareLinksRouter } from "./routes/shareLinks.js";
import { publicWallRouter } from "./routes/publicWall.js";
import { usersRouter } from "./routes/users.js";
import { auditLogRouter } from "./routes/auditLog.js";
import { diagLogRouter } from "./routes/diagLog.js";
@@ -89,6 +91,8 @@ export function createApp() {
app.use("/auth", authRouter);
app.use("/api/me", meRouter);
app.use("/api/uptime", uptimeRouter);
app.use("/api/share-links", shareLinksRouter);
app.use("/api/public/wall", publicWallRouter);
app.use("/api/users", usersRouter);
app.use("/api/audit-log", auditLogRouter);
app.use("/api/diag-log", diagLogRouter);
+25
View File
@@ -20,6 +20,9 @@ export const users = sqliteTable("users", {
favorites: text("favorites"),
// When this person last pressed "Got it" on the dashboard summary of what changed; the next summary starts from here (ISO).
lastLookedAt: text("last_looked_at"),
// How this person arranged the dashboard: a JSON object with the cards they hid ("hidden": ["Gitea"]) and the order of the others
// ("order": {"DNS": 0, "Secrets": 1}). Follows them to any browser; null is the default layout.
dashboardLayout: text("dashboard_layout"),
});
// ─── Audit log ──────────────────────────────────────────────────────────────
@@ -480,3 +483,25 @@ export const alertTickets = sqliteTable(
},
(t) => [index("alert_tickets_key_idx").on(t.alertKey)],
);
// ─── Share links: a read-only status board anyone with the address can open ─
export const shareLinkDetails = ["summary", "names"] as const;
export type ShareLinkDetail = (typeof shareLinkDetails)[number];
// A link to the wall display that needs no sign-in, for a TV in the hall or someone who only wants to know if things are up. Only a hash
// of the secret part of the address is kept (like an agent token), so it can't be read back out of the database or a backup.
export const shareLinks = sqliteTable("share_links", {
id: integer("id").primaryKey({ autoIncrement: true }),
label: text("label").notNull(), // what it is for, e.g. "Hall TV"
tokenHash: text("token_hash").notNull().unique(),
tokenPrefix: text("token_prefix").notNull(), // the first characters, to tell links apart in the list
// summary = how things are, in numbers; names = also the names of what is wrong, in maintenance, and the integrations
detail: text("detail").$type<ShareLinkDetail>().notNull().default("summary"),
createdBy: text("created_by"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
expiresAt: text("expires_at"), // ISO; null = never
lastUsedAt: text("last_used_at"), // ISO
});
+47 -5
View File
@@ -23,15 +23,45 @@ export function parseFavorites(stored: string | null): string[] {
}
}
/** What is stored for the dashboard, read back as a layout. Anything that isn't one is the default layout rather than an error. */
export function parseDashboardLayout(stored: string | null): DashboardLayout {
const empty: DashboardLayout = { hidden: [], order: {} };
if (!stored) return empty;
try {
const value = JSON.parse(stored);
const parsed = dashboardSchema.safeParse(value);
return parsed.success ? parsed.data : empty;
} catch {
return empty;
}
}
meRouter.get("/", requireAuth, (req, res) => {
const { id, email, name, role, oidcSub, favorites } = req.currentUser!;
res.json({ user: { id, sub: oidcSub, email, name, role, favorites: parseFavorites(favorites) } });
const { id, email, name, role, oidcSub, favorites, dashboardLayout } = req.currentUser!;
res.json({ user: { id, sub: oidcSub, email, name, role, favorites: parseFavorites(favorites), dashboard: parseDashboardLayout(dashboardLayout) } });
});
// Paths inside the app only: a slash, then letters, digits, dashes, underscores and further slashes. Which of them are real pages is
// the menu's business; a favourite for a page that is gone, or that this person's role can't open, is simply not shown.
// Paths inside the app only: a slash, then letters, digits, dashes, underscores and further slashes — and, for a saved view of a page,
// a short query of the characters a browser leaves as they are or percent-encodes (the search words, a status, a sort). Which of them
// are real pages is the menu's business; a favourite for a page that is gone, or that this person's role can't open, is simply not shown.
const favoritesSchema = z.object({
paths: z.array(z.string().regex(/^\/[A-Za-z0-9\-_/]{0,80}$/, "Not a page path")).max(MAX_FAVORITES),
paths: z.array(z.string().regex(/^\/[A-Za-z0-9\-_/]{0,80}(\?[A-Za-z0-9*\-._+%=&]{1,160})?$/, "Not a page path")).max(MAX_FAVORITES),
});
/** The most cards a layout can name: more than any dashboard has. */
const MAX_LAYOUT_CARDS = 60;
export interface DashboardLayout {
/** Card labels the person hid. */
hidden: string[];
/** Position of a card among its neighbours; lower comes first. */
order: Record<string, number>;
}
const cardName = z.string().min(1).max(60);
const dashboardSchema = z.object({
hidden: z.array(cardName).max(MAX_LAYOUT_CARDS),
order: z.record(cardName, z.number().int().min(0).max(1000)).refine((o) => Object.keys(o).length <= MAX_LAYOUT_CARDS, "Too many cards"),
});
// Replaces the signed-in person's pinned pages. Only ever their own.
@@ -69,3 +99,15 @@ meRouter.post("/changes/seen", requireAuth, asyncHandler(async (req, res) => {
await db.update(users).set({ lastLookedAt: at }).where(eq(users.id, req.currentUser!.id));
res.json({ lastLookedAt: at });
}));
// Replaces how the signed-in person arranged the dashboard. Only ever their own.
meRouter.put("/dashboard", requireAuth, asyncHandler(async (req, res) => {
const parsed = dashboardSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: "invalid_body", message: "Name the cards to hide and the order of the rest.", details: parsed.error.flatten() });
}
const layout: DashboardLayout = { hidden: [...new Set(parsed.data.hidden)], order: parsed.data.order };
const empty = layout.hidden.length === 0 && Object.keys(layout.order).length === 0;
await db.update(users).set({ dashboardLayout: empty ? null : JSON.stringify(layout) }).where(eq(users.id, req.currentUser!.id));
res.json({ dashboard: layout });
}));
+19
View File
@@ -0,0 +1,19 @@
import { Router } from "express";
import { NOT_FOUND, resolveShareLink } from "../services/shareLinks.js";
import { buildPublicWall } from "../services/publicWall.js";
import { rateLimit } from "../utils/rateLimit.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const publicWallRouter = Router();
// No sign-in here: the secret in the address is the whole of the access, so this reads nothing but the wall's picture, and answers a
// link that doesn't work — never made, ended, or taken back — in the same words.
const limiter = rateLimit({ windowMs: 60_000, max: 60, message: "Too many requests. Wait a minute." });
publicWallRouter.get("/:token", limiter, asyncHandler(async (req, res) => {
const link = await resolveShareLink(req.params.token);
if (!link) return res.status(404).json(NOT_FOUND);
res.setHeader("Cache-Control", "no-store");
res.setHeader("X-Robots-Tag", "noindex, nofollow");
res.json(await buildPublicWall(link.detail));
}));
+61
View File
@@ -0,0 +1,61 @@
import { Router } from "express";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { shareLinkDetails, shareLinks } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { createShareLink, publicShareLink } from "../services/shareLinks.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const shareLinksRouter = Router();
// Making a link that anyone can open without signing in is an administrator's decision.
shareLinksRouter.use(requireAuth, requireRole("admin"));
/** More links than anyone needs; each is something to keep track of and take back. */
const MAX_LINKS = 20;
const createSchema = z.object({
label: z.string().trim().min(1).max(60),
detail: z.enum(shareLinkDetails),
expiresInDays: z.number().int().min(1).max(365).nullable(),
});
shareLinksRouter.get("/", asyncHandler(async (_req, res) => {
const rows = await db.select().from(shareLinks).orderBy(shareLinks.createdAt);
res.json({ links: rows.map((r) => publicShareLink(r)) });
}));
// The secret part of the address is in this response and nowhere else, ever: only a hash of it is kept.
shareLinksRouter.post("/", asyncHandler(async (req, res) => {
const parsed = createSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: "invalid_body", message: "Give the link a name, say how much it shows, and how long it lasts.", details: parsed.error.flatten() });
}
const existing = await db.select({ id: shareLinks.id }).from(shareLinks);
if (existing.length >= MAX_LINKS) {
return res.status(400).json({ error: "too_many", message: `There are already ${MAX_LINKS} share links. Remove one you no longer use first.` });
}
const actor = req.currentUser!;
const { link, token } = await createShareLink({ ...parsed.data, createdBy: actor.name ?? actor.email ?? actor.oidcSub });
await recordAudit({
actor,
category: "share_link",
action: "create",
targetType: "share_link",
targetId: link.id,
detail: { label: link.label, detail: link.detail, expiresAt: link.expiresAt },
});
res.status(201).json({ link: publicShareLink(link), token, path: `/share/wall/${token}` });
}));
shareLinksRouter.delete("/:id", asyncHandler(async (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [link] = await db.select().from(shareLinks).where(eq(shareLinks.id, id)).limit(1);
if (!link) return res.status(404).json({ error: "not_found" });
await db.delete(shareLinks).where(eq(shareLinks.id, id));
await recordAudit({ actor: req.currentUser!, category: "share_link", action: "delete", targetType: "share_link", targetId: id, detail: { label: link.label } });
res.status(204).end();
}));
+86
View File
@@ -0,0 +1,86 @@
/**
* What a share link may show: the wall display's picture of how things are, built here on the server so that nothing beyond it ever
* reaches someone who isn't signed in. "summary" is only numbers and an overall state; "names" adds the names of what is wrong, of what
* is in maintenance, and of the integrations — but never addresses, tokens or other settings.
*/
import { db } from "../db/client.js";
import { integrations, servers } from "../db/schema.js";
import { env } from "../env.js";
import { getAlerts } from "./alerts.js";
import { getSourceStatus } from "./integrationHealthMonitor.js";
import { describeTarget, listActiveWindows, activeSubjects } from "./maintenance.js";
import { buildServerSummary } from "./serverSummary.js";
import { getSettings } from "./settingsStore.js";
import type { ShareLinkDetail } from "../db/schema.js";
export interface PublicWall {
detail: ShareLinkDetail;
/** Overall state, decided here exactly as the signed-in wall decides it. */
level: "ok" | "warning" | "critical" | "unsure";
environment: string | null;
servers: { online: number; offline: number };
alerts: { critical: number; warning: number };
/** Windows running now. */
maintenance: number;
integrationsFailing: number;
/** Only with detail "names". */
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;
/** How dates and times are written here — so the board reads the way the rest of the app does. */
display: { dateFormat: string; timeFormat: string };
}
const MAX_PROBLEMS = 7;
const MAX_WINDOWS = 8;
export async function buildPublicWall(detail: ShareLinkDetail, now: Date = new Date()): Promise<PublicWall> {
const [report, settings, windows, serverRows, integrationRows, subjects] = await Promise.all([
getAlerts(false),
getSettings(),
listActiveWindows(now),
db.select({ id: servers.id, name: servers.name, osType: servers.osType, lastSeenAt: servers.lastSeenAt, disks: servers.disks }).from(servers),
db.select({ id: integrations.id, name: integrations.name, type: integrations.type, enabled: integrations.enabled }).from(integrations),
activeSubjects(now),
]);
const summary = buildServerSummary(serverRows, settings.healthChecks, now.getTime(), subjects);
const enabled = integrationRows.filter((i) => i.enabled);
const statusOf = (type: string) => getSourceStatus(type).status;
const failing = enabled.filter((i) => statusOf(i.type) === "failing");
const critical = report.counts.critical;
const warning = report.counts.warning;
const level: PublicWall["level"] = critical > 0 ? "critical" : warning > 0 ? "warning" : report.couldntCheck.length > 0 ? "unsure" : "ok";
const out: PublicWall = {
detail,
level,
environment: env.environment?.name || null,
servers: { online: summary.online, offline: summary.offline.length },
alerts: { critical, warning },
maintenance: windows.length,
integrationsFailing: failing.length,
generatedAt: now.toISOString(),
display: { dateFormat: settings.display.dateFormat, timeFormat: settings.display.timeFormat },
};
if (detail === "names") {
out.problems = report.alerts
.filter((a): a is typeof a & { severity: "critical" | "warning" } => !a.silenced && a.severity !== "info")
.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "critical" ? -1 : 1))
.slice(0, MAX_PROBLEMS)
.map((a) => ({ id: a.id, severity: a.severity, message: a.message }));
const named: { id: number; name: string; endsAt: string }[] = [];
for (const w of [...windows].sort((a, b) => a.endsAt.localeCompare(b.endsAt))) {
const target = await describeTarget(w.targetType, w.targetId);
if (target) named.push({ id: w.id, name: target.name, endsAt: w.endsAt });
}
out.maintenanceWindows = named.slice(0, MAX_WINDOWS);
out.integrations = [...enabled]
.sort((a, b) => Number(statusOf(b.type) === "failing") - Number(statusOf(a.type) === "failing") || a.name.localeCompare(b.name))
.map((i) => ({ id: i.id, name: i.name, type: i.type, status: statusOf(i.type) }));
}
return out;
}
+62
View File
@@ -0,0 +1,62 @@
/**
* Share links: an address that opens a read-only wall display without signing in. The address carries a long random secret; only its
* SHA-256 is stored, so the secret can't be read back out of the database or a backup, and it is shown once, when the link is made.
*/
import { createHash, randomBytes } from "node:crypto";
import { eq } from "drizzle-orm";
import { db } from "../db/client.js";
import { shareLinks, type ShareLinkDetail } from "../db/schema.js";
export type ShareLinkRow = typeof shareLinks.$inferSelect;
/** What the public may be told about a link that doesn't work: nothing that tells "never existed" from "ended" or "removed". */
export const NOT_FOUND = { error: "not_found", message: "This link doesn't work." } as const;
const hash = (token: string) => createHash("sha256").update(token).digest("hex");
/** A link isn't recorded as used more than once in this time, so a screen refreshing every few seconds doesn't write the database each time. */
const USED_WRITE_GAP_MS = 60_000;
export async function createShareLink(params: { label: string; detail: ShareLinkDetail; expiresInDays: number | null; createdBy: string; now?: Date }): Promise<{ link: ShareLinkRow; token: string }> {
const now = params.now ?? new Date();
const token = randomBytes(24).toString("base64url");
const [link] = await db
.insert(shareLinks)
.values({
label: params.label,
tokenHash: hash(token),
tokenPrefix: token.slice(0, 6),
detail: params.detail,
createdBy: params.createdBy,
expiresAt: params.expiresInDays === null ? null : new Date(now.getTime() + params.expiresInDays * 86_400_000).toISOString(),
})
.returning();
return { link, token };
}
/** The link a secret belongs to, if it exists and has not ended. Notes that it was used. */
export async function resolveShareLink(token: string, now: Date = new Date()): Promise<ShareLinkRow | null> {
if (typeof token !== "string" || token.length < 16 || token.length > 128) return null;
const [link] = await db.select().from(shareLinks).where(eq(shareLinks.tokenHash, hash(token))).limit(1);
if (!link) return null;
if (link.expiresAt && Date.parse(link.expiresAt) <= now.getTime()) return null;
if (!link.lastUsedAt || now.getTime() - Date.parse(link.lastUsedAt) >= USED_WRITE_GAP_MS) {
await db.update(shareLinks).set({ lastUsedAt: now.toISOString() }).where(eq(shareLinks.id, link.id));
}
return link;
}
/** A link as the admin list shows it: everything but the hash. */
export function publicShareLink(link: ShareLinkRow, now: Date = new Date()) {
return {
id: link.id,
label: link.label,
tokenPrefix: link.tokenPrefix,
detail: link.detail,
createdBy: link.createdBy,
createdAt: link.createdAt,
expiresAt: link.expiresAt,
lastUsedAt: link.lastUsedAt,
expired: !!link.expiresAt && Date.parse(link.expiresAt) <= now.getTime(),
};
}
+266
View File
@@ -0,0 +1,266 @@
/**
* Saved views as favourites, the dashboard layout, and the share links that open a read-only wall without signing in.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-share-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, servers, integrations, auditLog, shareLinks, maintenanceWindows, secrets } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { meRouter, parseDashboardLayout } = await import("../src/routes/me.js");
const { shareLinksRouter } = await import("../src/routes/shareLinks.js");
const { publicWallRouter } = await import("../src/routes/publicWall.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
describe("parseDashboardLayout", () => {
test("anything that isn't a layout is the default layout", () => {
const empty = { hidden: [], order: {} };
assert.deepEqual(parseDashboardLayout(null), empty);
assert.deepEqual(parseDashboardLayout("not json"), empty);
assert.deepEqual(parseDashboardLayout(JSON.stringify({ hidden: "Gitea" })), empty);
assert.deepEqual(parseDashboardLayout(JSON.stringify({ hidden: ["Gitea"], order: { DNS: 1 } })), { hidden: ["Gitea"], order: { DNS: 1 } });
});
});
describe("favourites, dashboard layout and share links", () => {
let app: Server;
let base = "";
let who = "admin";
before(async () => {
await db.insert(users).values([
{ oidcSub: "admin", name: "Ada", role: "admin" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
]);
const hours = (n: number) => new Date(Date.now() - n * 3600_000).toISOString();
await db.insert(servers).values([
{ name: "elsa", apiTokenHash: "a", apiTokenPrefix: "a", lastSeenAt: hours(5) }, // stopped reporting
{ name: "anna", apiTokenHash: "b", apiTokenPrefix: "b", lastSeenAt: new Date().toISOString() },
]);
// Something that alerts straight away (a process that has only just started doesn't alert about silent servers for a while).
await db.insert(secrets).values({ name: "Old VPN token", type: "api_token", expiryDate: "2020-01-01", warnDays: 30 });
// Switched off, so collecting the alerts doesn't try to reach it.
await db.insert(integrations).values({ type: "gitea", name: "Gitea", baseUrl: "https://git.lab", config: "{}", enabled: false });
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: who } };
next();
});
a.use("/api/me", meRouter);
a.use("/api/share-links", shareLinksRouter);
// The public route has no sign-in: a request there carries no session at all.
const pub = express();
pub.use("/api/public/wall", publicWallRouter);
a.use(pub);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const send = (method: string, path: string, body?: unknown) =>
fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
test("a page with its filters can be pinned, and anything that isn't a path in this app can't", async () => {
const good = ["/servers", "/servers?status=offline", "/servers?q=elsa+running&sort=name&dir=desc&tag=back%C3%A5k"];
const res = await send("PUT", "/me/favorites", { paths: good });
assert.equal(res.status, 200);
assert.deepEqual((await res.json()).favorites, good);
for (const bad of ["//evil.example", "https://evil.example/x", "/servers?q=<script>", "/servers?q=a b", "/servers?", "/servers?" + "a".repeat(161), "servers"]) {
assert.equal((await send("PUT", "/me/favorites", { paths: [bad] })).status, 400, bad);
}
const me = await (await send("GET", "/me")).json();
assert.deepEqual(me.user.favorites, good);
});
test("the dashboard layout is saved for the person, read back with them, and reset by sending nothing", async () => {
assert.deepEqual((await (await send("GET", "/me")).json()).user.dashboard, { hidden: [], order: {} });
const layout = { hidden: ["Gitea", "Gitea", "osTicket"], order: { DNS: 1, Secrets: 0 } };
const res = await send("PUT", "/me/dashboard", layout);
assert.equal(res.status, 200);
assert.deepEqual((await res.json()).dashboard, { hidden: ["Gitea", "osTicket"], order: { DNS: 1, Secrets: 0 } }, "a card named twice is hidden once");
assert.deepEqual((await (await send("GET", "/me")).json()).user.dashboard, { hidden: ["Gitea", "osTicket"], order: { DNS: 1, Secrets: 0 } });
who = "viewer";
assert.deepEqual((await (await send("GET", "/me")).json()).user.dashboard, { hidden: [], order: {} }, "someone else's arrangement is theirs");
who = "admin";
await send("PUT", "/me/dashboard", { hidden: [], order: {} });
const [row] = await db.select().from(users).where(eq(users.oidcSub, "admin"));
assert.equal(row.dashboardLayout, null, "the default layout stores nothing");
});
test("a layout that isn't one is refused", async () => {
for (const bad of [
{ hidden: "Gitea", order: {} },
{ hidden: [], order: { DNS: 1.5 } },
{ hidden: [], order: { DNS: -1 } },
{ hidden: [], order: { DNS: 100000 } },
{ hidden: ["x".repeat(61)], order: {} },
{ hidden: new Array(61).fill("a").map((_, i) => `c${i}`), order: {} },
{},
]) {
assert.equal((await send("PUT", "/me/dashboard", bad)).status, 400, JSON.stringify(bad).slice(0, 60));
}
});
test("only an administrator can make, list or remove share links", async () => {
who = "viewer";
assert.equal((await send("GET", "/share-links")).status, 403);
assert.equal((await send("POST", "/share-links", { label: "TV", detail: "summary", expiresInDays: null })).status, 403);
assert.equal((await send("DELETE", "/share-links/1")).status, 403);
who = "admin";
});
let summaryToken = "";
let namesToken = "";
let namesId = 0;
test("a link is made once: the secret is in that answer and nowhere after", async () => {
const made = await send("POST", "/share-links", { label: "Hall TV", detail: "summary", expiresInDays: null });
assert.equal(made.status, 201);
const body = await made.json();
summaryToken = body.token;
assert.ok(summaryToken.length >= 30);
assert.equal(body.path, `/share/wall/${summaryToken}`);
assert.equal(body.link.label, "Hall TV");
const named = await (await send("POST", "/share-links", { label: "Rack screen", detail: "names", expiresInDays: 30 })).json();
namesToken = named.token;
namesId = named.link.id;
assert.ok(named.link.expiresAt);
const list = await (await send("GET", "/share-links")).json();
assert.equal(list.links.length, 2);
const text = JSON.stringify(list);
assert.ok(!text.includes(summaryToken) && !text.includes(namesToken), "the list never shows the secret");
assert.ok(!text.includes("tokenHash"), "or its hash");
const [stored] = await db.select().from(shareLinks).where(eq(shareLinks.id, body.link.id));
assert.notEqual(stored.tokenHash, summaryToken);
assert.equal(stored.tokenHash.length, 64);
const audits = (await db.select().from(auditLog)).filter((a) => a.category === "share_link");
assert.equal(audits.length, 2);
assert.ok(audits.every((a) => !(a.detail ?? "").includes(summaryToken) && !(a.detail ?? "").includes(namesToken)));
});
test("a bad request is refused", async () => {
for (const bad of [{ label: "", detail: "summary", expiresInDays: null }, { label: "x", detail: "everything", expiresInDays: null }, { label: "x", detail: "summary", expiresInDays: 0 }, { label: "x", detail: "summary", expiresInDays: 400 }, { label: "x", detail: "summary" }]) {
assert.equal((await send("POST", "/share-links", bad)).status, 400, JSON.stringify(bad));
}
});
test("the public wall needs no sign-in, and a summary link says how things are in numbers only", async () => {
who = "nobody-at-all"; // no such user: the public route must not care
after(() => {
who = "admin";
});
const res = await fetch(`${base}/public/wall/${summaryToken}`);
assert.equal(res.status, 200);
assert.equal(res.headers.get("cache-control"), "no-store");
assert.match(res.headers.get("x-robots-tag") ?? "", /noindex/);
const wall = await res.json();
assert.equal(wall.detail, "summary");
assert.equal(wall.servers.offline, 1);
assert.equal(wall.servers.online, 1);
assert.equal(wall.level, "critical");
assert.ok(wall.alerts.critical + wall.alerts.warning >= 1);
assert.equal(wall.problems, undefined);
assert.equal(wall.integrations, undefined);
assert.equal(wall.maintenanceWindows, undefined);
const text = JSON.stringify(wall);
for (const secret of ["elsa", "anna", "Gitea", "git.lab", "hash", "Old VPN token"]) assert.ok(!text.includes(secret), `a summary must not contain "${secret}"`);
assert.deepEqual(wall.display, { dateFormat: "ymd", timeFormat: "24h" });
who = "admin";
});
test("a names link adds what is wrong and what is in maintenance, but not addresses or settings", async () => {
const [anna] = await db.select().from(servers).where(eq(servers.name, "anna"));
await db.insert(maintenanceWindows).values({
targetType: "server",
targetId: anna.id,
reason: "secret reason text",
startedAt: new Date(Date.now() - 600_000).toISOString(),
endsAt: new Date(Date.now() + 3600_000).toISOString(),
createdBy: "Ada",
});
const wall = await (await fetch(`${base}/public/wall/${namesToken}`)).json();
assert.equal(wall.detail, "names");
assert.ok(wall.problems.some((p: { message: string }) => p.message.includes("Old VPN token")), JSON.stringify(wall.problems));
assert.deepEqual(wall.maintenanceWindows.map((w: { name: string }) => w.name), ["anna"]);
assert.equal(wall.maintenance, 1);
assert.deepEqual(wall.integrations, [], "a disabled integration isn't listed");
const text = JSON.stringify(wall);
for (const secret of ["git.lab", "secret reason text", "tokenHash", "apiToken"]) assert.ok(!text.includes(secret), `names must not contain "${secret}"`);
});
test("a link that never existed, ended, or was removed all answer the same", async () => {
const unknown = await fetch(`${base}/public/wall/${"x".repeat(32)}`);
assert.equal(unknown.status, 404);
const unknownBody = await unknown.text();
// ended
await db.update(shareLinks).set({ expiresAt: new Date(Date.now() - 1000).toISOString() }).where(eq(shareLinks.id, namesId));
const expired = await fetch(`${base}/public/wall/${namesToken}`);
assert.equal(expired.status, 404);
assert.equal(await expired.text(), unknownBody);
assert.equal((await (await send("GET", "/share-links")).json()).links.find((l: { id: number }) => l.id === namesId).expired, true);
// removed
assert.equal((await send("DELETE", `/share-links/${namesId}`)).status, 204);
const gone = await fetch(`${base}/public/wall/${namesToken}`);
assert.equal(gone.status, 404);
assert.equal(await gone.text(), unknownBody);
assert.equal((await send("DELETE", `/share-links/${namesId}`)).status, 404);
assert.equal((await fetch(`${base}/public/wall/short`)).status, 404);
// the other link carries on
assert.equal((await fetch(`${base}/public/wall/${summaryToken}`)).status, 200);
});
test("using a link is noted, and removal is in the audit log without the secret", async () => {
const [link] = await db.select().from(shareLinks);
assert.ok(link.lastUsedAt, "the summary link was opened above");
const audits = (await db.select().from(auditLog)).filter((a) => a.category === "share_link" && a.action === "delete");
assert.equal(audits.length, 1);
assert.match(audits[0].detail ?? "", /Rack screen/);
});
test("there is a limit to how many links there can be", async () => {
let made = (await db.select().from(shareLinks)).length;
while (made < 20) {
assert.equal((await send("POST", "/share-links", { label: `Link ${made}`, detail: "summary", expiresInDays: 1 })).status, 201);
made++;
}
const over = await send("POST", "/share-links", { label: "One too many", detail: "summary", expiresInDays: 1 });
assert.equal(over.status, 400);
assert.equal((await over.json()).error, "too_many");
});
});
+17 -1
View File
@@ -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
View File
@@ -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)}`),
},
+7 -1
View File
@@ -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"];
+53
View File
@@ -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>
);
}
+39
View File
@@ -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>
);
}
+2
View File
@@ -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}>
+199
View File
@@ -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>
);
}
+11 -2
View File
@@ -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 === "[") {
+33 -8
View File
@@ -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(() => {
+20 -2
View File
@@ -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(" ");
+2
View File
@@ -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.
+31 -7
View File
@@ -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>
)}
+1
View File
@@ -22,6 +22,7 @@ export const GO_SHORTCUTS: GoShortcut[] = [
export const OTHER_SHORTCUTS: { keys: string; label: string }[] = [
{ keys: "Ctrl K", label: "Search, and run actions (silence a server, switch theme…)" },
{ keys: "/", label: "Jump to the search box of the table on this page" },
{ keys: "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" },
+1 -1
View File
@@ -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() {
+47 -6
View File
@@ -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 && (
+1 -1
View File
@@ -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]>();
+1 -1
View File
@@ -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) {
+1 -1
View File
@@ -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]>();
+32 -4
View File
@@ -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)}>
+1 -1
View File
@@ -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;
+1 -1
View File
@@ -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]>();
+1 -1
View File
@@ -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]>();
+190
View File
@@ -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
View File
@@ -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>
+1 -1
View File
@@ -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;
+1
View File
@@ -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" },
+109
View File
@@ -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>
}
/>
);
}
+1 -1
View File
@@ -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]>();
+1 -1
View File
@@ -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]>();
+1 -1
View File
@@ -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
View File
@@ -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>
</>
}
/>
);
}
+199
View File
@@ -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>
</>
);
}
+47
View File
@@ -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);
}
+95
View File
@@ -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);
}
+52
View File
@@ -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;