Files
Homelab-manager/web/src/components/DependencyMap.tsx
T
bobbanandClaude Sonnet 5.5 6e39430a1f Swedish interface: labels and short texts across every page
About 1,600 more headings, buttons, table columns, status words, placeholders and short messages are translated. Tables of words built when the app loads are now read when they are drawn, so they follow the language, and a test fails if text is translated at load time.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:16:39 +01:00

204 lines
9.3 KiB
TypeScript

import { useEffect, useMemo, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { api, type DependencyGraph, type DependencyGraphNode } from "../api/client";
import { ErrorNotice } from "./Notice";
import { PageSkeleton } from "./Skeleton";
import { readableError } from "../utils/errors";
import MapLinesToggle, { useMapLineStyle } from "../components/MapLinesToggle";
import { edgePath } from "../utils/mapLines";
import { t } from "../i18n";
const NODE_W = 200;
const NODE_H = 46;
const GAP_Y = 12;
const COL_GAP = 120;
const STATUS_SYMBOL: Record<DependencyGraphNode["status"], string> = { ok: "✓", bad: "✕", warn: "▲", unknown: "·" };
const STATUS_WORD: Record<DependencyGraphNode["status"], string> = { ok: "working", bad: "problem", warn: "check", unknown: "no status" };
const KIND_LABEL: Record<DependencyGraphNode["type"], string> = { server: "Server", integration: "Integration", device: "Network device", internet: "Internet" };
interface Placed extends DependencyGraphNode {
x: number;
y: number;
layer: number;
}
/**
* Columns by how deep each thing sits: what needs nothing on the left, then what needs only those, and so on. A column is ordered by where the
* things it needs sit, so the lines cross as little as is easy. (A loop can't be made, but if one ever got in the layering gives up rather than spin.)
*/
function layout(graph: DependencyGraph): { placed: Map<string, Placed>; width: number; height: number } {
const needs = new Map<string, string[]>();
for (const e of graph.edges) needs.set(e.to, [...(needs.get(e.to) ?? []), e.from]);
const layer = new Map<string, number>(graph.nodes.map((n) => [n.key, 0]));
for (let pass = 0; pass < graph.nodes.length; pass++) {
let moved = false;
for (const n of graph.nodes) {
const want = Math.max(-1, ...(needs.get(n.key) ?? []).map((k) => layer.get(k) ?? 0)) + 1;
if (want > (layer.get(n.key) ?? 0)) {
layer.set(n.key, want);
moved = true;
}
}
if (!moved) break;
}
const columns = new Map<number, DependencyGraphNode[]>();
for (const n of graph.nodes) columns.set(layer.get(n.key) ?? 0, [...(columns.get(layer.get(n.key) ?? 0) ?? []), n]);
const placed = new Map<string, Placed>();
const step = NODE_H + GAP_Y;
let height = 0;
for (const depth of [...columns.keys()].sort((a, b) => a - b)) {
const wanted = columns.get(depth)!.map((n) => {
const ys = (needs.get(n.key) ?? []).map((k) => placed.get(k)?.y).filter((y): y is number => y !== undefined);
return { n, y: ys.length ? ys.reduce((a, b) => a + b, 0) / ys.length : 0 };
});
wanted.sort((a, b) => a.y - b.y || a.n.name.localeCompare(b.n.name));
let next = 0;
for (const { n, y } of wanted) {
const at = Math.max(next, depth === 0 ? next : y);
placed.set(n.key, { ...n, x: depth * (NODE_W + COL_GAP), y: at, layer: depth });
next = at + step;
height = Math.max(height, at + NODE_H);
}
}
const maxLayer = Math.max(0, ...[...placed.values()].map((p) => p.layer));
return { placed, width: maxLayer * (NODE_W + COL_GAP) + NODE_W, height };
}
/** Everything reached from `start` by following edges one way (`forward`: to what needs it; otherwise to what it needs). */
function reach(graph: DependencyGraph, start: string, forward: boolean): Set<string> {
const out = new Set<string>();
const queue = [start];
while (queue.length) {
const cur = queue.shift()!;
for (const e of graph.edges) {
const [a, b] = forward ? [e.from, e.to] : [e.to, e.from];
if (a === cur && !out.has(b) && b !== start) {
out.add(b);
queue.push(b);
}
}
}
return out;
}
const names = (graph: DependencyGraph, keys: Iterable<string>) => [...keys].map((k) => graph.nodes.find((n) => n.key === k)?.name ?? k).sort((a, b) => a.localeCompare(b));
/**
* What needs what, drawn with the foundations on the left. Pick a box to see what would go down with it (red) and what it relies on (blue);
* hovering does the same for a moment. This is the answer to "what breaks if I reboot this?" before doing it.
*/
export default function DependencyMap() {
const [lineStyle] = useMapLineStyle();
const [graph, setGraph] = useState<DependencyGraph | null>(null);
const [error, setError] = useState<string | null>(null);
// From the command palette ("What depends on …?"): start with that box picked.
const [params] = useSearchParams();
const [selected, setSelected] = useState<string | null>(params.get("select"));
const [hover, setHover] = useState<string | null>(null);
useEffect(() => {
api.dependencies
.graph()
.then(setGraph)
.catch((err) => setError(readableError(err)));
}, []);
const view = useMemo(() => (graph ? layout(graph) : null), [graph]);
const active = hover ?? selected;
const sets = useMemo(() => {
if (!graph || !active) return null;
return { down: reach(graph, active, true), up: reach(graph, active, false) };
}, [graph, active]);
const activeNode = graph?.nodes.find((n) => n.key === active) ?? null;
if (error) return <ErrorNotice error={error} />;
if (!graph || !view) return <PageSkeleton />;
if (graph.nodes.length === 0) {
return (
<div className="card">
<div className="card-body text-secondary">
Nothing depends on anything yet. Say what needs what below, or set which server another runs on, and it is drawn here.
</div>
</div>
);
}
const state = (key: string) => (!sets || !active ? "" : key === active ? "map-active" : sets.down.has(key) ? "map-down" : sets.up.has(key) ? "map-up" : "map-dim");
return (
<div className="card">
<div className="card-body map-scroll">
<MapLinesToggle />
<div className="map-canvas" style={{ width: view.width, height: view.height }}>
<svg className="map-lines" width={view.width} height={view.height} aria-hidden="true">
{graph.edges.map((e) => {
const a = view.placed.get(e.from);
const b = view.placed.get(e.to);
if (!a || !b) return null;
const x1 = a.x + NODE_W;
const y1 = a.y + NODE_H / 2;
const x2 = b.x;
const y2 = b.y + NODE_H / 2;
let cls = "map-edge";
if (sets && active) {
const downPath = (e.from === active || sets.down.has(e.from)) && sets.down.has(e.to);
const upPath = (e.to === active || sets.up.has(e.to)) && sets.up.has(e.from);
cls = downPath ? "map-edge map-edge-down" : upPath ? "map-edge map-edge-up" : "map-edge map-dim";
}
return <path key={`${e.from}>${e.to}`} d={edgePath(x1, y1, x2, y2, lineStyle)} className={cls} fill="none" strokeDasharray={e.kind !== "written" ? "5 4" : undefined} />;
})}
</svg>
{[...view.placed.values()].map((n) => (
<button
key={n.key}
type="button"
className={`map-node map-node-${n.type === "server" ? "server" : n.type === "device" ? "device" : n.type === "internet" ? "internet" : "monitor"} ${state(n.key)}`}
style={{ left: n.x, top: n.y, width: NODE_W, height: NODE_H, textAlign: "left" }}
aria-pressed={selected === n.key}
aria-label={`${KIND_LABEL[n.type]}: ${n.name}, ${STATUS_WORD[n.status]}. Show what depends on it.`}
onClick={() => setSelected((s) => (s === n.key ? null : n.key))}
onMouseEnter={() => setHover(n.key)}
onMouseLeave={() => setHover((h) => (h === n.key ? null : h))}
onFocus={() => setHover(n.key)}
onBlur={() => setHover((h) => (h === n.key ? null : h))}
>
<span className={`map-status map-status-${n.status}`} aria-hidden="true">
{STATUS_SYMBOL[n.status]}
</span>
<span className="map-label">
<span className="map-title">{n.name}</span>
<span className="map-sub">{KIND_LABEL[n.type]}</span>
</span>
</button>
))}
</div>
</div>
<div className="card-footer" aria-live="polite">
{activeNode && sets ? (
<div>
<div className="mb-1">
<strong>{activeNode.name}</strong>{" "}
<Link to={activeNode.href} className="small">
open
</Link>
{selected !== active && <span className="text-secondary small ms-2">(click to keep this)</span>}
</div>
<div className={sets.down.size ? "text-red" : "text-secondary"}>
{sets.down.size ? `If it goes down, ${sets.down.size} ${sets.down.size === 1 ? "thing goes" : "things go"} with it: ${names(graph, sets.down).join(", ")}.` : t("Nothing depends on it.")}
</div>
<div className="text-secondary">{sets.up.size ? `It relies on ${names(graph, sets.up).join(", ")}.` : t("It relies on nothing here.")}</div>
</div>
) : (
<div className="text-secondary small d-flex flex-wrap gap-3">
<span>Lines run from what is needed (left) to what needs it (right). Dashed: &ldquo;runs on&rdquo;, set on the server.</span>
<span className="ms-auto">{t("Pick a box to see what would go down with it.")}</span>
</div>
)}
</div>
</div>
);
}