SPB Git

Repository Public

TimeSeriesChart.tsx 9.9 KB 211 lines tsx

1"use client";2import uPlot from "uplot";3import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";4import { useI18n } from "@/i18n";5import { alignSeries, summarize, withAlpha, type SeriesInput } from "@/lib/chartData";6import { usePref } from "@/lib/prefs";7import { cx } from "./cx";8import { Button } from "./core";9import { DataTable, type Column } from "./Table";1011export type ChartSeries = SeriesInput;1213interface Props {14  title: string;15  /** Catalog unit (percent, bytes, bytes_per_s, ms, …) used for axis, legend and summary formatting. */16  unit: string;17  series: readonly ChartSeries[];18  /** Visible time range (ms). Defaults to the data extent. */19  from?: number;20  to?: number;21  size?: "short" | "default" | "tall";22  /** Upper bound of the value axis (100 for percentages). */23  yMax?: number;24  loading?: boolean;25  /** Shown in the plot area when there is nothing to draw (availability state, 501, error…). */26  placeholder?: ReactNode;27  /** Draw the min/max envelope (default: when at most 3 series). */28  band?: boolean;29  actions?: ReactNode;30}3132function cssVar(name: string): string {33  return getComputedStyle(document.documentElement).getPropertyValue(name).trim();34}3536/** Re-render trigger when the theme attribute changes (canvas colours are read from tokens at draw time). */37function useThemeVersion(): number {38  const [v, setV] = useState(0);39  useEffect(() => {40    const mo = new MutationObserver(() => setV((x) => x + 1));41    mo.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });42    return () => mo.disconnect();43  }, []);44  return v;45}4647/**48 * Accessible time-series chart on uPlot (canvas).49 * - average line + min/max envelope from `[ts, avg, min, max]` points; holes are drawn as gaps;50 * - keyboard: focus the plot, ←/→ move the cursor (Shift = ×10), Home/End jump; the value is announced;51 * - a textual summary and a table view are always available.52 */53export function TimeSeriesChart({ title, unit, series, from, to, size = "default", yMax, loading, placeholder, band, actions }: Props) {54  const { t, fmt } = useI18n();55  const host = useRef<HTMLDivElement>(null);56  const plot = useRef<uPlot | null>(null);57  const theme = useThemeVersion();58  const summaryId = useId();59  const [tablePref, setTablePref] = usePref<"0" | "1">("chart.table", "0");60  const asTable = tablePref === "1";61  const [cursor, setCursor] = useState<number | null>(null);6263  const aligned = useMemo(() => alignSeries(series), [series]);64  const summary = useMemo(() => summarize(series), [series]);65  const hasData = aligned.ts.length > 0;66  const showBand = band ?? series.length <= 3;67  const fmtRef = useRef(fmt);68  useEffect(() => {69    fmtRef.current = fmt;70  }, [fmt]);7172  useEffect(() => {73    const el = host.current;74    if (!el || asTable || !hasData) return;75    const axis = cssVar("--mcc-color-chart-axis");76    const grid = cssVar("--mcc-color-chart-grid");77    const colors = [1, 2, 3, 4, 5, 6].map((i) => cssVar(`--mcc-color-chart-${i}`));78    const font = `11px ${cssVar("--mcc-font-sans")}`;79    const data: uPlot.AlignedData = [aligned.ts, ...aligned.series.flatMap((s) => [s.avg, s.min, s.max])] as uPlot.AlignedData;80    const span = (to ?? aligned.ts[aligned.ts.length - 1] ?? 0) - (from ?? aligned.ts[0] ?? 0);81    const opts: uPlot.Options = {82      width: Math.max(160, el.clientWidth),83      height: Math.max(80, el.clientHeight),84      ms: 1,85      legend: { show: false },86      cursor: { y: false, points: { size: 7 }, drag: { x: false, y: false } },87      padding: [8, 8, 0, 0],88      scales: {89        x: { time: true, ...(from !== undefined && to !== undefined ? { range: [from, to] as [number, number] } : {}) },90        y: { range: (_u, min, max) => [Math.min(0, min ?? 0), yMax ?? (max === undefined || max === null || max <= 0 ? 1 : max * 1.08)] },91      },92      axes: [93        {94          stroke: axis, font, grid: { stroke: grid, width: 1 }, ticks: { stroke: grid, width: 1, size: 4 },95          values: (_u, splits) => splits.map((ms) => (span > 2 * 86400_000 ? fmtRef.current.date(ms) : fmtRef.current.time(ms, { seconds: false }))),96        },97        {98          stroke: axis, font, size: 64, grid: { stroke: grid, width: 1 }, ticks: { show: false },99          values: (_u, splits) => splits.map((v) => fmtRef.current.metric(v, unit)),100        },101      ],102      series: [103        {},104        ...aligned.series.flatMap((s, i) => {105          const c = colors[i % colors.length] ?? axis;106          return [107            { label: s.label, stroke: c, width: 1.6, spanGaps: false, points: { show: aligned.ts.length < 60, size: 4, fill: c } },108            { label: `${s.label} min`, stroke: "transparent", width: 0, spanGaps: false, points: { show: false } },109            { label: `${s.label} max`, stroke: "transparent", width: 0, spanGaps: false, points: { show: false } },110          ] satisfies uPlot.Series[];111        }),112      ],113      bands: showBand ? aligned.series.map((_s, i) => ({ series: [3 * i + 3, 3 * i + 2] as [number, number], fill: withAlpha(colors[i % colors.length] ?? axis, 0.16) })) : [],114      hooks: { setCursor: [(u) => setCursor(typeof u.cursor.idx === "number" ? u.cursor.idx : null)] },115    };116    const u = new uPlot(opts, data, el);117    plot.current = u;118    const ro = new ResizeObserver(() => u.setSize({ width: Math.max(160, el.clientWidth), height: Math.max(80, el.clientHeight) }));119    ro.observe(el);120    return () => {121      ro.disconnect();122      u.destroy();123      plot.current = null;124    };125  }, [aligned, asTable, hasData, from, to, unit, yMax, showBand, theme]);126127  const moveCursor = (delta: number | "start" | "end") => {128    const u = plot.current;129    if (!u || aligned.ts.length === 0) return;130    const lastIdx = aligned.ts.length - 1;131    const cur = cursor ?? lastIdx;132    const idx = delta === "start" ? 0 : delta === "end" ? lastIdx : Math.max(0, Math.min(lastIdx, cur + delta));133    const ts = aligned.ts[idx];134    if (ts === undefined) return;135    u.setCursor({ left: u.valToPos(ts, "x"), top: u.bbox.height / devicePixelRatio / 2 });136    setCursor(idx);137  };138139  const cursorText = (() => {140    if (cursor === null) return "";141    const ts = aligned.ts[cursor];142    if (ts === undefined) return "";143    const parts = aligned.series.map((s) => {144      const v = s.avg[cursor];145      return `${s.label}: ${v === null || v === undefined ? t("ui.chart.noValue") : fmt.metric(v, unit)}`;146    });147    return `${fmt.dateTime(ts, { seconds: true, zone: false })} — ${parts.join(" · ")}`;148  })();149150  const summaryText = hasData151    ? summary.map((s) => (s.count === 0 ? t("ui.chart.summaryEmpty", { label: s.label }) : t("ui.chart.summary", { label: s.label, last: fmt.metric(s.last ?? 0, unit), min: fmt.metric(s.min ?? 0, unit), avg: fmt.metric(s.avg ?? 0, unit), max: fmt.metric(s.max ?? 0, unit) }))).join(" ")152    : t("ui.chart.noData");153154  type Row = { ts: number; values: (number | null)[] };155  const tableRows: Row[] = useMemo(() => (asTable ? aligned.ts.map((ts, i) => ({ ts, values: aligned.series.map((s) => s.avg[i] ?? null) })).reverse() : []), [asTable, aligned]);156  const columns: Column<Row>[] = [157    { id: "ts", header: t("ui.chart.time"), cell: (r) => fmt.dateTime(r.ts, { seconds: true }), sortValue: (r) => r.ts, mono: true },158    ...aligned.series.map((s, i): Column<Row> => ({ id: s.id, header: s.label, align: "right", cell: (r) => { const v = r.values[i]; return v === null || v === undefined ? <span className="faint">{t("ui.chart.noValue")}</span> : fmt.metric(v, unit); }, sortValue: (r) => r.values[i] })),159  ];160161  return (162    <figure className="mcc-chart">163      <div className="mcc-chart-head">164        <figcaption><h3>{title}</h3></figcaption>165        <div className="row">166          {actions}167          <Button size="sm" variant="ghost" icon={asTable ? "chart" : "table"} aria-pressed={asTable} onClick={() => setTablePref(asTable ? "0" : "1")}>168            {asTable ? t("ui.chart.showChart") : t("ui.chart.showTable")}169          </Button>170        </div>171      </div>172      {asTable ? (173        <DataTable caption={title} columns={columns} rows={tableRows} rowKey={(r) => String(r.ts)} compact empty={t("ui.chart.noData")} />174      ) : (175        <div176          ref={host}177          className={cx("mcc-chart-plot", size !== "default" && size)}178          role="group"179          tabIndex={0}180          aria-label={t("ui.chart.aria", { title })}181          aria-describedby={summaryId}182          aria-busy={loading || undefined}183          onKeyDown={(e) => {184            const step = e.shiftKey ? 10 : 1;185            if (e.key === "ArrowLeft") { e.preventDefault(); moveCursor(-step); }186            else if (e.key === "ArrowRight") { e.preventDefault(); moveCursor(step); }187            else if (e.key === "Home") { e.preventDefault(); moveCursor("start"); }188            else if (e.key === "End") { e.preventDefault(); moveCursor("end"); }189          }}190        >191          {!hasData ? <div className="mcc-chart-msg">{loading ? <span className="mcc-skel w-60" role="status" aria-label={t("common.loading")} /> : (placeholder ?? <span className="mcc-unmeasured">{t("ui.chart.noData")}</span>)}</div> : null}192        </div>193      )}194      {hasData ? (195        <ul className="mcc-chart-legend" aria-label={t("ui.chart.legend")}>196          {summary.map((s, i) => (197            <li key={s.id}>198              <svg className="swatch" viewBox="0 0 12 12" aria-hidden="true"><line x1="0" y1="6" x2="12" y2="6" className={`s${(i % 6) + 1}`} /></svg>199              <span>{s.label}</span>200              {s.last !== undefined ? <span className="v num">{fmt.metric(s.last, unit)}</span> : null}201              {s.count > 0 ? <span className="faint num">{t("ui.chart.range", { min: fmt.metric(s.min ?? 0, unit), max: fmt.metric(s.max ?? 0, unit) })}</span> : null}202            </li>203          ))}204        </ul>205      ) : null}206      <p id={summaryId} className="sr-only">{summaryText} {t("ui.chart.keyboardHelp")}</p>207      {!asTable && hasData ? <p className="mcc-chart-cursor num" aria-live="polite">{cursorText}</p> : null}208    </figure>209  );210}211
Files main
Menu

Theme