SPB Git

Repository Public

viz.tsx 2.6 KB 48 lines tsx

1import { cx, type Tone } from "./cx";23/** Sparkline over `[ts, avg, …]` points or plain numbers. Missing stretches (null / large time gaps) break the line. */4export function Sparkline({ points, label, tone, max, min }: { points: readonly (readonly number[] | number | null)[]; label: string; tone?: Tone; max?: number; min?: number }) {5  const W = 96, H = 24;6  const vals: { x: number; y: number | null }[] = points.map((p, i) => (p === null ? { x: i, y: null } : typeof p === "number" ? { x: i, y: p } : { x: p[0] ?? i, y: p[1] ?? null }));7  const ys = vals.map((v) => v.y).filter((v): v is number => v !== null && Number.isFinite(v));8  if (ys.length < 2) return <svg className="mcc-spark" viewBox={`0 0 ${W} ${H}`} role="img" aria-label={label} />;9  const lo = min ?? Math.min(...ys), hi = max ?? Math.max(...ys);10  const x0 = vals[0]?.x ?? 0, x1 = vals[vals.length - 1]?.x ?? 1;11  const steps = vals.slice(1).map((v, i) => v.x - (vals[i]?.x ?? 0)).sort((a, b) => a - b);12  const median = steps[Math.floor(steps.length / 2)] ?? 1;13  const sx = (x: number) => ((x - x0) / (x1 - x0 || 1)) * W;14  const sy = (y: number) => H - 2 - ((y - lo) / (hi - lo || 1)) * (H - 4);15  let d = "";16  let pen = false;17  vals.forEach((v, i) => {18    const gap = i > 0 && v.x - (vals[i - 1]?.x ?? 0) > median * 2.5;19    if (v.y === null || !Number.isFinite(v.y)) { pen = false; return; }20    d += `${pen && !gap ? "L" : "M"}${sx(v.x).toFixed(1)} ${sy(v.y).toFixed(1)}`;21    pen = true;22  });23  return (24    <svg className={cx("mcc-spark", tone && "tone", tone && `tone-${tone}`)} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" role="img" aria-label={label}>25      <path d={d} />26    </svg>27  );28}2930/** Thresholds used when a meter is a utilisation (0–100 %). */31export function usageTone(pct: number, warn = 80, crit = 92): Tone {32  return pct >= crit ? "critical" : pct >= warn ? "warning" : "info";33}3435/** Horizontal meter. `value` is 0–100; the textual value is always shown beside the bar. */36export function Meter({ value, label, text, tone, stacked }: { value: number; label: string; text: string; tone?: Tone; stacked?: boolean }) {37  const v = Math.max(0, Math.min(100, value));38  return (39    <div className={cx("mcc-meter", `tone-${tone ?? usageTone(v)}`, stacked && "stacked")} role="meter" aria-label={label} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(v)} aria-valuetext={text}>40      <svg viewBox="0 0 100 6" preserveAspectRatio="none" aria-hidden="true">41        <rect className="track" x="0" y="0" width="100" height="6" />42        <rect className="fill" x="0" y="0" width={v} height="6" />43      </svg>44      <span className="val num">{text}</span>45    </div>46  );47}48
Files main
Menu

Theme