import { useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from "react"; import { formatDate, formatDateTime, formatTime } from "../utils/date"; export interface ChartPoint { /** ISO time. */ t: string; v: number; /** The lowest and highest of what this point stands for (an hour's or a day's figures); drawn as a band round the line. */ lo?: number; hi?: number; } export interface ChartSeries { name: string; color: string; /** SVG dash pattern, so lines can be told apart without their colour. Empty for a solid line. */ dash?: string; points: ChartPoint[]; } const W = 720; const PAD = { left: 46, right: 12, top: 10, bottom: 24 }; /** A round number at or above `v`: 1, 2, 5 or 10 times a power of ten. */ function niceCeil(v: number): number { if (!(v > 0)) return 10; const pow = 10 ** Math.floor(Math.log10(v)); const f = v / pow; return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * pow; } const median = (xs: number[]) => { if (xs.length === 0) return 0; const s = [...xs].sort((a, b) => a - b); return s[Math.floor(s.length / 2)]; }; /** * The one chart: lines (or bars) over a stretch of time, the same everywhere — server load and disks, a check's answer times and availability, uptime. * Hover (or arrow keys, once it has focus) reads off the values at that moment. A band shows the lowest and highest where a point stands for an hour or a day, and * a gap in the data is a gap in the line. The scale is 0–100 for percentages, so a quiet server never looks as busy as a loaded one; for times it fits the data. */ export default function TimeChart({ series, from, to, label, unit = "%", compact = false, bars = false, barColor, format, empty = "No history in this stretch yet.", }: { series: ChartSeries[]; from: number; to: number; /** Read out by screen readers in place of the picture. */ label: string; unit?: "%" | "ms"; compact?: boolean; /** One bar per point instead of a line (daily availability). */ bars?: boolean; barColor?: (v: number) => string; format?: (v: number) => string; empty?: string; }) { const H = compact ? 116 : 250; const wrap = useRef(null); // Where the cursor is, as a time (null: nowhere), and whether the keyboard put it there. const [cursor, setCursor] = useState(null); const fmt = format ?? ((v: number) => (unit === "%" ? `${Math.round(v * 10) / 10}%` : `${Math.round(v)} ms`)); const parsed = useMemo(() => series.map((s) => ({ ...s, pts: s.points.map((p) => ({ ...p, x: Date.parse(p.t) })).filter((p) => Number.isFinite(p.x)) })), [series]); const any = parsed.some((s) => s.pts.length > 0); const top = unit === "%" ? 100 : niceCeil(Math.max(0, ...parsed.flatMap((s) => s.pts.map((p) => p.hi ?? p.v))) * 1.05); const x = (t: number) => PAD.left + ((t - from) / Math.max(to - from, 1)) * (W - PAD.left - PAD.right); const y = (v: number) => PAD.top + (1 - Math.min(top, Math.max(0, v)) / top) * (H - PAD.top - PAD.bottom); const spanDays = (to - from) / 86_400_000; const tickLabel = (t: number) => spanDays <= 1.5 ? formatTime(new Date(t), false) : spanDays <= 45 ? new Date(t).toLocaleDateString(undefined, { day: "numeric", month: "short" }) : new Date(t).toLocaleDateString(undefined, { month: "short", year: "2-digit" }); const ticks = (compact ? [0, 0.5, 1] : [0, 0.25, 0.5, 0.75, 1]).map((f) => from + f * (to - from)); const grid = compact ? [0, top / 2, top] : [0, top / 4, top / 2, (3 * top) / 4, top]; // Every moment any series has a point, for the arrow keys to step through. const moments = useMemo(() => [...new Set(parsed.flatMap((s) => s.pts.map((p) => p.x)))].sort((a, b) => a - b), [parsed]); const nearest = (s: (typeof parsed)[number], t: number) => { let best: (typeof s.pts)[number] | null = null; for (const p of s.pts) if (best === null || Math.abs(p.x - t) < Math.abs(best.x - t)) best = p; return best; }; // The moment closest to the cursor, so the vertical line sits on a real point. const at = cursor === null || moments.length === 0 ? null : moments.reduce((b, m) => (Math.abs(m - cursor) < Math.abs(b - cursor) ? m : b), moments[0]); const readings = at === null ? [] : parsed.map((s) => ({ s, p: nearest(s, at) })).filter((r): r is { s: (typeof parsed)[number]; p: NonNullable } => r.p !== null && Math.abs(r.p.x - at) <= Math.max((to - from) / 40, 1)); function move(e: PointerEvent) { const box = wrap.current?.getBoundingClientRect(); if (!box || box.width === 0) return; const vx = ((e.clientX - box.left) / box.width) * W; setCursor(from + ((vx - PAD.left) / (W - PAD.left - PAD.right)) * (to - from)); } function key(e: KeyboardEvent) { if (moments.length === 0) return; if (e.key === "Escape") return setCursor(null); if (e.key !== "ArrowLeft" && e.key !== "ArrowRight" && e.key !== "Home" && e.key !== "End") return; e.preventDefault(); const i = at === null ? moments.length - 1 : moments.indexOf(at); const next = e.key === "Home" ? 0 : e.key === "End" ? moments.length - 1 : Math.min(moments.length - 1, Math.max(0, i + (e.key === "ArrowRight" ? 1 : -1))); setCursor(moments[next]); } const summary = parsed .filter((s) => s.pts.length > 0) .map((s) => { const vs = s.pts.map((p) => p.v); return `${s.name}: now ${fmt(vs[vs.length - 1])}, from ${fmt(Math.min(...vs))} to ${fmt(Math.max(...vs))}`; }) .join(". "); if (!any) { return (
{empty}
); } const spacing = median(parsed.flatMap((s) => s.pts.slice(1).map((p, i) => p.x - s.pts[i].x))); const barW = Math.max(1.5, Math.min(24, ((W - PAD.left - PAD.right) * (spacing > 0 ? spacing : (to - from) / 30)) / Math.max(to - from, 1) * 0.8)); const tipLeft = at === null ? 0 : ((x(at) / W) * 100); return (
setCursor(null)} onKeyDown={key} onBlur={() => setCursor(null)} > {grid.map((v) => ( {unit === "%" ? `${v}%` : `${Math.round(v)}`} ))} {unit === "ms" && ( ms )} {ticks.map((t, i) => ( {tickLabel(t)} ))} {parsed.map((s) => { if (s.pts.length === 0) return null; if (bars) { return ( {s.pts.map((p, i) => ( ))} ); } // Where the data stops for a while, so does the line. const limit = Math.max(spacing * 3, (to - from) / 60); let d = ""; const bands: string[] = []; s.pts.forEach((p, i) => { const gap = i > 0 && p.x - s.pts[i - 1].x > limit; d += `${i === 0 || gap ? "M" : "L"}${x(p.x).toFixed(1)},${y(p.v).toFixed(1)} `; }); // The band: along the highs, then back along the lows, one shape for each unbroken stretch. const hasBand = s.pts.some((p) => p.hi !== undefined); if (hasBand) { let run: typeof s.pts = []; const close = () => { if (run.length > 1) { const up = run.map((p) => `${x(p.x).toFixed(1)},${y(p.hi ?? p.v).toFixed(1)}`); const down = [...run].reverse().map((p) => `${x(p.x).toFixed(1)},${y(p.lo ?? p.v).toFixed(1)}`); bands.push([...up, ...down].join(" ")); } run = []; }; s.pts.forEach((p, i) => { if (i > 0 && p.x - s.pts[i - 1].x > limit) close(); run.push(p); }); close(); } return ( {hasBand && bands.map((b, i) => )} {s.pts.length === 1 ? ( ) : ( )} ); })} {at !== null && ( {!bars && readings.map((r) => )} )} {at !== null && readings.length > 0 && (
60 ? "translateX(calc(-100% - 10px))" : "translateX(10px)" }} role="status" aria-live="polite">
{spanDays > 120 ? formatDate(new Date(at)) : formatDateTime(new Date(at))}
{readings.map((r) => (
))}
)}
); }