Cells blend in OKLab from a neutral empty color to the theme's accent on a square-root scale instead of seven fixed blue steps; the legend shows the gradient. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
278 lines
9.7 KiB
TypeScript
278 lines
9.7 KiB
TypeScript
// Hand-written SVG charts following the dataviz method: categorical colors in
|
||
// fixed slot order, thin marks with 2px gaps, recessive axes, hover tooltips,
|
||
// legends, and a table view for every chart.
|
||
|
||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||
import { useT } from "../i18n";
|
||
|
||
export const SERIES = Array.from({ length: 8 }, (_, i) => `var(--series-${i + 1})`);
|
||
/**
|
||
* Sequential heat color from the theme: empty cells use the neutral --heat-empty,
|
||
* any value > 0 blends continuously (in OKLab, so lightness changes evenly) from a
|
||
* faint tint to the full theme accent. A square-root scale keeps rare small values
|
||
* visible next to a few large peaks.
|
||
*/
|
||
const HEAT_MIN = 22;
|
||
function heatShare(v: number, max: number): number {
|
||
if (v <= 0 || max <= 0) return 0;
|
||
return HEAT_MIN + (100 - HEAT_MIN) * Math.sqrt(Math.min(v / max, 1));
|
||
}
|
||
function heatColor(share: number): string {
|
||
return share <= 0 ? "var(--heat-empty)" : `color-mix(in oklab, var(--heat-full) ${share.toFixed(1)}%, var(--heat-empty))`;
|
||
}
|
||
const HEAT_GRADIENT = `linear-gradient(in oklab to right, ${[0, 0.1, 0.25, 0.45, 0.7, 1]
|
||
.map((f) => `${heatColor(heatShare(f * f, 1))} ${f * 100}%`)
|
||
.join(", ")})`;
|
||
|
||
function useWidth<T extends HTMLElement>() {
|
||
const ref = useRef<T>(null);
|
||
const [width, setWidth] = useState(600);
|
||
useEffect(() => {
|
||
if (!ref.current) return;
|
||
const ro = new ResizeObserver(([e]) => setWidth(e.contentRect.width));
|
||
ro.observe(ref.current);
|
||
return () => ro.disconnect();
|
||
}, []);
|
||
return [ref, width] as const;
|
||
}
|
||
|
||
/** Round up to 1/2/2.5/5 × 10^n for clean axis ticks. */
|
||
function niceMax(v: number): number {
|
||
if (v <= 0) return 1;
|
||
const exp = Math.pow(10, Math.floor(Math.log10(v)));
|
||
for (const m of [1, 2, 2.5, 5, 10]) if (v <= m * exp) return m * exp;
|
||
return 10 * exp;
|
||
}
|
||
|
||
export interface Series {
|
||
key: string;
|
||
label: string;
|
||
color: string;
|
||
}
|
||
|
||
export function Legend({ series }: { series: Series[] }) {
|
||
return (
|
||
<div className="legend">
|
||
{series.map((s) => (
|
||
<span key={s.key}>
|
||
<i style={{ background: s.color }} />
|
||
{s.label}
|
||
</span>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
interface Tip {
|
||
x: number;
|
||
y: number;
|
||
content: ReactNode;
|
||
}
|
||
|
||
/** Stacked bar chart over categories (days). values[i][seriesKey]. */
|
||
export function StackedBars({
|
||
categories,
|
||
categoryLabel,
|
||
series,
|
||
values,
|
||
format,
|
||
height = 220,
|
||
}: {
|
||
categories: string[];
|
||
categoryLabel: (c: string) => string;
|
||
series: Series[];
|
||
values: Record<string, number>[];
|
||
format: (v: number) => string;
|
||
height?: number;
|
||
}) {
|
||
const [ref, width] = useWidth<HTMLDivElement>();
|
||
const [tip, setTip] = useState<Tip>();
|
||
const [hover, setHover] = useState<number>();
|
||
const left = 56;
|
||
const bottom = 22;
|
||
const top = 8;
|
||
const plotW = Math.max(width - left - 4, 50);
|
||
const plotH = height - top - bottom;
|
||
const totals = values.map((v) => series.reduce((a, s) => a + (v[s.key] ?? 0), 0));
|
||
const max = niceMax(Math.max(...totals, 0));
|
||
const n = Math.max(categories.length, 1);
|
||
const slot = plotW / n;
|
||
const barW = Math.max(Math.min(slot * 0.72, 28), 2);
|
||
const ticks = [0, 0.25, 0.5, 0.75, 1].map((f) => f * max);
|
||
const labelEvery = Math.ceil(n / Math.max(Math.floor(plotW / 70), 1));
|
||
const y = (v: number) => top + plotH - (v / max) * plotH;
|
||
|
||
return (
|
||
<div className="chart" ref={ref} onMouseLeave={() => (setTip(undefined), setHover(undefined))}>
|
||
<svg height={height} role="img">
|
||
<g className="axis">
|
||
{ticks.map((tk) => (
|
||
<g key={tk}>
|
||
<line className="grid-line" x1={left} x2={left + plotW} y1={y(tk)} y2={y(tk)} />
|
||
<text x={left - 6} y={y(tk) + 4} textAnchor="end">
|
||
{format(tk)}
|
||
</text>
|
||
</g>
|
||
))}
|
||
{categories.map((c, i) =>
|
||
i % labelEvery === 0 ? (
|
||
<text key={c} x={left + slot * i + slot / 2} y={height - 6} textAnchor="middle">
|
||
{categoryLabel(c)}
|
||
</text>
|
||
) : null,
|
||
)}
|
||
</g>
|
||
{categories.map((c, i) => {
|
||
let acc = 0;
|
||
const x = left + slot * i + (slot - barW) / 2;
|
||
const segs = series.filter((s) => (values[i][s.key] ?? 0) > 0);
|
||
return (
|
||
<g key={c} opacity={hover === undefined || hover === i ? 1 : 0.55}>
|
||
{segs.map((s, si) => {
|
||
const v = values[i][s.key] ?? 0;
|
||
const y0 = y(acc);
|
||
acc += v;
|
||
const y1 = y(acc);
|
||
// 2px surface gap between stacked segments.
|
||
const h = Math.max(y0 - y1 - (si > 0 ? 2 : 0), 1);
|
||
const yTop = y1;
|
||
const isTop = si === segs.length - 1;
|
||
const r = isTop ? Math.min(4, barW / 2, h) : 0;
|
||
const d = `M${x},${yTop + h} V${yTop + r} Q${x},${yTop} ${x + r},${yTop} H${x + barW - r} Q${x + barW},${yTop} ${x + barW},${yTop + r} V${yTop + h} Z`;
|
||
return <path key={s.key} d={d} fill={s.color} />;
|
||
})}
|
||
{/* Hit target: full slot height, wider than the bar. */}
|
||
<rect
|
||
x={left + slot * i}
|
||
y={top}
|
||
width={slot}
|
||
height={plotH}
|
||
fill="transparent"
|
||
onMouseMove={(e) => {
|
||
setHover(i);
|
||
const box = (e.currentTarget.ownerSVGElement as SVGSVGElement).getBoundingClientRect();
|
||
setTip({
|
||
x: Math.min(e.clientX - box.left + 12, width - 180),
|
||
y: e.clientY - box.top + 12,
|
||
content: (
|
||
<>
|
||
<b>{categoryLabel(c)}</b>
|
||
{[...series].reverse().map((s) =>
|
||
values[i][s.key] ? (
|
||
<div key={s.key} className="tt-row">
|
||
<span>
|
||
<i style={{ background: s.color }} /> {s.label}
|
||
</span>
|
||
<span>{format(values[i][s.key])}</span>
|
||
</div>
|
||
) : null,
|
||
)}
|
||
<div className="tt-row" style={{ borderTop: "1px solid var(--bg3)", marginTop: 3 }}>
|
||
<span>Σ</span>
|
||
<b>{format(totals[i])}</b>
|
||
</div>
|
||
</>
|
||
),
|
||
});
|
||
}}
|
||
/>
|
||
</g>
|
||
);
|
||
})}
|
||
</svg>
|
||
{tip && (
|
||
<div className="tooltip" style={{ left: tip.x, top: tip.y }}>
|
||
{tip.content}
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** Day × hour heatmap with a continuous sequential ramp in the theme accent. cells[row*24+hour]; rows top to bottom. */
|
||
export function Heatmap({
|
||
cells,
|
||
rows,
|
||
format,
|
||
}: {
|
||
cells: number[];
|
||
/** Short label (axis) and long label (tooltip) per row. */
|
||
rows: { label: string; title: string }[];
|
||
format: (v: number) => string;
|
||
}) {
|
||
const t = useT();
|
||
const [ref, width] = useWidth<HTMLDivElement>();
|
||
const [tip, setTip] = useState<Tip>();
|
||
const left = 64;
|
||
const top = 18;
|
||
// Cells stretch with the width but stay at most 26 px tall.
|
||
const cellW = Math.max(Math.floor((width - left) / 24), 8);
|
||
const cell = Math.min(cellW, 26);
|
||
const max = Math.max(...cells, 0);
|
||
const order = rows.map((_, i) => i);
|
||
|
||
return (
|
||
<div className="chart" ref={ref} onMouseLeave={() => setTip(undefined)}>
|
||
<svg height={top + cell * rows.length + 4} role="img" aria-label={t("stats.heatmap")}>
|
||
<g className="axis">
|
||
{Array.from({ length: 24 }, (_, h) => h)
|
||
.filter((h) => h % (cellW >= 22 ? 1 : cellW >= 12 ? 3 : 6) === 0)
|
||
.map((h) => (
|
||
<text key={h} x={left + h * cellW + cellW / 2} y={12} textAnchor="middle">
|
||
{h}
|
||
</text>
|
||
))}
|
||
{order.map((d, row) => (
|
||
<text key={d} x={left - 6} y={top + row * cell + cell / 2 + 4} textAnchor="end">
|
||
{rows[d].label}
|
||
</text>
|
||
))}
|
||
</g>
|
||
{order.map((d, row) =>
|
||
Array.from({ length: 24 }, (_, h) => {
|
||
const v = cells[d * 24 + h] ?? 0;
|
||
return (
|
||
<rect
|
||
key={`${d}-${h}`}
|
||
x={left + h * cellW + 1}
|
||
y={top + row * cell + 1}
|
||
width={cellW - 2}
|
||
height={cell - 2}
|
||
rx={3}
|
||
style={{ fill: heatColor(heatShare(v, max)) }}
|
||
onMouseMove={(e) => {
|
||
const box = (e.currentTarget.ownerSVGElement as SVGSVGElement).getBoundingClientRect();
|
||
setTip({
|
||
x: Math.min(e.clientX - box.left + 12, width - 140),
|
||
y: e.clientY - box.top + 12,
|
||
content: (
|
||
<>
|
||
<b>
|
||
{rows[d].title} {String(h).padStart(2, "0")}:00–{String(h).padStart(2, "0")}:59
|
||
</b>
|
||
<div>{format(v)}</div>
|
||
</>
|
||
),
|
||
});
|
||
}}
|
||
/>
|
||
);
|
||
}),
|
||
)}
|
||
</svg>
|
||
<div className="legend" style={{ marginTop: 6 }}>
|
||
<i style={{ background: heatColor(0), width: 18 }} />
|
||
<span>{t("stats.heatEmpty")}</span>
|
||
<span style={{ marginLeft: 12 }}>{format(0)}</span>
|
||
<i className="heat-scale" style={{ background: HEAT_GRADIENT }} />
|
||
<span>{format(max)}</span>
|
||
</div>
|
||
{tip && (
|
||
<div className="tooltip" style={{ left: tip.x, top: tip.y }}>
|
||
{tip.content}
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|