Repository Public
1// Pure layout maths of the overview widget grid (12 columns, unit rows). Persisted as `DashboardWidget[]` through2// PUT /me/dashboards/overview. Everything here is deterministic: same input, same layout.3import type { Schemas } from "@/api/client";45export type Widget = Schemas["DashboardWidget"];6export const COLS = 12;7export const MAX_H = 12;8export const MAX_WIDGETS = 24;9export const DASHBOARD_NAME = "overview";1011export const WIDGET_TYPES = ["nodes", "capacity", "trends", "alerts", "incidents", "jobs", "services", "models", "storage", "maintenance", "actions"] as const;12export type WidgetType = (typeof WIDGET_TYPES)[number];13export const isWidgetType = (t: string): t is WidgetType => (WIDGET_TYPES as readonly string[]).includes(t);1415export interface WidgetSpec {16 w: number;17 h: number;18 minW: number;19 minH: number;20 /** several instances allowed (each with its own config) */21 multiple?: boolean;22}23export const SPECS: Record<WidgetType, WidgetSpec> = {24 nodes: { w: 4, h: 3, minW: 3, minH: 2 },25 capacity: { w: 4, h: 3, minW: 3, minH: 3 },26 trends: { w: 8, h: 4, minW: 4, minH: 4, multiple: true },27 alerts: { w: 4, h: 3, minW: 3, minH: 2 },28 incidents: { w: 4, h: 2, minW: 3, minH: 2 },29 jobs: { w: 4, h: 2, minW: 2, minH: 2 },30 services: { w: 4, h: 2, minW: 3, minH: 2 },31 models: { w: 4, h: 2, minW: 2, minH: 2 },32 storage: { w: 4, h: 3, minW: 3, minH: 2 },33 maintenance: { w: 4, h: 3, minW: 3, minH: 2 },34 actions: { w: 4, h: 3, minW: 3, minH: 2 },35};36const FALLBACK_SPEC: WidgetSpec = { w: 4, h: 2, minW: 2, minH: 1 };37export const specOf = (type: string): WidgetSpec => (isWidgetType(type) ? SPECS[type] : FALLBACK_SPEC);3839export const TREND_METRICS = ["cpu.usage", "mem.used", "load.1", "gpu.usage", "net.rx", "net.tx", "disk.read", "disk.write"] as const;40export const TREND_GROUPS = ["cluster", "site", "role"] as const;41export type TrendGroup = (typeof TREND_GROUPS)[number];4243export function defaultLayout(): Widget[] {44 return [45 { id: "nodes", type: "nodes", x: 0, y: 0, w: 4, h: 3, config: {} },46 { id: "capacity", type: "capacity", x: 4, y: 0, w: 4, h: 3, config: {} },47 { id: "alerts", type: "alerts", x: 8, y: 0, w: 4, h: 3, config: {} },48 { id: "trends-cpu", type: "trends", x: 0, y: 3, w: 8, h: 4, config: { metric: "cpu.usage", group_by: "cluster" } },49 { id: "incidents", type: "incidents", x: 8, y: 3, w: 4, h: 2, config: {} },50 { id: "jobs", type: "jobs", x: 8, y: 5, w: 4, h: 2, config: {} },51 { id: "trends-mem", type: "trends", x: 0, y: 7, w: 8, h: 4, config: { metric: "mem.used", group_by: "cluster" } },52 { id: "services", type: "services", x: 8, y: 7, w: 4, h: 2, config: {} },53 { id: "models", type: "models", x: 8, y: 9, w: 4, h: 2, config: {} },54 { id: "storage", type: "storage", x: 0, y: 11, w: 4, h: 3, config: {} },55 { id: "maintenance", type: "maintenance", x: 4, y: 11, w: 4, h: 3, config: {} },56 { id: "actions", type: "actions", x: 8, y: 11, w: 4, h: 3, config: {} },57 ];58}5960const int = (v: unknown, fallback: number): number => (typeof v === "number" && Number.isFinite(v) ? Math.round(v) : fallback);61const clamp = (v: number, lo: number, hi: number): number => Math.max(lo, Math.min(hi, v));6263/** Bounds of one widget: inside the 12 columns, at least its minimum size. */64export function clampWidget(w: Widget): Widget {65 const spec = specOf(w.type);66 const width = clamp(int(w.w, spec.w), Math.min(spec.minW, COLS), COLS);67 const height = clamp(int(w.h, spec.h), spec.minH, MAX_H);68 return { ...w, w: width, h: height, x: clamp(int(w.x, 0), 0, COLS - width), y: Math.max(0, int(w.y, 0)) };69}7071export const collides = (a: Widget, b: Widget): boolean => a.id !== b.id && a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;7273/** Reading order: top to bottom, then left to right (DOM order, narrow-screen order). */74export function readingOrder(layout: readonly Widget[]): Widget[] {75 return [...layout].sort((a, b) => a.y - b.y || a.x - b.x || a.id.localeCompare(b.id));76}7778/**79 * Removes overlaps and vertical holes. `anchorId` (the widget being moved or resized) wins conflicts: the others80 * are pushed down, then every widget rises as far as it can ("gravity").81 */82export function settle(layout: readonly Widget[], anchorId?: string): Widget[] {83 const clamped = layout.map(clampWidget);84 const anchor = clamped.find((w) => w.id === anchorId);85 const order = readingOrder(clamped.filter((w) => w !== anchor));86 // the anchor is inserted where it stands in reading order but placed first, so it keeps its cell87 const placed: Widget[] = anchor ? [anchor] : [];88 for (const w of order) {89 let next = w;90 while (placed.some((p) => collides(p, next))) next = { ...next, y: next.y + 1 };91 placed.push(next);92 }93 const out: Widget[] = [];94 for (const w of readingOrder(placed)) {95 let next = w;96 while (next.y > 0 && !out.some((p) => collides(p, { ...next, y: next.y - 1 }))) next = { ...next, y: next.y - 1 };97 out.push(next);98 }99 return readingOrder(out);100}101102export function moveTo(layout: readonly Widget[], id: string, x: number, y: number): Widget[] {103 return settle(layout.map((w) => (w.id === id ? clampWidget({ ...w, x, y: Math.max(0, y) }) : w)), id);104}105export function moveBy(layout: readonly Widget[], id: string, dx: number, dy: number): Widget[] {106 const w = layout.find((x) => x.id === id);107 return w ? moveTo(layout, id, w.x + dx, w.y + dy) : [...layout];108}109export function resizeTo(layout: readonly Widget[], id: string, w: number, h: number): Widget[] {110 return settle(111 layout.map((it) => {112 if (it.id !== id) return it;113 const spec = specOf(it.type);114 const width = clamp(w, Math.min(spec.minW, COLS), COLS - it.x);115 return clampWidget({ ...it, w: Math.max(width, Math.min(spec.minW, COLS)), h: clamp(h, spec.minH, MAX_H) });116 }),117 id,118 );119}120export function resizeBy(layout: readonly Widget[], id: string, dw: number, dh: number): Widget[] {121 const w = layout.find((x) => x.id === id);122 return w ? resizeTo(layout, id, w.w + dw, w.h + dh) : [...layout];123}124125export function bottom(layout: readonly Widget[]): number {126 return layout.reduce((m, w) => Math.max(m, w.y + w.h), 0);127}128129/** Types that can still be added (single-instance types already on the grid are excluded). */130export function addableTypes(layout: readonly Widget[]): WidgetType[] {131 if (layout.length >= MAX_WIDGETS) return [];132 return WIDGET_TYPES.filter((t) => SPECS[t].multiple || !layout.some((w) => w.type === t));133}134135export function addWidget(layout: readonly Widget[], type: WidgetType, config: Record<string, unknown> = {}): Widget[] {136 if (!addableTypes(layout).includes(type)) return [...layout];137 let n = 1;138 let id: string = type;139 while (layout.some((w) => w.id === id)) id = `${type}-${++n}`;140 const spec = SPECS[type];141 return settle([...layout, { id, type, x: 0, y: bottom(layout), w: spec.w, h: spec.h, config: type === "trends" ? { metric: "cpu.usage", group_by: "cluster", ...config } : config }]);142}143export function removeWidget(layout: readonly Widget[], id: string): Widget[] {144 return settle(layout.filter((w) => w.id !== id));145}146export function setConfig(layout: readonly Widget[], id: string, config: Record<string, unknown>): Widget[] {147 return layout.map((w) => (w.id === id ? { ...w, config: { ...w.config, ...config } } : w));148}149150/** Layout received from the server (or anything else): invalid entries dropped, ids unique, no overlap. Unknown types are kept. */151export function sanitizeLayout(input: unknown): Widget[] {152 if (!Array.isArray(input)) return [];153 const seen = new Set<string>();154 const out: Widget[] = [];155 for (const raw of input) {156 if (typeof raw !== "object" || raw === null) continue;157 const r = raw as Record<string, unknown>;158 if (typeof r.id !== "string" || r.id === "" || r.id.length > 40 || typeof r.type !== "string" || r.type.length > 60 || seen.has(r.id)) continue;159 seen.add(r.id);160 const spec = specOf(r.type);161 const config = typeof r.config === "object" && r.config !== null && !Array.isArray(r.config) ? (r.config as Record<string, unknown>) : {};162 out.push({ id: r.id, type: r.type, x: int(r.x, 0), y: int(r.y, 0), w: int(r.w, spec.w), h: int(r.h, spec.h), config });163 if (out.length >= MAX_WIDGETS) break;164 }165 return settle(out);166}167168export function sameLayout(a: readonly Widget[], b: readonly Widget[]): boolean {169 const key = (l: readonly Widget[]) => JSON.stringify(readingOrder(l).map((w) => [w.id, w.type, w.x, w.y, w.w, w.h, Object.entries(w.config).sort(([p], [q]) => p.localeCompare(q))]));170 return key(a) === key(b);171}172173/** Config of a trends widget, tolerant of anything stored. */174export function trendConfig(config: Record<string, unknown>): { metric: string; groupBy: TrendGroup } {175 const metric = typeof config.metric === "string" && config.metric.length > 0 && config.metric.length <= 80 ? config.metric : "cpu.usage";176 const g = config.group_by;177 return { metric, groupBy: g === "site" || g === "role" ? g : "cluster" };178}179180/** Preset accepted by GET /cluster/trends for a period (custom ranges are not supported by that endpoint). */181export function trendRange(preset: "1h" | "24h" | "7d" | "30d" | null, spanMs: number): "1h" | "24h" | "7d" | "30d" {182 if (preset) return preset;183 return spanMs <= 2 * 3600_000 ? "1h" : spanMs <= 2 * 86400_000 ? "24h" : spanMs <= 10 * 86400_000 ? "7d" : "30d";184}185