History: server load, memory and disks are also kept as hourly (four months) and daily (over two years) averages with lowest and highest; endpoint answers as hourly (four months) beside the daily figures. Charts ask for 24 hours to a year and are drawn from whichever is fine enough. A disk that two weeks call flat is looked at again over ninety days for the forecast. Built once from what is kept. One chart: TimeChart replaces the sparkline and the multi-line chart: hover and arrow-key readout, a lowest/highest band, gaps shown as gaps, the same ranges everywhere and the choice remembered. Used for server trends, comparing servers, a check's availability and answer times (Endpoints > History) and a server's availability. Read API: /api/v1 (servers, metrics, alerts, incidents, inventory, network, endpoints and their history, maintenance) with personal read-only tokens made under the user menu: shown once, hashed, 30/90/365 days or none, ten at most, removed with their owner. GET only. Documented in API.md. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
242 lines
11 KiB
TypeScript
242 lines
11 KiB
TypeScript
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<HTMLDivElement>(null);
|
||
// Where the cursor is, as a time (null: nowhere), and whether the keyboard put it there.
|
||
const [cursor, setCursor] = useState<number | null>(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<typeof r.p> } => r.p !== null && Math.abs(r.p.x - at) <= Math.max((to - from) / 40, 1));
|
||
|
||
function move(e: PointerEvent<HTMLDivElement>) {
|
||
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<HTMLDivElement>) {
|
||
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 (
|
||
<div className="time-chart time-chart-empty text-secondary small" style={{ minHeight: compact ? 50 : 120 }} role="status">
|
||
{empty}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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 (
|
||
<div
|
||
ref={wrap}
|
||
className="time-chart"
|
||
tabIndex={0}
|
||
role="group"
|
||
aria-label={`${label}. Use the arrow keys to read it off.`}
|
||
onPointerMove={move}
|
||
onPointerLeave={() => setCursor(null)}
|
||
onKeyDown={key}
|
||
onBlur={() => setCursor(null)}
|
||
>
|
||
<svg viewBox={`0 0 ${W} ${H}`} className="time-chart-svg" role="img" aria-label={`${label}. ${summary}`}>
|
||
{grid.map((v) => (
|
||
<g key={v}>
|
||
<line x1={PAD.left} x2={W - PAD.right} y1={y(v)} y2={y(v)} stroke="currentColor" strokeOpacity={v === 0 ? 0.4 : 0.15} />
|
||
<text x={PAD.left - 6} y={y(v) + 4} textAnchor="end" fontSize="11" fill="currentColor" fillOpacity="0.7">
|
||
{unit === "%" ? `${v}%` : `${Math.round(v)}`}
|
||
</text>
|
||
</g>
|
||
))}
|
||
{unit === "ms" && (
|
||
<text x={4} y={PAD.top + 10} fontSize="10" fill="currentColor" fillOpacity="0.6">
|
||
ms
|
||
</text>
|
||
)}
|
||
{ticks.map((t, i) => (
|
||
<text key={i} x={x(t)} y={H - 6} textAnchor={i === 0 ? "start" : i === ticks.length - 1 ? "end" : "middle"} fontSize="11" fill="currentColor" fillOpacity="0.7">
|
||
{tickLabel(t)}
|
||
</text>
|
||
))}
|
||
{parsed.map((s) => {
|
||
if (s.pts.length === 0) return null;
|
||
if (bars) {
|
||
return (
|
||
<g key={s.name}>
|
||
{s.pts.map((p, i) => (
|
||
<rect key={i} x={x(p.x) - barW / 2} y={y(p.v)} width={barW} height={Math.max(0, y(0) - y(p.v))} fill={barColor ? barColor(p.v) : s.color} opacity={at !== null && p.x !== at ? 0.55 : 1} />
|
||
))}
|
||
</g>
|
||
);
|
||
}
|
||
// 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 (
|
||
<g key={s.name}>
|
||
{hasBand && bands.map((b, i) => <polygon key={i} points={b} fill={s.color} fillOpacity="0.14" stroke="none" />)}
|
||
{s.pts.length === 1 ? (
|
||
<circle cx={x(s.pts[0].x)} cy={y(s.pts[0].v)} r="3" fill={s.color} />
|
||
) : (
|
||
<path d={d} fill="none" stroke={s.color} strokeWidth={compact ? 1.6 : 2} strokeDasharray={s.dash || undefined} strokeLinejoin="round" strokeLinecap="round" />
|
||
)}
|
||
</g>
|
||
);
|
||
})}
|
||
{at !== null && (
|
||
<g pointerEvents="none">
|
||
<line x1={x(at)} x2={x(at)} y1={PAD.top} y2={H - PAD.bottom} stroke="currentColor" strokeOpacity="0.5" strokeDasharray="3 3" />
|
||
{!bars && readings.map((r) => <circle key={r.s.name} cx={x(r.p.x)} cy={y(r.p.v)} r="3.5" fill={r.s.color} stroke="var(--tblr-bg-surface, #fff)" strokeWidth="1.5" />)}
|
||
</g>
|
||
)}
|
||
</svg>
|
||
{at !== null && readings.length > 0 && (
|
||
<div className="time-chart-tip" style={{ left: `${tipLeft}%`, transform: tipLeft > 60 ? "translateX(calc(-100% - 10px))" : "translateX(10px)" }} role="status" aria-live="polite">
|
||
<div className="time-chart-tip-time">{spanDays > 120 ? formatDate(new Date(at)) : formatDateTime(new Date(at))}</div>
|
||
{readings.map((r) => (
|
||
<div key={r.s.name} className="time-chart-tip-row">
|
||
<span className="time-chart-swatch" style={{ background: bars && barColor ? barColor(r.p.v) : r.s.color }} aria-hidden="true" />
|
||
<span className="time-chart-tip-name">{r.s.name}</span>
|
||
<strong>{fmt(r.p.v)}</strong>
|
||
{r.p.lo !== undefined && r.p.hi !== undefined && r.p.hi !== r.p.lo && (
|
||
<span className="text-secondary small">
|
||
{" "}
|
||
({fmt(r.p.lo)}–{fmt(r.p.hi)})
|
||
</span>
|
||
)}
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|