Spaces:
Sleeping
Sleeping
File size: 9,930 Bytes
5c43695 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | /**
* MiniLineChart β small SVG line/area chart for analytics trend tiles.
*
* Designed to fit inline next to a number tile or above a list. NOT a
* general-purpose chart library β supports just the shapes we need:
*
* β’ Single series β pass `data` as [{date, value}]
* β’ Multi-series β pass `series` as [{name, color?, points: [{date, value}]}]
*
* Renders an SVG with:
* - x-axis: evenly spaced date ticks (first, middle, last labeled)
* - y-axis: derived from data range with a 0 floor; no left ticks (keeps it small)
* - Hover tooltip shows the date and per-series values
* - Optional fill under the line for the single-series variant (looks like a
* "spark area" rather than a line)
*
* Why hand-rolled SVG and not Recharts?
* The bundle is already 285 kB and we render maybe 4 of these. Recharts
* would add ~120 kB gzipped for a fancier version of the same thing.
*
* Props:
* data single-series: [{date: "2026-05-12", value: 4}]
* series multi-series: [{name, color?, points: [{date, value}]}]
* width default 320
* height default 80
* color single-series color (default brand orange)
* fillUnder single-series only β fill area below line (default true)
* yLabel optional y-axis text label (rendered as title attribute)
* formatValue optional (v) => string for tooltip values
*/
import { useMemo, useState } from "react";
const DEFAULT_COLORS = [
"#d76a35", // brand orange
"#3b82c4", // blue
"#5fa86b", // green
"#b87cb8", // purple
"#d4a017", // gold
];
export default function MiniLineChart({
data = null,
series = null,
width = 320,
height = 80,
color = "#d76a35",
fillUnder = true,
yLabel = "",
formatValue = (v) => String(v),
showLegend = false,
}) {
// ββ Normalize to internal multi-series shape ββββββββββββββββββββββββββ
const normSeries = useMemo(() => {
if (series && series.length) {
return series.map((s, i) => ({
name: s.name,
color: s.color || DEFAULT_COLORS[i % DEFAULT_COLORS.length],
points: s.points || [],
}));
}
if (data && data.length) {
return [{ name: yLabel || "value", color, points: data.map((d) => ({ date: d.date, value: d.value ?? d.count ?? 0 })) }];
}
return [];
}, [data, series, color, yLabel]);
// ββ Date axis (union of all dates) ββββββββββββββββββββββββββββββββββββ
const allDates = useMemo(() => {
const s = new Set();
for (const ser of normSeries) {
for (const p of ser.points) s.add(p.date);
}
return Array.from(s).sort();
}, [normSeries]);
// ββ Y range βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const yMax = useMemo(() => {
let m = 0;
for (const ser of normSeries) {
for (const p of ser.points) {
const v = Number(p.value ?? p.count ?? 0);
if (v > m) m = v;
}
}
return m || 1;
}, [normSeries]);
// ββ Hover state βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const [hoverIdx, setHoverIdx] = useState(null);
if (allDates.length === 0) {
return (
<div className="mini-chart-empty" style={{ width, height }}>
no data yet
</div>
);
}
// ββ Geometry ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const padL = 8;
const padR = 8;
const padT = 6;
const padB = 18;
const innerW = width - padL - padR;
const innerH = height - padT - padB;
// x positions per date index (evenly spaced)
const n = allDates.length;
const xAt = (i) => padL + (n <= 1 ? innerW / 2 : (i / (n - 1)) * innerW);
const yAt = (v) => padT + innerH - (v / yMax) * innerH;
// For each series β SVG path
const lookup = (ser) => {
const m = new Map();
for (const p of ser.points) m.set(p.date, Number(p.value ?? p.count ?? 0));
return m;
};
const seriesPaths = normSeries.map((ser) => {
const m = lookup(ser);
let d = "";
let started = false;
allDates.forEach((date, i) => {
const v = m.get(date);
if (v == null) return;
const x = xAt(i);
const y = yAt(v);
d += (started ? " L " : "M ") + x.toFixed(1) + " " + y.toFixed(1);
started = true;
});
// Closed area path (only used for single-series fill)
let area = "";
if (started && fillUnder && normSeries.length === 1) {
const firstIdx = allDates.findIndex((dt) => m.has(dt));
const lastIdx = allDates.length - 1 - [...allDates].reverse().findIndex((dt) => m.has(dt));
area = `M ${xAt(firstIdx).toFixed(1)} ${yAt(0).toFixed(1)} ` +
d.replace(/^M /, "L ") +
` L ${xAt(lastIdx).toFixed(1)} ${yAt(0).toFixed(1)} Z`;
}
return { ser, path: d, area };
});
// Date tick labels (first, middle, last)
const tickIdxs = n <= 1 ? [0] :
n <= 3 ? allDates.map((_, i) => i) :
[0, Math.floor((n - 1) / 2), n - 1];
// Tooltip content for hovered index
const tip = hoverIdx == null ? null : (() => {
const date = allDates[hoverIdx];
const rows = normSeries.map((ser) => {
const v = lookup(ser).get(date);
return v == null ? null : { name: ser.name, color: ser.color, value: v };
}).filter(Boolean);
return { date, rows };
})();
return (
<div className="mini-chart" title={yLabel || ""}>
<svg
width={width}
height={height}
viewBox={`0 0 ${width} ${height}`}
role="img"
aria-label={yLabel || "trend chart"}
onMouseLeave={() => setHoverIdx(null)}
>
{/* Faint y-baseline */}
<line
x1={padL} y1={padT + innerH}
x2={padL + innerW} y2={padT + innerH}
stroke="var(--border)" strokeWidth="1"
/>
{/* Area fill (single series, optional) */}
{seriesPaths.map(({ ser, area }, i) =>
area ? (
<path
key={`area-${i}`}
d={area}
fill={ser.color}
fillOpacity="0.12"
/>
) : null
)}
{/* Lines */}
{seriesPaths.map(({ ser, path }, i) => (
<path
key={`line-${i}`}
d={path}
fill="none"
stroke={ser.color}
strokeWidth="1.6"
strokeLinejoin="round"
strokeLinecap="round"
/>
))}
{/* Hover dot (per series at hovered index) */}
{hoverIdx != null && normSeries.map((ser, i) => {
const v = lookup(ser).get(allDates[hoverIdx]);
if (v == null) return null;
return (
<circle
key={`dot-${i}`}
cx={xAt(hoverIdx)}
cy={yAt(v)}
r="3"
fill={ser.color}
stroke="var(--surface)"
strokeWidth="1.5"
/>
);
})}
{/* Hover vertical guide */}
{hoverIdx != null && (
<line
x1={xAt(hoverIdx)} y1={padT}
x2={xAt(hoverIdx)} y2={padT + innerH}
stroke="var(--muted)" strokeWidth="0.7" strokeDasharray="2 2"
opacity="0.5"
/>
)}
{/* Invisible mouse-area rects per data point */}
{allDates.map((_, i) => {
const left = i === 0 ? 0 : (xAt(i - 1) + xAt(i)) / 2;
const right = i === n - 1 ? width : (xAt(i) + xAt(i + 1)) / 2;
return (
<rect
key={`hit-${i}`}
x={left}
y={0}
width={Math.max(right - left, 1)}
height={height}
fill="transparent"
onMouseEnter={() => setHoverIdx(i)}
/>
);
})}
{/* x-axis ticks */}
{tickIdxs.map((i) => (
<text
key={`tick-${i}`}
x={xAt(i)}
y={height - 4}
textAnchor={i === 0 ? "start" : i === n - 1 ? "end" : "middle"}
fontSize="10"
fill="var(--muted)"
>
{fmtTick(allDates[i])}
</text>
))}
</svg>
{/* Tooltip */}
{tip && (
<div className="mini-chart-tip">
<div className="mini-chart-tip-date">{tip.date}</div>
{tip.rows.map((r) => (
<div key={r.name} className="mini-chart-tip-row">
<span className="mini-chart-tip-swatch" style={{ background: r.color }} />
<span className="mini-chart-tip-name">{r.name}</span>
<span className="mini-chart-tip-val">{formatValue(r.value)}</span>
</div>
))}
</div>
)}
{/* Legend */}
{showLegend && normSeries.length > 1 && (
<div className="mini-chart-legend">
{normSeries.map((ser) => (
<span key={ser.name} className="mini-chart-legend-item">
<span className="mini-chart-legend-swatch" style={{ background: ser.color }} />
{ser.name}
</span>
))}
</div>
)}
</div>
);
}
function fmtTick(isoDate) {
// "2026-05-12" β "May 12"
if (!isoDate || isoDate.length < 10) return isoDate || "";
const [, m, d] = isoDate.split("-");
const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
return `${months[parseInt(m, 10) - 1]} ${parseInt(d, 10)}`;
}
|