Add named wall displays: pages, order and speed per screen

An administrator can make named displays (Hall TV, Office monitor) under
Settings -> Share links, each with an address of its own (/wall/hall-tv), the
pages it rotates through in the board's order, and a rotation speed. The
signed-in wall opens one from its address and can switch between them, and a
wall share link can open one too. The address still wins over the display's
speed, then the browser's choice.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-12 23:04:22 +01:00
1 parent 639408c0d0
commit 333146e8e3
24 files changed
+10411 -22

No files matched your search

+13
View File
@@ -1574,6 +1574,7 @@ links): the wall display, or a status page. Only a hash of the secret is stored.
| `token_hash` | text NOT NULL, unique | SHA-256 of the secret in the address; the secret itself is shown once and never stored. | | `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. | | `token_prefix` | text NOT NULL | The first characters of the secret, to tell links apart in the list. |
| `detail` | text NOT NULL, default `summary` | For a wall: `summary` (numbers only) or `names` (also the names of what is wrong, in maintenance, and the integrations). Not used by a status page. | | `detail` | text NOT NULL, default `summary` | For a wall: `summary` (numbers only) or `names` (also the names of what is wrong, in maintenance, and the integrations). Not used by a status page. |
| `display_id` | integer | For a wall: the named display it opens (→ `wall_displays.id`); null = the whole board. Cleared in code when the display is removed (the foreign key has no ON DELETE action in SQLite's added column). |
| `kind` | text NOT NULL, default `wall` | `wall`, `status` or `calendar` (an iCalendar feed of what is coming up; `detail` says whether it carries names). Each kind's address opens only that kind. | | `kind` | text NOT NULL, default `wall` | `wall`, `status` or `calendar` (an iCalendar feed of what is coming up; `detail` says whether it carries names). Each kind's address opens only that kind. |
| `title`, `message` | text | A status page's heading and its optional message; null for a wall. | | `title`, `message` | text | A status page's heading and its optional message; null for a wall. |
| `created_by` | text | The administrator's name at the time. | | `created_by` | text | The administrator's name at the time. |
@@ -1581,6 +1582,18 @@ links): the wall display, or a status page. Only a hash of the secret is stored.
| `expires_at` | text | ISO; null = until removed. | | `expires_at` | text | ISO; null = until removed. |
| `last_used_at` | text | ISO; updated at most once a minute. | | `last_used_at` | text | ISO; updated at most once a minute. |
#### `wall_displays`
Named wall displays (services/wallDisplays.ts): which pages the board rotates through, and how fast.
| Column | Type | Notes |
|---|---|---|
| `id`, `name` | | |
| `slug` | text NOT NULL, unique | The address: `/wall/<slug>`; lower case letters, digits and single hyphens. Made from the name; kept when the name is changed. |
| `pages` | text NOT NULL, default `[]` | JSON: page ids in the order they are shown — `overview`, `alerts`, `group:<id>`; empty = every page the board has. |
| `rotate_seconds` | integer | 10–600; null = not set (the address or the browser decides). |
| `created_by`, `created_at` | | |
#### `status_items` #### `status_items`
What a status page shows, in order. What a status page shows, in order.
+2
View File
@@ -437,6 +437,8 @@ The Map's second view, **Dependencies**, draws what needs what with the foundati
a dependency or a "runs on" link, each with its status). Pick a box and what would go down with it turns red and what it relies on blue, a dependency or a "runs on" link, each with its status). Pick a box and what would go down with it turns red and what it relies on blue,
with a sentence underneath — "If it goes down, 4 things go with it: …" — so the answer to "what breaks if I reboot this?" is there before you do it. with a sentence underneath — "If it goes down, 4 things go with it: …" — so the answer to "what breaks if I reboot this?" is there before you do it.
**Named wall displays** (Settings → Share links → *Wall displays*, administrators). One board for every screen is rarely right: the hall TV wants the overview and what needs attention, the office monitor the apps and the network. A display is a **name**, an **address of its own** (`/wall/hall-tv`, made from the name unless you give one — it stays put if you later correct the name, so a bookmark on a screen keeps working), **which pages it rotates through and in what order** (the overview, *Needs attention*, and a page for each group of integrations; none ticked is every page) and **how fast**. A page that has nothing to show just now (*Needs attention* with nothing wrong, a group with no integrations) is left out, and a display none of whose pages exist shows the overview. The signed-in wall opens one from its address and has a *Display* choice in its footer; the footer says which display it is; an unknown address says so and shows everything. How fast is decided by the address (`?rotate=45`) first, then the display, then what this browser last chose. A **wall share link** can open a display too (choose it when making the link): the public board then rotates through that display's pages at its speed; remove the display and the link goes on opening the whole board. Up to twenty displays; each change is in the audit log and the change log. A display only chooses among the board's pages — what the board shows (and, for a share link, how much: numbers only or with names) is unchanged.
**Wall display** (`/wall`, also on the dashboard and the user menu) is a **Wall display** (`/wall`, also on the dashboard and the user menu) is a
full-screen status board for a spare monitor or tablet: the overall state in full-screen status board for a spare monitor or tablet: the overall state in
large type, servers online, alerts, maintenance windows and failing integrations — and, for what is connected, how many Hetzner servers and game servers are running, how many critical vulnerabilities and stuck downloads there are, and one line for each group of the menu (Infrastructure, Apps …) saying whether it is well — large type, servers online, alerts, maintenance windows and failing integrations — and, for what is connected, how many Hetzner servers and game servers are running, how many critical vulnerabilities and stuck downloads there are, and one line for each group of the menu (Infrastructure, Apps …) saying whether it is well —
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE `wall_displays` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`name` text NOT NULL,
`slug` text NOT NULL,
`pages` text DEFAULT '[]' NOT NULL,
`rotate_seconds` integer,
`created_by` text,
`created_at` text DEFAULT (current_timestamp) NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `wall_displays_slug_unique` ON `wall_displays` (`slug`);--> statement-breakpoint
ALTER TABLE `share_links` ADD `display_id` integer REFERENCES wall_displays(id);
File diff suppressed because it is too large. Load diff
+7
View File
@@ -673,6 +673,13 @@
"when": 1794514473426, "when": 1794514473426,
"tag": "0095_user_language", "tag": "0095_user_language",
"breakpoints": true "breakpoints": true
},
{
"idx": 96,
"version": "6",
"when": 1794520424972,
"tag": "0096_wall_displays",
"breakpoints": true
} }
] ]
} }
+2
View File
@@ -72,6 +72,7 @@ import { speedtestRouter } from "./routes/speedtest.js";
import { fragnetRouter } from "./routes/fragnet.js"; import { fragnetRouter } from "./routes/fragnet.js";
import { arrRouter } from "./routes/arr.js"; import { arrRouter } from "./routes/arr.js";
import { wallRouter } from "./routes/wall.js"; import { wallRouter } from "./routes/wall.js";
import { wallDisplaysRouter } from "./routes/wallDisplays.js";
import { adguardRouter } from "./routes/adguard.js"; import { adguardRouter } from "./routes/adguard.js";
import { technitiumRouter } from "./routes/technitium.js"; import { technitiumRouter } from "./routes/technitium.js";
import { downloadsRouter } from "./routes/downloads.js"; import { downloadsRouter } from "./routes/downloads.js";
@@ -229,6 +230,7 @@ export function createApp() {
app.use("/api/fragnet", fragnetRouter); app.use("/api/fragnet", fragnetRouter);
app.use("/api/arr", arrRouter); app.use("/api/arr", arrRouter);
app.use("/api/wall", wallRouter); app.use("/api/wall", wallRouter);
app.use("/api/wall-displays", wallDisplaysRouter);
app.use("/api/adguard", adguardRouter); app.use("/api/adguard", adguardRouter);
app.use("/api/technitium", technitiumRouter); app.use("/api/technitium", technitiumRouter);
app.use("/api/downloads", downloadsRouter); app.use("/api/downloads", downloadsRouter);
+15
View File
@@ -850,6 +850,19 @@ export type ShareLinkDetail = (typeof shareLinkDetails)[number];
export const shareLinkKinds = ["wall", "status", "calendar"] as const; export const shareLinkKinds = ["wall", "status", "calendar"] as const;
export type ShareLinkKind = (typeof shareLinkKinds)[number]; export type ShareLinkKind = (typeof shareLinkKinds)[number];
// Named wall displays ("Hall TV"): which pages the board rotates through, in which order, and how fast — services/wallDisplays.ts. A share link to a wall can open one.
export const wallDisplays = sqliteTable("wall_displays", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
slug: text("slug").notNull().unique(), // the address: /wall/<slug>
pages: text("pages").notNull().default("[]"), // JSON: page ids in order ("overview", "alerts", "group:apps" …); empty = every page the board has
rotateSeconds: integer("rotate_seconds"), // how long each page stays; null = not set (the address or the browser decides, else the board does not rotate)
createdBy: text("created_by"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// 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 // 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. // 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", { export const shareLinks = sqliteTable("share_links", {
@@ -860,6 +873,8 @@ export const shareLinks = sqliteTable("share_links", {
// summary = how things are, in numbers; names = also the names of what is wrong, in maintenance, and the integrations // 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"), detail: text("detail").$type<ShareLinkDetail>().notNull().default("summary"),
kind: text("kind").$type<ShareLinkKind>().notNull().default("wall"), kind: text("kind").$type<ShareLinkKind>().notNull().default("wall"),
// For a wall: the named display it opens (its pages and speed); null = the whole board. Taken away with the display.
displayId: integer("display_id").references(() => wallDisplays.id, { onDelete: "set null" }),
// A status page's own heading and an optional announcement under it ("Movies are being updated tonight"). Unused by a wall. // A status page's own heading and an optional announcement under it ("Movies are being updated tonight"). Unused by a wall.
title: text("title"), title: text("title"),
message: text("message"), message: text("message"),
+3 -1
View File
@@ -1,6 +1,7 @@
import { Router } from "express"; import { Router } from "express";
import { NOT_FOUND, resolveShareLink } from "../services/shareLinks.js"; import { NOT_FOUND, resolveShareLink } from "../services/shareLinks.js";
import { buildPublicWall } from "../services/publicWall.js"; import { buildPublicWall } from "../services/publicWall.js";
import { displayForLink } from "../services/wallDisplays.js";
import { rateLimit } from "../utils/rateLimit.js"; import { rateLimit } from "../utils/rateLimit.js";
import { asyncHandler } from "../utils/asyncHandler.js"; import { asyncHandler } from "../utils/asyncHandler.js";
@@ -16,5 +17,6 @@ publicWallRouter.get("/:token", limiter, asyncHandler(async (req, res) => {
if (!link || link.kind !== "wall") return res.status(404).json(NOT_FOUND); if (!link || link.kind !== "wall") return res.status(404).json(NOT_FOUND);
res.setHeader("Cache-Control", "no-store"); res.setHeader("Cache-Control", "no-store");
res.setHeader("X-Robots-Tag", "noindex, nofollow"); res.setHeader("X-Robots-Tag", "noindex, nofollow");
res.json(await buildPublicWall(link.detail)); // The named display this link opens, if any: which pages the board rotates through and how fast (the picture itself is the same).
res.json({ ...(await buildPublicWall(link.detail)), displayConfig: await displayForLink(link.displayId) });
})); }));
+8 -2
View File
@@ -2,7 +2,7 @@ import { Router } from "express";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { z } from "zod"; import { z } from "zod";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { shareLinkDetails, shareLinkKinds, shareLinks, statusItemKinds, statusItems } from "../db/schema.js"; import { shareLinkDetails, shareLinkKinds, shareLinks, statusItemKinds, statusItems, wallDisplays } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js"; import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js"; import { recordAudit } from "../services/audit.js";
import { createShareLink, publicShareLink } from "../services/shareLinks.js"; import { createShareLink, publicShareLink } from "../services/shareLinks.js";
@@ -22,6 +22,8 @@ const createSchema = z.object({
kind: z.enum(shareLinkKinds).default("wall"), kind: z.enum(shareLinkKinds).default("wall"),
// For a wall: how much it shows. A status page always shows only names and states, so this is ignored for it. For a calendar: summary leaves the names out of the events. // For a wall: how much it shows. A status page always shows only names and states, so this is ignored for it. For a calendar: summary leaves the names out of the events.
detail: z.enum(shareLinkDetails).default("summary"), detail: z.enum(shareLinkDetails).default("summary"),
// For a wall: a named display (its pages and speed) instead of the whole board.
displayId: z.number().int().positive().nullable().optional(),
title: z.string().trim().max(MAX_TITLE).optional(), title: z.string().trim().max(MAX_TITLE).optional(),
message: z.string().trim().max(MAX_MESSAGE).optional(), message: z.string().trim().max(MAX_MESSAGE).optional(),
expiresInDays: z.number().int().min(1).max(365).nullable(), expiresInDays: z.number().int().min(1).max(365).nullable(),
@@ -49,6 +51,10 @@ shareLinksRouter.post("/", asyncHandler(async (req, res) => {
if (existing.length >= MAX_LINKS) { 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.` }); return res.status(400).json({ error: "too_many", message: `There are already ${MAX_LINKS} share links. Remove one you no longer use first.` });
} }
if (parsed.data.displayId != null) {
const [shown] = await db.select({ id: wallDisplays.id }).from(wallDisplays).where(eq(wallDisplays.id, parsed.data.displayId)).limit(1);
if (!shown) return res.status(400).json({ error: "no_such_display", message: "That wall display doesn't exist (any more)." });
}
const actor = req.currentUser!; const actor = req.currentUser!;
const { link, token } = await createShareLink({ ...parsed.data, createdBy: actor.name ?? actor.email ?? actor.oidcSub }); const { link, token } = await createShareLink({ ...parsed.data, createdBy: actor.name ?? actor.email ?? actor.oidcSub });
await recordAudit({ await recordAudit({
@@ -57,7 +63,7 @@ shareLinksRouter.post("/", asyncHandler(async (req, res) => {
action: "create", action: "create",
targetType: "share_link", targetType: "share_link",
targetId: link.id, targetId: link.id,
detail: { label: link.label, kind: link.kind, detail: link.detail, expiresAt: link.expiresAt }, detail: { label: link.label, kind: link.kind, detail: link.detail, expiresAt: link.expiresAt, ...(link.displayId !== null ? { displayId: link.displayId } : {}) },
}); });
res.status(201).json({ link: publicShareLink(link), token, path: link.kind === "calendar" ? `/api/public/calendar/${token}.ics` : `/share/${link.kind === "status" ? "status" : "wall"}/${token}` }); res.status(201).json({ link: publicShareLink(link), token, path: link.kind === "calendar" ? `/api/public/calendar/${token}.ics` : `/share/${link.kind === "status" ? "status" : "wall"}/${token}` });
})); }));
+79
View File
@@ -0,0 +1,79 @@
import { Router } from "express";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { shareLinks, wallDisplays } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { freeSlug, listDisplays, MAX_DISPLAYS, MAX_SLUG, PAGE_ID, ROTATE_MAX, ROTATE_MIN, shapeDisplay, SLUG, slugOf } from "../services/wallDisplays.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const wallDisplaysRouter = Router();
// Everyone signed in can see the list (the wall's own footer offers them); making, changing and removing one is an administrator's, like the share links they can be opened from.
wallDisplaysRouter.use(requireAuth);
const displaySchema = z.object({
name: z.string().trim().min(1).max(60),
// Left out: made from the name. Given: lower case letters, digits and hyphens.
slug: z.string().trim().max(MAX_SLUG).regex(SLUG, "Use lower case letters, digits and single hyphens, like hall-tv.").optional(),
// The pages in the order the board rotates through them; empty is every page it has.
pages: z.array(z.string().regex(PAGE_ID, "That is not a page of the board.")).max(20).default([]),
rotateSeconds: z.number().int().min(ROTATE_MIN).max(ROTATE_MAX).nullable().default(null),
});
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
const addressOf = (slug: string) => `/wall/${slug}`;
wallDisplaysRouter.get("/", asyncHandler(async (_req, res) => {
res.json({ displays: (await listDisplays()).map(shapeDisplay) });
}));
wallDisplaysRouter.post("/", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = displaySchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "Give the display a name.", details: parsed.error.flatten() });
const all = await listDisplays();
if (all.length >= MAX_DISPLAYS) return res.status(409).json({ error: "too_many", message: `At most ${MAX_DISPLAYS} displays.` });
// A slug asked for that is taken is said to be; one made from the name is made free by a number.
if (parsed.data.slug && all.some((d) => d.slug === parsed.data.slug)) return res.status(409).json({ error: "slug_taken", message: `Another display already has the address ${addressOf(parsed.data.slug)}.` });
const slug = parsed.data.slug ?? freeSlug(slugOf(parsed.data.name), all.map((d) => d.slug));
const actor = req.currentUser!;
const [row] = await db
.insert(wallDisplays)
.values({ name: parsed.data.name, slug, pages: JSON.stringify([...new Set(parsed.data.pages)]), rotateSeconds: parsed.data.rotateSeconds, createdBy: actor.name ?? actor.email ?? actor.oidcSub })
.returning();
await recordAudit({ actor, category: "wall_display", action: "create", targetType: "wall_display", targetId: row.id, detail: { name: row.name, address: addressOf(row.slug) } });
res.status(201).json({ display: shapeDisplay(row) });
}));
wallDisplaysRouter.put("/:id", requireRole("admin"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
const parsed = displaySchema.safeParse(req.body);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "Give the display a name.", details: parsed.error.flatten() });
const all = await listDisplays();
const before = all.find((d) => d.id === id);
if (!before) return res.status(404).json({ error: "not_found" });
// The address stays as it was unless it is changed on purpose, so a bookmark on a screen keeps working when the name is corrected.
const slug = parsed.data.slug ?? before.slug;
if (all.some((d) => d.id !== id && d.slug === slug)) return res.status(409).json({ error: "slug_taken", message: `Another display already has the address ${addressOf(slug)}.` });
const [row] = await db
.update(wallDisplays)
.set({ name: parsed.data.name, slug, pages: JSON.stringify([...new Set(parsed.data.pages)]), rotateSeconds: parsed.data.rotateSeconds })
.where(eq(wallDisplays.id, id))
.returning();
await recordAudit({ actor: req.currentUser!, category: "wall_display", action: "update", targetType: "wall_display", targetId: id, detail: { name: row.name, address: addressOf(row.slug) } });
res.json({ display: shapeDisplay(row) });
}));
wallDisplaysRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [before] = await db.select().from(wallDisplays).where(eq(wallDisplays.id, id)).limit(1);
if (!before) return res.status(404).json({ error: "not_found" });
// A share link that opened it goes on opening the whole board.
await db.update(shareLinks).set({ displayId: null }).where(eq(shareLinks.displayId, id));
await db.delete(wallDisplays).where(eq(wallDisplays.id, id));
await recordAudit({ actor: req.currentUser!, category: "wall_display", action: "delete", targetType: "wall_display", targetId: id, detail: { name: before.name } });
res.status(204).end();
}));
+7
View File
@@ -38,6 +38,7 @@ const KIND_OF_CATEGORY: Record<string, ChangeKind> = {
user: "settings", user: "settings",
push: "settings", push: "settings",
share_link: "settings", share_link: "settings",
wall_display: "settings",
metrics_token: "settings", metrics_token: "settings",
api_token: "settings", api_token: "settings",
alert_rule: "alerts", alert_rule: "alerts",
@@ -259,6 +260,12 @@ export function describeChange(category: string, action: string, detail: Record<
return { title: `Alert settled${str(detail.message) ? `: ${str(detail.message)}` : ""}`, tone: detail.active === true ? "bad" : "good", detail: detail.active === true ? "steady for an hour, and still active" : "steady for an hour, and cleared" }; return { title: `Alert settled${str(detail.message) ? `: ${str(detail.message)}` : ""}`, tone: detail.active === true ? "bad" : "good", detail: detail.active === true ? "steady for an hour, and still active" : "steady for an hour, and cleared" };
case "report/send_monthly": case "report/send_monthly":
return { title: `Monthly report sent${str(detail.month) ? ` (${str(detail.month)})` : ""}`, tone: "neutral", detail: null }; return { title: `Monthly report sent${str(detail.month) ? ` (${str(detail.month)})` : ""}`, tone: "neutral", detail: null };
case "wall_display/create":
return { title: `Wall display added${name ? `: ${name}` : ""}`, tone: "neutral", detail: str(detail.address) };
case "wall_display/update":
return { title: `Wall display changed${name ? `: ${name}` : ""}`, tone: "neutral", detail: str(detail.address) };
case "wall_display/delete":
return { title: `Wall display removed${name ? `: ${name}` : ""}`, tone: "neutral", detail: null };
case "patch_plan/create": case "patch_plan/create":
return { title: `Patch plan added${name ? `: ${name}` : ""}`, tone: "neutral", detail: null }; return { title: `Patch plan added${name ? `: ${name}` : ""}`, tone: "neutral", detail: null };
case "patch_plan/update": case "patch_plan/update":
+3 -1
View File
@@ -17,7 +17,7 @@ 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. */ /** 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; const USED_WRITE_GAP_MS = 60_000;
export async function createShareLink(params: { label: string; detail: ShareLinkDetail; kind?: ShareLinkKind; title?: string | null; message?: string | null; expiresInDays: number | null; createdBy: string; now?: Date }): Promise<{ link: ShareLinkRow; token: string }> { export async function createShareLink(params: { label: string; detail: ShareLinkDetail; kind?: ShareLinkKind; displayId?: number | null; title?: string | null; message?: string | null; expiresInDays: number | null; createdBy: string; now?: Date }): Promise<{ link: ShareLinkRow; token: string }> {
const now = params.now ?? new Date(); const now = params.now ?? new Date();
const token = randomBytes(24).toString("base64url"); const token = randomBytes(24).toString("base64url");
const [link] = await db const [link] = await db
@@ -28,6 +28,7 @@ export async function createShareLink(params: { label: string; detail: ShareLink
tokenPrefix: token.slice(0, 6), tokenPrefix: token.slice(0, 6),
detail: params.detail, detail: params.detail,
kind: params.kind ?? "wall", kind: params.kind ?? "wall",
displayId: (params.kind ?? "wall") === "wall" ? (params.displayId ?? null) : null,
title: params.title?.trim() || null, title: params.title?.trim() || null,
message: params.message?.trim() || null, message: params.message?.trim() || null,
createdBy: params.createdBy, createdBy: params.createdBy,
@@ -57,6 +58,7 @@ export function publicShareLink(link: ShareLinkRow, now: Date = new Date()) {
tokenPrefix: link.tokenPrefix, tokenPrefix: link.tokenPrefix,
detail: link.detail, detail: link.detail,
kind: link.kind, kind: link.kind,
displayId: link.displayId,
title: link.title, title: link.title,
message: link.message, message: link.message,
createdBy: link.createdBy, createdBy: link.createdBy,
+71
View File
@@ -0,0 +1,71 @@
/**
* Named wall displays: "Hall TV", "Office monitor", "Rack tablet". Each is a saved choice of which pages the board rotates through (and in which order) and how fast, with an address of its own
* (`/wall/hall-tv`) that can be bookmarked on the screen it is for, and a share link can open one too. Nothing about what the board shows changes: a display only chooses among the pages the
* board has (the overview, what needs attention, and one for each group of integrations) — see web/src/utils/wallPages.ts.
*/
import { eq } from "drizzle-orm";
import { db } from "../db/client.js";
import { wallDisplays } from "../db/schema.js";
export type WallDisplayRow = typeof wallDisplays.$inferSelect;
/** More displays than there are screens in a house. */
export const MAX_DISPLAYS = 20;
export const ROTATE_MIN = 10;
export const ROTATE_MAX = 600;
/** A page of the board: "overview", "alerts", or "group:<id>" for a group of integrations (infrastructure, apps, backups, network, monitoring, automation, other …). */
export const PAGE_ID = /^(overview|alerts|group:[a-z0-9-]{1,40})$/;
/** The address part of a display: lower case letters, digits and single hyphens. */
export const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/;
export const MAX_SLUG = 40;
/** Pure: a name as an address part — "Hall TV (upstairs)" → "hall-tv-upstairs"; Swedish letters are folded (å, ä → a, ö → o) so the address is plain. */
export function slugOf(name: string): string {
const folded = name
.toLowerCase()
.replace(/[åä]/g, "a")
.replace(/ö/g, "o")
.normalize("NFD")
.replace(/[̀-ͯ]/g, "");
const slug = folded.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, MAX_SLUG).replace(/-+$/g, "");
return slug || "display";
}
/** Pure: a slug nobody else has, by adding -2, -3 … (the display being edited does not count against itself). */
export function freeSlug(wanted: string, taken: Iterable<string>): string {
const used = new Set(taken);
if (!used.has(wanted)) return wanted;
for (let n = 2; ; n++) {
const tail = `-${n}`;
const candidate = `${wanted.slice(0, MAX_SLUG - tail.length)}${tail}`;
if (!used.has(candidate)) return candidate;
}
}
/** What is stored for the pages, read back as a list of page ids; anything that is not one is none (which means every page). */
export function parsePages(stored: string | null | undefined): string[] {
if (!stored) return [];
try {
const v = JSON.parse(stored);
return Array.isArray(v) ? [...new Set(v.filter((p): p is string => typeof p === "string" && PAGE_ID.test(p)))] : [];
} catch {
return [];
}
}
/** A display as everyone signed in sees it. */
export function shapeDisplay(row: WallDisplayRow) {
return { id: row.id, name: row.name, slug: row.slug, pages: parsePages(row.pages), rotateSeconds: row.rotateSeconds, createdBy: row.createdBy, createdAt: row.createdAt };
}
export async function listDisplays(): Promise<WallDisplayRow[]> {
return db.select().from(wallDisplays).orderBy(wallDisplays.name);
}
/** The display a share link points at, as the public board needs it (name, pages, speed) — null when there is none or it was taken away. */
export async function displayForLink(displayId: number | null): Promise<{ name: string; pages: string[]; rotateSeconds: number | null } | null> {
if (displayId === null) return null;
const [row] = await db.select().from(wallDisplays).where(eq(wallDisplays.id, displayId)).limit(1);
return row ? { name: row.name, pages: parsePages(row.pages), rotateSeconds: row.rotateSeconds } : null;
}
+229
View File
@@ -0,0 +1,229 @@
/**
* Named wall displays: the address made from a name, which pages a display rotates through and in what order, how fast (and who wins: the address, the display, or the browser), the admin routes, the share
* link that opens one, and what the public board is told.
*
* 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-walls-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
process.env.HEALTH_STARTUP_GRACE_MS = "0";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, shareLinks, auditLog } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const W = await import("../src/services/wallDisplays.js");
const { createShareLink } = await import("../src/services/shareLinks.js");
const { wallDisplaysRouter } = await import("../src/routes/wallDisplays.js");
const { shareLinksRouter } = await import("../src/routes/shareLinks.js");
const { publicWallRouter } = await import("../src/routes/publicWall.js");
const { describeChange } = await import("../src/services/changeLog.js");
const P = await import("../../web/src/utils/wallPages.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
describe("the address", () => {
test("a name becomes an address of lower case letters, digits and single hyphens; Swedish letters are folded", () => {
assert.equal(W.slugOf("Hall TV"), "hall-tv");
assert.equal(W.slugOf(" Office monitor (upstairs)! "), "office-monitor-upstairs");
assert.equal(W.slugOf("Köket & Vardagsrummet"), "koket-vardagsrummet");
assert.equal(W.slugOf("Åke"), "ake");
assert.equal(W.slugOf("!!!"), "display", "nothing to make one from");
assert.ok(W.slugOf("x".repeat(100)).length <= W.MAX_SLUG);
for (const s of [W.slugOf("Hall TV"), W.slugOf("Köket"), W.slugOf("a b")]) assert.match(s, W.SLUG);
});
test("one that is taken gets a number", () => {
assert.equal(W.freeSlug("hall-tv", []), "hall-tv");
assert.equal(W.freeSlug("hall-tv", ["hall-tv"]), "hall-tv-2");
assert.equal(W.freeSlug("hall-tv", ["hall-tv", "hall-tv-2", "hall-tv-3"]), "hall-tv-4");
assert.ok(W.freeSlug("y".repeat(40), ["y".repeat(40)]).length <= W.MAX_SLUG);
});
test("a stored list of pages is read back as ids of pages that exist, once each; anything else is none", () => {
assert.deepEqual(W.parsePages(JSON.stringify(["overview", "group:apps", "overview", "bogus", 5, "group:Bad"])), ["overview", "group:apps"]);
for (const odd of [null, undefined, "", "{", "{}", '"overview"']) assert.deepEqual(W.parsePages(odd as string), []);
});
});
describe("what a display shows, and how fast", () => {
const board: import("../../web/src/utils/wallPages.js").WallPage[] = [
{ id: "overview", label: "Overview", kind: "overview" },
{ id: "alerts", label: "Needs attention", kind: "alerts" },
{ id: "group:apps", label: "Apps", kind: "group", groupId: "apps" },
{ id: "group:network", label: "Network", kind: "group", groupId: "network" },
];
test("the pages it lists, in its order, that the board has now; none listed is every page", () => {
assert.deepEqual(P.applyDisplay(board, []).map((p) => p.id), ["overview", "alerts", "group:apps", "group:network"]);
assert.deepEqual(P.applyDisplay(board, ["group:network", "overview"]).map((p) => p.id), ["group:network", "overview"], "its order, not the board's");
assert.deepEqual(P.applyDisplay(board, ["overview", "overview", "group:apps"]).map((p) => p.id), ["overview", "group:apps"]);
});
test("a page the board has not got just now is left out, and a display with none of its pages shows the overview", () => {
const quiet = board.filter((p) => p.id !== "alerts");
assert.deepEqual(P.applyDisplay(quiet, ["alerts", "group:apps"]).map((p) => p.id), ["group:apps"]);
assert.deepEqual(P.applyDisplay(quiet, ["alerts"]).map((p) => p.id), ["overview"]);
assert.deepEqual(P.applyDisplay(quiet, ["group:nothing"]).map((p) => p.id), ["overview"]);
});
test("the pages a display may be given are the board's, in its order", () => {
const ids = P.displayPageChoices().map((c) => c.id);
assert.deepEqual(ids.slice(0, 2), ["overview", "alerts"]);
assert.ok(ids.includes("group:infrastructure") && ids.includes("group:other"));
for (const id of ids) assert.match(id, W.PAGE_ID, `${id} is a page the server accepts`);
});
test("the address wins, then what the display says, then what the browser last chose", () => {
assert.equal(P.rotateSeconds("45", "off", 60), 45, "the address");
assert.equal(P.rotateSeconds("off", "30", 60), null, "the address may switch it off");
assert.equal(P.rotateSeconds(null, "off", 60), 60, "the display, over the browser");
assert.equal(P.rotateSeconds(null, "30", null), 30, "the browser, when the display says nothing");
assert.equal(P.rotateSeconds(null, null, null), null);
assert.equal(P.rotateSeconds(null, null, 5), P.ROTATE_MIN, "a speed out of range is brought into it");
assert.equal(P.rotateSeconds(null, "30"), 30, "existing callers are unchanged");
});
});
describe("the routes", () => {
let app: Server;
let base = "";
let who = "root";
const call = (method: string, path: string, body?: unknown) => fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
before(async () => {
await db.insert(users).values([
{ oidcSub: "root", name: "Rut", role: "admin" },
{ oidcSub: "viewer", name: "Vera", role: "viewer" },
]);
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/wall-displays", wallDisplaysRouter);
a.use("/api/share-links", shareLinksRouter);
a.use("/api/public/wall", publicWallRouter);
app = await new Promise<Server>((resolve) => {
const x = a.listen(0, "127.0.0.1", () => resolve(x));
});
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.
}
});
test("an administrator makes one, the address is made from the name, and anyone signed in can see the list", async () => {
const res = await call("POST", "/wall-displays", { name: "Hall TV", pages: ["overview", "group:apps"], rotateSeconds: 30 });
assert.equal(res.status, 201);
const { display } = await res.json();
assert.deepEqual([display.name, display.slug, display.pages, display.rotateSeconds], ["Hall TV", "hall-tv", ["overview", "group:apps"], 30]);
assert.equal(display.createdBy, "Rut");
who = "viewer";
const list = await (await call("GET", "/wall-displays")).json();
assert.deepEqual(list.displays.map((d: { slug: string }) => d.slug), ["hall-tv"]);
who = "root";
});
test("a viewer can not make, change or remove one", async () => {
who = "viewer";
assert.equal((await call("POST", "/wall-displays", { name: "No" })).status, 403);
const id = (await (await call("GET", "/wall-displays")).json()).displays[0].id;
assert.equal((await call("PUT", `/wall-displays/${id}`, { name: "No" })).status, 403);
assert.equal((await call("DELETE", `/wall-displays/${id}`)).status, 403);
who = "root";
});
test("a second with the same name gets a number; an address asked for that is taken is refused; a bad one is refused with a reason", async () => {
const second = (await (await call("POST", "/wall-displays", { name: "Hall TV" })).json()).display;
assert.equal(second.slug, "hall-tv-2");
assert.deepEqual([second.pages, second.rotateSeconds], [[], null], "no pages is every page");
const taken = await call("POST", "/wall-displays", { name: "Other", slug: "hall-tv" });
assert.equal(taken.status, 409);
assert.equal((await taken.json()).error, "slug_taken");
for (const bad of [{ name: "" }, { name: "x", slug: "Has Spaces" }, { name: "x", slug: "-lead" }, { name: "x", pages: ["nonsense"] }, { name: "x", pages: ["group:UPPER"] }, { name: "x", rotateSeconds: 3 }, { name: "x", rotateSeconds: 9999 }, { name: "x", pages: Array(25).fill("overview") }]) {
assert.equal((await call("POST", "/wall-displays", bad)).status, 400, JSON.stringify(bad).slice(0, 50));
}
assert.match((await (await call("POST", "/wall-displays", { name: "x", pages: ["nonsense"] })).json()).message, /not a page of the board/);
await call("DELETE", `/wall-displays/${second.id}`);
});
test("changing it keeps its address unless that is changed on purpose, so a bookmark on a screen survives a corrected name", async () => {
const id = (await (await call("GET", "/wall-displays")).json()).displays.find((d: { slug: string }) => d.slug === "hall-tv").id;
const renamed = (await (await call("PUT", `/wall-displays/${id}`, { name: "Hallway TV", pages: ["group:network"], rotateSeconds: null })).json()).display;
assert.deepEqual([renamed.name, renamed.slug, renamed.pages, renamed.rotateSeconds], ["Hallway TV", "hall-tv", ["group:network"], null]);
const moved = (await (await call("PUT", `/wall-displays/${id}`, { name: "Hallway TV", slug: "hallway" })).json()).display;
assert.equal(moved.slug, "hallway");
assert.equal((await call("PUT", "/wall-displays/9999", { name: "x" })).status, 404);
assert.equal((await call("PUT", "/wall-displays/abc", { name: "x" })).status, 400);
await call("PUT", `/wall-displays/${id}`, { name: "Hall TV", slug: "hall-tv", pages: ["overview", "group:apps"], rotateSeconds: 30 });
});
test("a wall share link can open one; the public board is told its name, pages and speed; one that is gone opens the whole board", async () => {
const id = (await (await call("GET", "/wall-displays")).json()).displays[0].id;
const made = await call("POST", "/share-links", { label: "Hall screen", kind: "wall", detail: "summary", displayId: id, expiresInDays: null });
assert.equal(made.status, 201);
const { link, token } = await made.json();
assert.equal(link.displayId, id);
const board = await (await call("GET", `/public/wall/${token}`)).json();
assert.deepEqual(board.displayConfig, { name: "Hall TV", pages: ["overview", "group:apps"], rotateSeconds: 30 });
// a link with no display says none
const plain = (await (await call("POST", "/share-links", { label: "Whole board", kind: "wall", expiresInDays: null })).json()).token;
assert.equal((await (await call("GET", `/public/wall/${plain}`)).json()).displayConfig, null);
// taking the display away leaves the link working, on the whole board
assert.equal((await call("DELETE", `/wall-displays/${id}`)).status, 204);
const after = await (await call("GET", `/public/wall/${token}`)).json();
assert.equal(after.displayConfig, null);
const [row] = await db.select().from(shareLinks).where(eq(shareLinks.label, "Hall screen"));
assert.equal(row.displayId, null);
});
test("a link can only open a display that exists, only a wall can, and the rest of what it needs is unchanged", async () => {
const refused = await call("POST", "/share-links", { label: "x", kind: "wall", displayId: 9999, expiresInDays: null });
assert.equal(refused.status, 400);
assert.equal((await refused.json()).error, "no_such_display");
const display = (await (await call("POST", "/wall-displays", { name: "For status" })).json()).display;
const calendar = (await (await call("POST", "/share-links", { label: "cal", kind: "calendar", detail: "summary", displayId: display.id, expiresInDays: null })).json()).link;
assert.equal(calendar.displayId, null, "a calendar has no display");
void createShareLink;
});
test("it is in the audit log and the change log", async () => {
const audit = (await db.select().from(auditLog)).filter((a) => a.category === "wall_display");
assert.deepEqual([...new Set(audit.map((a) => a.action))].sort(), ["create", "delete", "update"]);
assert.deepEqual(describeChange("wall_display", "create", { name: "Hall TV", address: "/wall/hall-tv" }), { title: "Wall display added: Hall TV", tone: "neutral", detail: "/wall/hall-tv" });
assert.equal(describeChange("wall_display", "update", { name: "Hall TV" }).title, "Wall display changed: Hall TV");
assert.equal(describeChange("wall_display", "delete", { name: "Hall TV" }).title, "Wall display removed: Hall TV");
});
test("no more than twenty", async () => {
for (let i = 0; i < 25; i++) {
const r = await call("POST", "/wall-displays", { name: `Screen ${i}` });
if (r.status === 409) {
assert.equal((await r.json()).error, "too_many");
return;
}
}
assert.fail("never refused");
});
});
+1
View File
@@ -166,6 +166,7 @@ export default function App() {
<Fragment key={lang}> <Fragment key={lang}>
<Routes> <Routes>
<Route path="/wall" element={<Wall />} /> <Route path="/wall" element={<Wall />} />
<Route path="/wall/:slug" element={<Wall />} />
<Route path="*" element={<Shelled user={user} />} /> <Route path="*" element={<Shelled user={user} />} />
</Routes> </Routes>
</Fragment> </Fragment>
+29 -1
View File
@@ -53,11 +53,31 @@ export interface PublicStatus {
} }
/** A link that opens the wall display, or a status page, without signing in, as the settings list shows it (never the secret). */ /** A link that opens the wall display, or a status page, without signing in, as the settings list shows it (never the secret). */
/** A named wall display: which pages the board rotates through (in order; none is every page) and how fast. */
export interface WallDisplay {
id: number;
name: string;
/** The address: /wall/<slug>. */
slug: string;
pages: string[];
rotateSeconds: number | null;
createdBy: string | null;
createdAt: string;
}
export interface WallDisplayInput {
name: string;
slug?: string;
pages: string[];
rotateSeconds: number | null;
}
export interface ShareLink { export interface ShareLink {
id: number; id: number;
label: string; label: string;
tokenPrefix: string; tokenPrefix: string;
kind: ShareLinkKind; kind: ShareLinkKind;
/** For a wall: the named display it opens; null is the whole board. */
displayId: number | null;
/** A status page's own heading and message. */ /** A status page's own heading and message. */
title: string | null; title: string | null;
message: string | null; message: string | null;
@@ -90,6 +110,8 @@ export interface WallGroup {
} }
export interface PublicWall { export interface PublicWall {
/** The named display this link opens, if any. */
displayConfig?: { name: string; pages: string[]; rotateSeconds: number | null } | null;
detail: ShareLinkDetail; detail: ShareLinkDetail;
level: "ok" | "warning" | "critical" | "unsure"; level: "ok" | "warning" | "critical" | "unsure";
environment: string | null; environment: string | null;
@@ -4059,10 +4081,16 @@ export const api = {
}, },
shareLinks: { shareLinks: {
list: () => request<{ links: ShareLink[] }>("/api/share-links"), list: () => request<{ links: ShareLink[] }>("/api/share-links"),
create: (data: { label: string; detail?: ShareLinkDetail; kind?: ShareLinkKind; title?: string; message?: string; expiresInDays: number | null }) => create: (data: { label: string; detail?: ShareLinkDetail; kind?: ShareLinkKind; displayId?: number | null; title?: string; message?: string; expiresInDays: number | null }) =>
request<{ link: ShareLink; token: string; path: string }>("/api/share-links", { method: "POST", body: JSON.stringify(data) }), 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" }), remove: (id: number) => request<void>(`/api/share-links/${id}`, { method: "DELETE" }),
}, },
wallDisplays: {
list: () => request<{ displays: WallDisplay[] }>("/api/wall-displays"),
create: (data: WallDisplayInput) => request<{ display: WallDisplay }>("/api/wall-displays", { method: "POST", body: JSON.stringify(data) }),
update: (id: number, data: WallDisplayInput) => request<{ display: WallDisplay }>(`/api/wall-displays/${id}`, { method: "PUT", body: JSON.stringify(data) }),
remove: (id: number) => request<void>(`/api/wall-displays/${id}`, { method: "DELETE" }),
},
statusPages: { statusPages: {
get: (linkId: number) => request<{ title: string; message: string; items: StatusPageItem[]; maxItems: number }>("/api/share-links/" + linkId + "/status"), get: (linkId: number) => request<{ title: string; message: string; items: StatusPageItem[]; maxItems: number }>("/api/share-links/" + linkId + "/status"),
choices: () => request<{ servers: { id: number; name: string }[]; integrations: { id: number; name: string; type: string }[] }>("/api/share-links/status-choices"), choices: () => request<{ servers: { id: number; name: string }[]; integrations: { id: number; name: string; type: string }[] }>("/api/share-links/status-choices"),
+196
View File
@@ -0,0 +1,196 @@
import { useState } from "react";
import { api, type WallDisplay } from "../api/client";
import { t } from "../i18n";
import { confirmDialog } from "../utils/dialogs";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
import { displayPageChoices, ROTATE_CHOICES } from "../utils/wallPages";
import CopyButton from "./CopyButton";
import { ErrorNotice } from "./Notice";
interface Draft {
id: number | null;
name: string;
slug: string;
pages: string[];
rotateSeconds: number | null;
}
const EMPTY: Draft = { id: null, name: "", slug: "", pages: [], rotateSeconds: null };
/** What a display shows, in words: "every page", or the pages it lists. */
function pagesWords(pages: string[]): string {
if (pages.length === 0) return t("Every page the board has");
const label = new Map(displayPageChoices().map((c) => [c.id, c.label]));
return pages.map((p) => t(label.get(p) ?? p)).join(" → ");
}
/**
* Named wall displays: "Hall TV", "Office monitor". Each is a choice of which pages the board rotates through and how fast, with an address of its own (/wall/hall-tv) to bookmark on that screen — and a
* share link can open one too. Administrators make and change them; they only choose among the pages the board has, they do not change what it shows.
*/
export default function WallDisplays({ displays, onChanged }: { displays: WallDisplay[] | null; onChanged: () => void }) {
const [draft, setDraft] = useState<Draft | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const choices = displayPageChoices();
function edit(d: WallDisplay) {
setDraft({ id: d.id, name: d.name, slug: d.slug, pages: d.pages, rotateSeconds: d.rotateSeconds });
setError(null);
}
/** The pages in the order of the board, whichever order they were ticked in. */
function toggle(id: string) {
if (!draft) return;
const on = draft.pages.includes(id);
const next = on ? draft.pages.filter((p) => p !== id) : [...draft.pages, id];
setDraft({ ...draft, pages: choices.map((c) => c.id).filter((c) => next.includes(c)) });
}
async function save(e: React.FormEvent) {
e.preventDefault();
if (!draft) return;
setBusy(true);
setError(null);
try {
const input = { name: draft.name.trim(), slug: draft.slug.trim() || undefined, pages: draft.pages, rotateSeconds: draft.rotateSeconds };
if (draft.id === null) await api.wallDisplays.create(input);
else await api.wallDisplays.update(draft.id, input);
toast.success(draft.id === null ? t("Added {name}.", { name: draft.name.trim() }) : t("Saved."));
setDraft(null);
onChanged();
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
async function remove(d: WallDisplay) {
if (!(await confirmDialog({ title: t("Remove a wall display"), message: t("Remove \"{name}\"? A screen using its address shows the whole board instead, and a share link that opened it opens the whole board.", { name: d.name }), confirmLabel: t("Remove"), danger: true }))) return;
try {
await api.wallDisplays.remove(d.id);
toast.success(t("Removed {name}.", { name: d.name }));
onChanged();
} catch (err) {
setError(readableError(err));
}
}
return (
<div className="card mb-4">
<div className="card-header">
<h3 className="card-title">{t("Wall displays")}</h3>
{!draft && (
<div className="card-actions">
<button type="button" className="btn btn-primary btn-sm" onClick={() => setDraft({ ...EMPTY })}>
{t("Add a display")}
</button>
</div>
)}
</div>
<div className="card-body">
<p className="text-secondary">
{t("A display is a screen with its own address — the hall TV, the office monitor — that shows the pages you choose, in your order, at the speed you choose. Open it from the user menu's Wall display, or bookmark its address on the screen it is for. It chooses among the pages the board has; what the board shows does not change.")}
</p>
<ErrorNotice error={error} />
{draft && (
<form onSubmit={save} className="row g-3 mb-3">
<div className="col-md-5">
<label className="form-label" htmlFor="wd-name">
{t("Name")}
</label>
<input id="wd-name" className="form-control" required maxLength={60} placeholder={t("e.g. Hall TV")} value={draft.name} onChange={(e) => setDraft({ ...draft, name: e.target.value })} />
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="wd-slug">
{t("Address")} <span className="text-secondary">{t("(optional)")}</span>
</label>
<div className="input-group">
<span className="input-group-text">/wall/</span>
<input id="wd-slug" className="form-control" maxLength={40} placeholder={t("made from the name")} pattern="[a-z0-9]+(-[a-z0-9]+)*" title={t("Lower case letters, digits and single hyphens")} value={draft.slug} onChange={(e) => setDraft({ ...draft, slug: e.target.value })} />
</div>
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="wd-rotate">
{t("Rotate every")}
</label>
<select id="wd-rotate" className="form-select" value={draft.rotateSeconds ?? ""} onChange={(e) => setDraft({ ...draft, rotateSeconds: e.target.value === "" ? null : Number(e.target.value) })}>
<option value="">{t("Not set (the address or this screen decides)")}</option>
{ROTATE_CHOICES.map((s) => (
<option key={s} value={s}>
{t("{n} seconds", { n: s })}
</option>
))}
</select>
</div>
<div className="col-12">
<div className="form-label">{t("Pages it shows, in the order of the board")}</div>
<div className="d-flex flex-wrap gap-3">
{choices.map((c) => (
<label key={c.id} className="form-check mb-0">
<input type="checkbox" className="form-check-input" checked={draft.pages.includes(c.id)} onChange={() => toggle(c.id)} />
<span className="form-check-label">{t(c.label)}</span>
</label>
))}
</div>
<div className="form-hint text-secondary small mt-1">
{t("Tick none for every page the board has. A page only appears while it has something to show: “Needs attention” only while something does, a group only if you have an integration in it.")}
</div>
</div>
<div className="col-12 d-flex gap-2">
<button type="submit" className="btn btn-primary" disabled={busy || draft.name.trim() === ""}>
{busy ? t("Saving…") : t("Save")}
</button>
<button type="button" className="btn" onClick={() => setDraft(null)}>
{t("Cancel")}
</button>
</div>
</form>
)}
{displays?.length === 0 && !draft && <div className="text-secondary">{t("No displays yet. Without one, the wall shows every page.")}</div>}
{displays && displays.length > 0 && (
<div className="table-responsive">
<table className="table table-vcenter mb-0">
<thead>
<tr>
<th>{t("Name")}</th>
<th>{t("Address")}</th>
<th>{t("Pages")}</th>
<th>{t("Rotates")}</th>
<th className="w-1">{t("Actions")}</th>
</tr>
</thead>
<tbody>
{displays.map((d) => (
<tr key={d.id}>
<td className="fw-bold">{d.name}</td>
<td>
<a href={`/wall/${d.slug}`} target="_blank" rel="noreferrer">
/wall/{d.slug}
</a>{" "}
<CopyButton text={`${window.location.origin}/wall/${d.slug}`} />
</td>
<td className="text-secondary">{pagesWords(d.pages)}</td>
<td className="text-secondary">{d.rotateSeconds === null ? t("not set") : t("every {n} s", { n: d.rotateSeconds })}</td>
<td>
<div className="btn-list flex-nowrap">
<button type="button" className="btn btn-sm" onClick={() => edit(d)}>
{t("Edit")}
</button>
<button type="button" className="btn btn-sm btn-outline-danger" onClick={() => void remove(d)}>
{t("Remove")}
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
);
}
+7 -3
View File
@@ -2,7 +2,7 @@ import { useEffect, useState, type ReactNode } from "react";
import type { WallGroup, WallTile } from "../api/client"; import type { WallGroup, WallTile } from "../api/client";
import { formatDate, formatTime } from "../utils/date"; import { formatDate, formatTime } from "../utils/date";
import { formatRemaining } from "../utils/duration"; import { formatRemaining } from "../utils/duration";
import { groupMembers, pageOrOverview, ROTATE_CHOICES, stepPage, wallPages } from "../utils/wallPages"; import { applyDisplay, groupMembers, pageOrOverview, ROTATE_CHOICES, stepPage, wallPages } from "../utils/wallPages";
import { t } from "../i18n"; import { t } from "../i18n";
export const REFRESH_MS = 30_000; export const REFRESH_MS = 30_000;
@@ -115,10 +115,13 @@ export default function WallView({
idle, idle,
footerActions, footerActions,
rotation, rotation,
display,
}: { }: {
data: WallData; data: WallData;
idle: boolean; idle: boolean;
footerActions: ReactNode; footerActions: ReactNode;
/** A named display: its name (shown in the footer) and which pages it rotates through, in order; none listed is every page. */
display?: { name: string; pages: string[] } | null;
/** How the pages rotate (seconds each, null for the overview alone) and how to change it; absent on a board that does not rotate. */ /** How the pages rotate (seconds each, null for the overview alone) and how to change it; absent on a board that does not rotate. */
rotation?: { seconds: number | null; onChange: (seconds: number | null) => void }; rotation?: { seconds: number | null; onChange: (seconds: number | null) => void };
}) { }) {
@@ -127,7 +130,7 @@ export default function WallView({
// The pages: the overview, what needs attention (while something does), and one for each group of integrations. // The pages: the overview, what needs attention (while something does), and one for each group of integrations.
const rotating = !!rotation && rotation.seconds !== null; const rotating = !!rotation && rotation.seconds !== null;
const pages = wallPages(data); const pages = applyDisplay(wallPages(data), display?.pages ?? []);
const pagesKey = pages.map((p) => p.id).join(","); const pagesKey = pages.map((p) => p.id).join(",");
const [pageId, setPageId] = useState("overview"); const [pageId, setPageId] = useState("overview");
const [paused, setPaused] = useState(false); const [paused, setPaused] = useState(false);
@@ -287,6 +290,7 @@ export default function WallView({
<footer className="wall-footer"> <footer className="wall-footer">
<span> <span>
{display?.name && <strong>{display.name} · </strong>}
{data.updatedAt ? `Updated ${formatTime(data.updatedAt)}` : "Loading…"} · refreshes every {REFRESH_MS / 1000} s {data.updatedAt ? `Updated ${formatTime(data.updatedAt)}` : "Loading…"} · refreshes every {REFRESH_MS / 1000} s
{rotating && pages.length > 1 && ( {rotating && pages.length > 1 && (
<span className="wall-pager" aria-label={`Page ${pages.findIndex((p) => p.id === page.id) + 1} of ${pages.length}: ${page.label}`}> <span className="wall-pager" aria-label={`Page ${pages.findIndex((p) => p.id === page.id) + 1} of ${pages.length}: ${page.label}`}>
@@ -310,7 +314,7 @@ export default function WallView({
value={rotation.seconds === null ? "off" : String(rotation.seconds)} value={rotation.seconds === null ? "off" : String(rotation.seconds)}
onChange={(e) => { onChange={(e) => {
setPaused(false); setPaused(false);
setPageId("overview"); setPageId(pages[0].id);
rotation.onChange(e.target.value === "off" ? null : Number(e.target.value)); rotation.onChange(e.target.value === "off" ? null : Number(e.target.value));
}} }}
> >
+3 -3
View File
@@ -14,11 +14,11 @@ function stored(): string | null {
/** /**
* How the wall display rotates: how many seconds each page stays, or null for the overview alone. It lives in the address (`?rotate=30`), * How the wall display rotates: how many seconds each page stays, or null for the overview alone. It lives in the address (`?rotate=30`),
* so a TV's bookmark carries it, and this browser remembers the last choice made on the board itself. * so a TV's bookmark carries it, and this browser remembers the last choice made on the board itself. A named display may say how fast too (`configured`); the address still wins over it.
*/ */
export function useWallRotation() { export function useWallRotation(configured: number | null = null) {
const [params, setParams] = useSearchParams(); const [params, setParams] = useSearchParams();
const seconds = rotateSeconds(params.get("rotate"), stored()); const seconds = rotateSeconds(params.get("rotate"), stored(), configured);
const setSeconds = useCallback( const setSeconds = useCallback(
(next: number | null) => { (next: number | null) => {
try { try {
+31
View File
@@ -24,6 +24,7 @@ export const sv: Record<string, string> = {
"{n} mo ago": "för {n} mån sedan", "{n} mo ago": "för {n} mån sedan",
"{n} more acknowledged": "{n} till kvitterade", "{n} more acknowledged": "{n} till kvitterade",
"{n} more explained by something that is down": "{n} till förklaras av något som ligger nere", "{n} more explained by something that is down": "{n} till förklaras av något som ligger nere",
"{n} seconds": "{n} sekunder",
"{n} silenced by maintenance": "{n} tystade av underhåll", "{n} silenced by maintenance": "{n} tystade av underhåll",
"{n} so far": "{n} hittills", "{n} so far": "{n} hittills",
"{n} stretch with a failure": "{n} period med ett fel", "{n} stretch with a failure": "{n} period med ett fel",
@@ -53,6 +54,7 @@ export const sv: Record<string, string> = {
"7 days": "7 dagar", "7 days": "7 dagar",
"8 hours": "8 timmar", "8 hours": "8 timmar",
"90 days": "90 dagar", "90 days": "90 dagar",
"A display is a screen with its own address — the hall TV, the office monitor — that shows the pages you choose, in your order, at the speed you choose. Open it from the user menu's Wall display, or bookmark its address on the screen it is for. It chooses among the pages the board has; what the board shows does not change.": "En display är en skärm med en egen adress — hallens TV, kontorets skärm — som visar de sidor du väljer, i den ordning du väljer, i den takt du väljer. Öppna den från Väggskärm i användarmenyn, eller bokmärk dess adress på skärmen den är till för. Den väljer bland de sidor tavlan har; vad tavlan visar ändras inte.",
"A full-screen status board for a spare monitor or tablet": "En helskärmsöversikt för en ledig skärm eller surfplatta", "A full-screen status board for a spare monitor or tablet": "En helskärmsöversikt för en ledig skärm eller surfplatta",
"A job about this": "Ett jobb om det här", "A job about this": "Ett jobb om det här",
"A job to add": "Ett jobb att lägga till", "A job to add": "Ett jobb att lägga till",
@@ -70,6 +72,7 @@ export const sv: Record<string, string> = {
"Actions": "Åtgärder", "Actions": "Åtgärder",
"Active": "Aktiv", "Active": "Aktiv",
"Add {name} to favourites": "Lägg till {name} i favoriter", "Add {name} to favourites": "Lägg till {name} i favoriter",
"Add a display": "Lägg till en display",
"Add a job": "Lägg till ett jobb", "Add a job": "Lägg till ett jobb",
"Add a job about this…": "Lägg till ett jobb om det här…", "Add a job about this…": "Lägg till ett jobb om det här…",
"Add a job above, and give it a day if it has one.": "Lägg till ett jobb ovan och ge det en dag om det har en.", "Add a job above, and give it a day if it has one.": "Lägg till ett jobb ovan och ge det en dag om det har en.",
@@ -89,8 +92,10 @@ export const sv: Record<string, string> = {
"Add server": "Lägg till server", "Add server": "Lägg till server",
"Add task": "Lägg till uppgift", "Add task": "Lägg till uppgift",
"Add:": "Lägg till:", "Add:": "Lägg till:",
"Added {name}.": "{name} är tillagd.",
"Added.": "Tillagd.", "Added.": "Tillagd.",
"Adding…": "Lägger till…", "Adding…": "Lägger till…",
"Address": "Adress",
"Address aliases": "Adressalias", "Address aliases": "Adressalias",
"Address in Uptime Kuma": "Adress i Uptime Kuma", "Address in Uptime Kuma": "Adress i Uptime Kuma",
"Address to scan": "Adress att skanna", "Address to scan": "Adress att skanna",
@@ -210,6 +215,7 @@ export const sv: Record<string, string> = {
"Disabled": "Avstängd", "Disabled": "Avstängd",
"Disk (allocated)": "Disk (tilldelad)", "Disk (allocated)": "Disk (tilldelad)",
"Dismiss": "Avfärda", "Dismiss": "Avfärda",
"Display": "Display",
"DNS answers": "DNS-svar", "DNS answers": "DNS-svar",
"DNS providers": "DNS-leverantörer", "DNS providers": "DNS-leverantörer",
"DNS record change notifications.": "Notiser om ändrade DNS-poster.", "DNS record change notifications.": "Notiser om ändrade DNS-poster.",
@@ -219,6 +225,7 @@ export const sv: Record<string, string> = {
"Done": "Klar", "Done": "Klar",
"Download clients": "Nedladdningsklienter", "Download clients": "Nedladdningsklienter",
"Due day (optional)": "Förfallodag (valfritt)", "Due day (optional)": "Förfallodag (valfritt)",
"e.g. Hall TV": "t.ex. Hallens TV",
"Each connected system gets its own page — open it from here or from the sidebar, in the group shown. Add and manage credentials here.": "Varje anslutet system får en egen sida — öppna den härifrån eller från sidomenyn, i gruppen som visas. Lägg till och hantera inloggningsuppgifter här.", "Each connected system gets its own page — open it from here or from the sidebar, in the group shown. Add and manage credentials here.": "Varje anslutet system får en egen sida — öppna den härifrån eller från sidomenyn, i gruppen som visas. Lägg till och hantera inloggningsuppgifter här.",
"Each server may be under maintenance for": "Varje server får vara under underhåll i högst", "Each server may be under maintenance for": "Varje server får vara under underhåll i högst",
"Edit": "Redigera", "Edit": "Redigera",
@@ -232,14 +239,19 @@ export const sv: Record<string, string> = {
"Ends": "Slutar", "Ends": "Slutar",
"Ends in": "Slutar om", "Ends in": "Slutar om",
"Enter a value": "Ange ett värde", "Enter a value": "Ange ett värde",
"every {n} s": "var {n} s",
"Every alert is live. Start a window above before you work on something, so it doesn't raise alarms while you do.": "Alla larm är aktiva. Starta ett fönster ovan innan du jobbar med något, så att det inte larmar medan du gör det.", "Every alert is live. Start a window above before you work on something, so it doesn't raise alarms while you do.": "Alla larm är aktiva. Starta ett fönster ovan innan du jobbar med något, så att det inte larmar medan du gör det.",
"Every container is on its latest image, as far as the last check could tell.": "Alla containrar kör sin senaste avbild, så vitt den senaste kontrollen kunde se.", "Every container is on its latest image, as far as the last check could tell.": "Alla containrar kör sin senaste avbild, så vitt den senaste kontrollen kunde se.",
"Every page the board has": "Alla sidor tavlan har",
"Every server": "Alla servrar", "Every server": "Alla servrar",
"Every time a recurring maintenance happens": "Varje gång ett återkommande underhåll sker", "Every time a recurring maintenance happens": "Varje gång ett återkommande underhåll sker",
"Every Uptime Kuma integration is disabled — enable one under Integrations.": "Alla Uptime Kuma-integrationer är avstängda — slå på en under Integrationer.", "Every Uptime Kuma integration is disabled — enable one under Integrations.": "Alla Uptime Kuma-integrationer är avstängda — slå på en under Integrationer.",
"Everything": "Allt",
"Everything — every page": "Allt — alla sidor",
"Everything — every server, integration, network device and DNS provider": "Allt — alla servrar, integrationer, nätverksenheter och DNS-leverantörer", "Everything — every server, integration, network device and DNS provider": "Allt — alla servrar, integrationer, nätverksenheter och DNS-leverantörer",
"Everything about this server in the change log": "Allt om den här servern i ändringsloggen", "Everything about this server in the change log": "Allt om den här servern i ändringsloggen",
"Everything coming up": "Allt som är på gång", "Everything coming up": "Allt som är på gång",
"Exit (Esc)": "Avsluta (Esc)",
"Expired:": "Utgånget:", "Expired:": "Utgånget:",
"Expiring:": "Löper ut:", "Expiring:": "Löper ut:",
"Export CSV": "Exportera CSV", "Export CSV": "Exportera CSV",
@@ -255,6 +267,7 @@ export const sv: Record<string, string> = {
"Fold the cards you do not need and put the others in the order you like — for every server": "Fäll ihop korten du inte behöver och lägg de andra i den ordning du vill — för alla servrar", "Fold the cards you do not need and put the others in the order you like — for every server": "Fäll ihop korten du inte behöver och lägg de andra i den ordning du vill — för alla servrar",
"Follow Settings again": "Följ Inställningar igen", "Follow Settings again": "Följ Inställningar igen",
"From now": "Från nu", "From now": "Från nu",
"Full screen": "Helskärm",
"Further ahead": "Längre fram", "Further ahead": "Längre fram",
"Game servers": "Spelservrar", "Game servers": "Spelservrar",
"Generator": "Generator", "Generator": "Generator",
@@ -330,7 +343,9 @@ export const sv: Record<string, string> = {
"Load:": "Belastning:", "Load:": "Belastning:",
"Loading…": "Läser in…", "Loading…": "Läser in…",
"Longest wait": "Längsta väntan", "Longest wait": "Längsta väntan",
"Lower case letters, digits and single hyphens": "Små bokstäver, siffror och enstaka bindestreck",
"Lowercase letters, numbers and - _ . : / — up to 12 tags per server.": "Små bokstäver, siffror och - _ . : / — upp till 12 taggar per server.", "Lowercase letters, numbers and - _ . : / — up to 12 tags per server.": "Små bokstäver, siffror och - _ . : / — upp till 12 taggar per server.",
"made from the name": "görs av namnet",
"Main menu": "Huvudmeny", "Main menu": "Huvudmeny",
"Maintenance": "Underhåll", "Maintenance": "Underhåll",
"Maintenance — alerts silenced for": "Underhåll — larm tystade för", "Maintenance — alerts silenced for": "Underhåll — larm tystade för",
@@ -377,6 +392,8 @@ export const sv: Record<string, string> = {
"No admin links added yet — e.g. Dockge, Webmin, or Cockpit for this server.": "Inga adminlänkar tillagda än — till exempel Dockge, Webmin eller Cockpit för den här servern.", "No admin links added yet — e.g. Dockge, Webmin, or Cockpit for this server.": "Inga adminlänkar tillagda än — till exempel Dockge, Webmin eller Cockpit för den här servern.",
"No agent data": "Inga agentdata", "No agent data": "Inga agentdata",
"No data": "Inga data", "No data": "Inga data",
"No display called “{slug}” — showing everything": "Ingen display heter ”{slug}” — visar allt",
"No displays yet. Without one, the wall shows every page.": "Inga displayer än. Utan någon visar väggskärmen alla sidor.",
"No enabled Proxmox integrations configured yet.": "Inga påslagna Proxmox-integrationer har konfigurerats än.", "No enabled Proxmox integrations configured yet.": "Inga påslagna Proxmox-integrationer har konfigurerats än.",
"No expiry dates": "Inga utgångsdatum", "No expiry dates": "Inga utgångsdatum",
"No hardware data yet. Install the agent on this server, or link it to a Proxmox VM/LXC (under Settings).": "Inga hårdvarudata än. Installera agenten på servern, eller koppla den till en Proxmox-VM/LXC (under Inställningar).", "No hardware data yet. Install the agent on this server, or link it to a Proxmox VM/LXC (under Settings).": "Inga hårdvarudata än. Installera agenten på servern, eller koppla den till en Proxmox-VM/LXC (under Inställningar).",
@@ -410,6 +427,8 @@ export const sv: Record<string, string> = {
"not reported": "ej rapporterat", "not reported": "ej rapporterat",
"Not reporting": "Rapporterar inte", "Not reporting": "Rapporterar inte",
"Not scanned yet.": "Inte skannad än.", "Not scanned yet.": "Inte skannad än.",
"not set": "inte satt",
"Not set (the address or this screen decides)": "Inte satt (adressen eller skärmen bestämmer)",
"Not set up yet": "Inte uppsatt än", "Not set up yet": "Inte uppsatt än",
"Not silenced": "Inte tystad", "Not silenced": "Inte tystad",
"Notes": "Anteckningar", "Notes": "Anteckningar",
@@ -458,9 +477,12 @@ export const sv: Record<string, string> = {
"Operating system": "Operativsystem", "Operating system": "Operativsystem",
"Operations": "Drift", "Operations": "Drift",
"OS type": "OS-typ", "OS type": "OS-typ",
"Other": "Övrigt",
"Others sign in with Authentik and appear under Users; you decide their role.": "Andra loggar in med Authentik och dyker upp under Användare; du bestämmer deras roll.", "Others sign in with Authentik and appear under Users; you decide their role.": "Andra loggar in med Authentik och dyker upp under Användare; du bestämmer deras roll.",
"Overview": "Översikt", "Overview": "Översikt",
"Page {page} of {pages} ({total} total)": "Sida {page} av {pages} ({total} totalt)", "Page {page} of {pages} ({total} total)": "Sida {page} av {pages} ({total} totalt)",
"Pages": "Sidor",
"Pages it shows, in the order of the board": "Sidor den visar, i tavlans ordning",
"Patch plans": "Patchplaner", "Patch plans": "Patchplaner",
"Pick all {n} shown": "Markera alla {n} som visas", "Pick all {n} shown": "Markera alla {n} som visas",
"Pick the servers to change together, then choose what to do from the bar at the foot of the page.": "Markera de servrar som ska ändras tillsammans och välj sedan vad som ska göras i fältet längst ned på sidan.", "Pick the servers to change together, then choose what to do from the bar at the foot of the page.": "Markera de servrar som ska ändras tillsammans och välj sedan vad som ska göras i fältet längst ned på sidan.",
@@ -489,11 +511,14 @@ export const sv: Record<string, string> = {
"Refresh": "Uppdatera", "Refresh": "Uppdatera",
"Refreshing…": "Uppdaterar…", "Refreshing…": "Uppdaterar…",
"Remove": "Ta bort", "Remove": "Ta bort",
"Remove \"{name}\"? A screen using its address shows the whole board instead, and a share link that opened it opens the whole board.": "Ta bort ”{name}”? En skärm som använder dess adress visar hela tavlan i stället, och en delningslänk som öppnade den öppnar hela tavlan.",
"Remove {name} from favourites": "Ta bort {name} från favoriter", "Remove {name} from favourites": "Ta bort {name} från favoriter",
"Remove a wall display": "Ta bort en väggdisplay",
"Remove acknowledgement": "Ta bort kvittering", "Remove acknowledgement": "Ta bort kvittering",
"Remove it": "Ta bort den", "Remove it": "Ta bort den",
"Remove recurring maintenance": "Ta bort återkommande underhåll", "Remove recurring maintenance": "Ta bort återkommande underhåll",
"Remove server": "Ta bort server", "Remove server": "Ta bort server",
"Removed {name}.": "{name} är borttagen.",
"Reported": "Rapporterad", "Reported": "Rapporterad",
"Reported by the agent as of": "Rapporterat av agenten per", "Reported by the agent as of": "Rapporterat av agenten per",
"Reporting": "Rapporterar", "Reporting": "Rapporterar",
@@ -510,7 +535,9 @@ export const sv: Record<string, string> = {
"Restart…": "Starta om…", "Restart…": "Starta om…",
"restarted": "omstartad", "restarted": "omstartad",
"Roomy": "Luftig", "Roomy": "Luftig",
"Rotate every": "Rotera var",
"Rotate token": "Byt nyckel", "Rotate token": "Byt nyckel",
"Rotates": "Roterar",
"Rows per page": "Rader per sida", "Rows per page": "Rader per sida",
"Run #{id} in Semaphore — the playbook's output is there.": "Körning #{id} i Semaphore — playbookens utdata finns där.", "Run #{id} in Semaphore — the playbook's output is there.": "Körning #{id} i Semaphore — playbookens utdata finns där.",
"Run a playbook": "Kör en playbook", "Run a playbook": "Kör en playbook",
@@ -623,6 +650,7 @@ export const sv: Record<string, string> = {
"This server's agent hasn't reported updates — it may be an older agent, or its package manager isn't one it can ask.": "Serverns agent har inte rapporterat uppdateringar — det kan vara en äldre agent, eller så är dess pakethanterare ingen den kan fråga.", "This server's agent hasn't reported updates — it may be an older agent, or its package manager isn't one it can ask.": "Serverns agent har inte rapporterat uppdateringar — det kan vara en äldre agent, eller så är dess pakethanterare ingen den kan fråga.",
"This token is only shown once — copy it now.": "Nyckeln visas bara en gång — kopiera den nu.", "This token is only shown once — copy it now.": "Nyckeln visas bara en gång — kopiera den nu.",
"This week": "Den här veckan", "This week": "Den här veckan",
"Tick none for every page the board has. A page only appears while it has something to show: “Needs attention” only while something does, a group only if you have an integration in it.": "Kryssa inget för alla sidor tavlan har. En sida visas bara när den har något att visa: ”Behöver uppmärksamhet” bara när något gör det, en grupp bara om du har en integration i den.",
"Time in total": "Tid totalt", "Time in total": "Tid totalt",
"Time range": "Tidsperiod", "Time range": "Tidsperiod",
"Title": "Titel", "Title": "Titel",
@@ -663,6 +691,7 @@ export const sv: Record<string, string> = {
"Wake": "Väck", "Wake": "Väck",
"Wake now": "Väck nu", "Wake now": "Väck nu",
"Wall display": "Väggskärm", "Wall display": "Väggskärm",
"Wall displays": "Väggdisplayer",
"Warning": "Varning", "Warning": "Varning",
"Welcome back,": "Välkommen tillbaka,", "Welcome back,": "Välkommen tillbaka,",
"What are you working on?": "Vad jobbar du med?", "What are you working on?": "Vad jobbar du med?",
@@ -678,7 +707,9 @@ export const sv: Record<string, string> = {
"When you acknowledge an alert, are handed one, put something under maintenance or start an update run, it is listed here until it is done.": "När du kvitterar ett larm, får ett tilldelat, sätter något under underhåll eller startar en uppdateringskörning listas det här tills det är klart.", "When you acknowledge an alert, are handed one, put something under maintenance or start an update run, it is listed here until it is done.": "När du kvitterar ett larm, får ett tilldelat, sätter något under underhåll eller startar en uppdateringskörning listas det här tills det är klart.",
"Where": "Var", "Where": "Var",
"Whether somebody is on it": "Om någon jobbar med det", "Whether somebody is on it": "Om någon jobbar med det",
"Which display": "Vilken display",
"Which servers": "Vilka servrar", "Which servers": "Vilka servrar",
"Which wall display": "Vilken väggdisplay",
"Whose jobs": "Vems jobb", "Whose jobs": "Vems jobb",
"Widen the sidebar": "Bredda sidomenyn", "Widen the sidebar": "Bredda sidomenyn",
"Widen the sidebar ([)": "Bredda sidomenyn ([)", "Widen the sidebar ([)": "Bredda sidomenyn ([)",
+6 -1
View File
@@ -4,6 +4,7 @@ import { api, type PublicWall } from "../api/client";
import WallView, { REFRESH_MS, wallHeadline, type WallData } from "../components/WallView"; import WallView, { REFRESH_MS, wallHeadline, type WallData } from "../components/WallView";
import { setDateTimeSettings } from "../utils/date"; import { setDateTimeSettings } from "../utils/date";
import { useWallRotation } from "../hooks/useWallRotation"; import { useWallRotation } from "../hooks/useWallRotation";
import { t } from "../i18n";
/** /**
* The wall display behind a share link: the same board, read-only and without signing in. The address carries the secret, and the * The wall display behind a share link: the same board, read-only and without signing in. The address carries the secret, and the
@@ -16,7 +17,9 @@ export default function SharedWall() {
const [state, setState] = useState<"loading" | "ok" | "dead" | "unreachable">("loading"); const [state, setState] = useState<"loading" | "ok" | "dead" | "unreachable">("loading");
const [updatedAt, setUpdatedAt] = useState<Date | null>(null); const [updatedAt, setUpdatedAt] = useState<Date | null>(null);
const [idle, setIdle] = useState(false); const [idle, setIdle] = useState(false);
const rotation = useWallRotation(); // The named display this link opens, once the board has been read: its pages and its speed.
const [displayConfig, setDisplayConfig] = useState<PublicWall["displayConfig"]>(null);
const rotation = useWallRotation(displayConfig?.rotateSeconds ?? null);
useEffect(() => { useEffect(() => {
let alive = true; let alive = true;
@@ -28,6 +31,7 @@ export default function SharedWall() {
if (!alive) return; if (!alive) return;
setDateTimeSettings({ dateFormat: w.display.dateFormat as "ymd" | "dmy" | "mdy", timeFormat: w.display.timeFormat as "24h" | "12h" }); setDateTimeSettings({ dateFormat: w.display.dateFormat as "ymd" | "dmy" | "mdy", timeFormat: w.display.timeFormat as "24h" | "12h" });
setWall(w); setWall(w);
setDisplayConfig(w.displayConfig ?? null);
setUpdatedAt(new Date()); setUpdatedAt(new Date());
setState("ok"); setState("ok");
}) })
@@ -103,6 +107,7 @@ export default function SharedWall() {
<WallView <WallView
data={data} data={data}
idle={idle} idle={idle}
display={displayConfig ? { name: displayConfig.name, pages: displayConfig.pages } : null}
rotation={{ seconds: rotation.seconds, onChange: rotation.setSeconds }} rotation={{ seconds: rotation.seconds, onChange: rotation.setSeconds }}
footerActions={ footerActions={
<button type="button" className="wall-link" onClick={() => void document.documentElement.requestFullscreen?.().catch(() => {})}> <button type="button" className="wall-link" onClick={() => void document.documentElement.requestFullscreen?.().catch(() => {})}>
+34 -5
View File
@@ -1,10 +1,11 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom"; import { Link, useNavigate, useParams } from "react-router-dom";
import { api, type IntegrationSummary, type MaintenanceWindow, type ServerSummary, type WallGroup, type WallTile } from "../api/client"; import { api, type IntegrationSummary, type MaintenanceWindow, type ServerSummary, type WallDisplay, type WallGroup, type WallTile } from "../api/client";
import { alertBadge, useAlertsReport } from "../hooks/useAlertsReport"; import { alertBadge, useAlertsReport } from "../hooks/useAlertsReport";
import { useEnvironment } from "../utils/environment"; import { useEnvironment } from "../utils/environment";
import { useWallRotation } from "../hooks/useWallRotation"; import { useWallRotation } from "../hooks/useWallRotation";
import WallView, { REFRESH_MS, wallHeadline, type WallData } from "../components/WallView"; import WallView, { REFRESH_MS, wallHeadline, type WallData } from "../components/WallView";
import { t } from "../i18n";
/** /**
* A full-screen status board for a spare monitor or tablet: how things are, in type big enough to read across a room, refreshing * A full-screen status board for a spare monitor or tablet: how things are, in type big enough to read across a room, refreshing
@@ -20,7 +21,17 @@ export default function Wall() {
const [extras, setExtras] = useState<{ tiles: WallTile[]; groups: WallGroup[] } | null>(null); const [extras, setExtras] = useState<{ tiles: WallTile[]; groups: WallGroup[] } | null>(null);
const [updatedAt, setUpdatedAt] = useState<Date | null>(null); const [updatedAt, setUpdatedAt] = useState<Date | null>(null);
const [idle, setIdle] = useState(false); const [idle, setIdle] = useState(false);
const rotation = useWallRotation(); // A named display ("/wall/hall-tv"): which pages it rotates through and how fast. Without one (or while it is being read) the board is the whole board, as it always was.
const { slug } = useParams();
const [displays, setDisplays] = useState<WallDisplay[] | null>(null);
const display = slug ? (displays ?? []).find((d) => d.slug === slug) ?? null : null;
const rotation = useWallRotation(display?.rotateSeconds ?? null);
useEffect(() => {
api.wallDisplays
.list()
.then((res) => setDisplays(res.displays))
.catch(() => setDisplays([]));
}, []);
useEffect(() => { useEffect(() => {
let alive = true; let alive = true;
@@ -93,14 +104,32 @@ export default function Wall() {
<WallView <WallView
data={data} data={data}
idle={idle} idle={idle}
display={display ? { name: display.name, pages: display.pages } : slug && displays !== null ? { name: t("No display called “{slug}” — showing everything", { slug }), pages: [] } : null}
rotation={{ seconds: rotation.seconds, onChange: rotation.setSeconds }} rotation={{ seconds: rotation.seconds, onChange: rotation.setSeconds }}
footerActions={ footerActions={
<> <>
{displays && displays.length > 0 && (
<label className="wall-rotate">
{t("Display")}{" "}
<select
aria-label={t("Which wall display")}
value={slug ?? ""}
onChange={(e) => navigate(e.target.value ? `/wall/${e.target.value}${window.location.search}` : `/wall${window.location.search}`)}
>
<option value="">{t("Everything")}</option>
{displays.map((d) => (
<option key={d.id} value={d.slug}>
{d.name}
</option>
))}
</select>
</label>
)}
<button type="button" className="wall-link" onClick={() => void document.documentElement.requestFullscreen?.().catch(() => {})}> <button type="button" className="wall-link" onClick={() => void document.documentElement.requestFullscreen?.().catch(() => {})}>
Full screen {t("Full screen")}
</button> </button>
<Link to="/" className="wall-link"> <Link to="/" className="wall-link">
Exit (Esc) {t("Exit (Esc)")}
</Link> </Link>
</> </>
} }
+37 -3
View File
@@ -1,5 +1,6 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { api, type ShareLink, type ShareLinkDetail, type ShareLinkKind } from "../../api/client"; import { api, type ShareLink, type ShareLinkDetail, type ShareLinkKind, type WallDisplay } from "../../api/client";
import WallDisplays from "../../components/WallDisplays";
import StatusPageEditor from "../../components/StatusPageEditor"; import StatusPageEditor from "../../components/StatusPageEditor";
import CopyButton from "../../components/CopyButton"; import CopyButton from "../../components/CopyButton";
import TimeAgo from "../../components/TimeAgo"; import TimeAgo from "../../components/TimeAgo";
@@ -28,6 +29,9 @@ const DETAIL_WORDS: Record<ShareLinkDetail, string> = {
export default function ShareSettings() { export default function ShareSettings() {
const [links, setLinks] = useState<ShareLink[] | null>(null); const [links, setLinks] = useState<ShareLink[] | null>(null);
const [displays, setDisplays] = useState<WallDisplay[] | null>(null);
// For a wall link: the named display it opens ("" is the whole board).
const [displayId, setDisplayId] = useState("");
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [label, setLabel] = useState(""); const [label, setLabel] = useState("");
const [detail, setDetail] = useState<ShareLinkDetail>("summary"); const [detail, setDetail] = useState<ShareLinkDetail>("summary");
@@ -46,14 +50,21 @@ export default function ShareSettings() {
.then((res) => setLinks(res.links)) .then((res) => setLinks(res.links))
.catch((err) => setError(readableError(err))); .catch((err) => setError(readableError(err)));
} }
function loadDisplays() {
api.wallDisplays
.list()
.then((res) => setDisplays(res.displays))
.catch(() => setDisplays([]));
}
useEffect(load, []); useEffect(load, []);
useEffect(loadDisplays, []);
async function create(e: React.FormEvent) { async function create(e: React.FormEvent) {
e.preventDefault(); e.preventDefault();
setError(null); setError(null);
setBusy(true); setBusy(true);
try { try {
const res = await api.shareLinks.create(kind === "status" ? { label: label.trim(), kind, title: title.trim() || undefined, message: message.trim() || undefined, expiresInDays: days } : { label: label.trim(), kind, detail, expiresInDays: days }); const res = await api.shareLinks.create(kind === "status" ? { label: label.trim(), kind, title: title.trim() || undefined, message: message.trim() || undefined, expiresInDays: days } : { label: label.trim(), kind, detail, ...(kind === "wall" && displayId ? { displayId: Number(displayId) } : {}), expiresInDays: days });
setCreated({ label: res.link.label, url: window.location.origin + res.path }); setCreated({ label: res.link.label, url: window.location.origin + res.path });
setLabel(""); setLabel("");
setTitle(""); setTitle("");
@@ -90,6 +101,14 @@ export default function ShareSettings() {
</div> </div>
<ErrorNotice error={error} /> <ErrorNotice error={error} />
<WallDisplays
displays={displays}
onChanged={() => {
loadDisplays();
load();
}}
/>
{created && ( {created && (
<div className="card mb-3"> <div className="card mb-3">
<div className="card-header"> <div className="card-header">
@@ -152,6 +171,21 @@ export default function ShareSettings() {
</select> </select>
</div> </div>
)} )}
{kind === "wall" && displays && displays.length > 0 && (
<div className="col-md-4">
<label className="form-label" htmlFor="share-display">
{t("Which display")}
</label>
<select id="share-display" className="form-select" value={displayId} onChange={(e) => setDisplayId(e.target.value)}>
<option value="">{t("Everything — every page")}</option>
{displays.map((d) => (
<option key={d.id} value={d.id}>
{d.name}
</option>
))}
</select>
</div>
)}
{kind === "status" && ( {kind === "status" && (
<> <>
<div className="col-md-6"> <div className="col-md-6">
@@ -221,7 +255,7 @@ export default function ShareSettings() {
<td> <td>
{l.label} <span className="text-secondary small">{l.tokenPrefix}…</span> {l.label} <span className="text-secondary small">{l.tokenPrefix}…</span>
</td> </td>
<td>{l.kind === "status" ? "Status page · " + l.itemCount + (l.itemCount === 1 ? " thing" : " things") : l.kind === "calendar" ? "Calendar · " + (l.detail === "names" ? "with names" : "kinds only") : "Wall · " + DETAIL_WORDS[l.detail].toLowerCase()}</td> <td>{l.kind === "status" ? "Status page · " + l.itemCount + (l.itemCount === 1 ? " thing" : " things") : l.kind === "calendar" ? "Calendar · " + (l.detail === "names" ? "with names" : "kinds only") : "Wall · " + DETAIL_WORDS[l.detail].toLowerCase() + (l.displayId !== null ? " · " + (displays?.find((d) => d.id === l.displayId)?.name ?? "") : "")}</td>
<td className="text-secondary"> <td className="text-secondary">
{l.createdBy ?? "—"}, <TimeAgo value={l.createdAt} fromDb /> {l.createdBy ?? "—"}, <TimeAgo value={l.createdAt} fromDb />
</td> </td>
+18 -2
View File
@@ -40,6 +40,21 @@ export function wallPages(d: WallPagesInput): WallPage[] {
return pages; return pages;
} }
/**
* Pure: the pages a named display rotates through — those it lists, in the order it lists them, that the board has just now (an "alerts" page only exists while something needs attention). A display that
* lists none shows every page the board has, and one whose pages are all gone from the board shows the overview rather than nothing.
*/
export function applyDisplay(pages: WallPage[], wanted: string[]): WallPage[] {
if (wanted.length === 0) return pages;
const chosen = [...new Set(wanted)].map((id) => pages.find((p) => p.id === id)).filter((p): p is WallPage => !!p);
return chosen.length > 0 ? chosen : pages.slice(0, 1);
}
/** The page ids a display may be given, in the order of the board, and what each is called: the overview, what needs attention, and a group of integrations each. */
export function displayPageChoices(): { id: string; label: string }[] {
return [{ id: "overview", label: "Overview" }, { id: "alerts", label: "Needs attention" }, ...[...TYPE_GROUPS.map((g) => ({ id: `group:${g.id}`, label: g.label })), { id: "group:other", label: "Other" }]];
}
/** Pure: the page `step` places on from the current one (wrapping round); a page that is gone (its alerts cleared) sends it to the overview. */ /** Pure: the page `step` places on from the current one (wrapping round); a page that is gone (its alerts cleared) sends it to the overview. */
export function stepPage(pages: WallPage[], currentId: string, step: number): WallPage { export function stepPage(pages: WallPage[], currentId: string, step: number): WallPage {
const at = pages.findIndex((p) => p.id === currentId); const at = pages.findIndex((p) => p.id === currentId);
@@ -54,9 +69,9 @@ export function pageOrOverview(pages: WallPage[], currentId: string): WallPage {
/** /**
* Pure: how long each page stays, in seconds, or null for no rotation. The address wins (`?rotate=45`; `?rotate=on` for the default; `?rotate=off`), * Pure: how long each page stays, in seconds, or null for no rotation. The address wins (`?rotate=45`; `?rotate=on` for the default; `?rotate=off`),
* then what this browser last chose, else no rotation. A number out of range is brought into it; anything else means off. * then what the named display says (when it says), then what this browser last chose, else no rotation. A number out of range is brought into it; anything else means off.
*/ */
export function rotateSeconds(param: string | null, stored: string | null): number | null { export function rotateSeconds(param: string | null, stored: string | null, configured: number | null = null): number | null {
const read = (v: string | null): number | null | undefined => { const read = (v: string | null): number | null | undefined => {
if (v === null || v === "") return undefined; if (v === null || v === "") return undefined;
const t = v.trim().toLowerCase(); const t = v.trim().toLowerCase();
@@ -67,6 +82,7 @@ export function rotateSeconds(param: string | null, stored: string | null): numb
}; };
const fromAddress = read(param); const fromAddress = read(param);
if (fromAddress !== undefined) return fromAddress; if (fromAddress !== undefined) return fromAddress;
if (configured !== null) return Math.min(ROTATE_MAX, Math.max(ROTATE_MIN, configured));
return read(stored) ?? null; return read(stored) ?? null;
} }