1"use client";
2
3import * as React from "react";
4import { cn } from "@/lib/utils";
5
6const VIEWBOX_W = 640;
7const VIEWBOX_H = 220;
8const PAD_X = 0;
9const PAD_Y_TOP = 24;
10const PAD_Y_BOTTOM = 12;
11const LINE_WIDTH = 2;
12const CORNER_RADIUS = 2.5;
13const TRANSITION = "200ms cubic-bezier(0.16, 1, 0.3, 1)";
14const TOOLTIP_SHADOW = [
15 "0 0 0 1px rgba(0, 0, 0, 0.04)",
16 "0 1px 2px rgba(0, 0, 0, 0.04)",
17 "0 4px 16px -4px rgba(0, 0, 0, 0.12)",
18 "0 12px 32px -8px rgba(0, 0, 0, 0.08)",
19].join(", ");
20const DOT_SHADOW = "0 0 0 2px #FFF, 0 0 8px 2px rgba(0, 0, 0, 0.12)";
21
22function buildRoundedPath(
23 pts: Array<{ x: number; y: number }>,
24 radius: number,
25): string {
26 if (pts.length === 0) return "";
27 const f = (n: number) => n.toFixed(3);
28 if (pts.length === 1) return `M${f(pts[0].x)} ${f(pts[0].y)}`;
29
30 let d = `M${f(pts[0].x)} ${f(pts[0].y)}`;
31 for (let i = 1; i < pts.length - 1; i++) {
32 const prev = pts[i - 1];
33 const curr = pts[i];
34 const next = pts[i + 1];
35 const inDx = curr.x - prev.x;
36 const inDy = curr.y - prev.y;
37 const inLen = Math.hypot(inDx, inDy) || 1;
38 const outDx = next.x - curr.x;
39 const outDy = next.y - curr.y;
40 const outLen = Math.hypot(outDx, outDy) || 1;
41 const r = Math.min(radius, inLen / 2, outLen / 2);
42 const bx = curr.x - (inDx / inLen) * r;
43 const by = curr.y - (inDy / inLen) * r;
44 const ax = curr.x + (outDx / outLen) * r;
45 const ay = curr.y + (outDy / outLen) * r;
46 d += ` L${f(bx)} ${f(by)} Q${f(curr.x)} ${f(curr.y)} ${f(ax)} ${f(ay)}`;
47 }
48 const last = pts[pts.length - 1];
49 d += ` L${f(last.x)} ${f(last.y)}`;
50 return d;
51}
52
53export interface ChartProps {
54 /** Numeric values to plot — one segment per pair of consecutive points. */
55 data: number[];
56 /** Optional label for each data point — shown at the top of the tooltip card. */
57 labels?: string[];
58 /** Series name shown next to the indicator dot in the tooltip. */
59 name?: string;
60 /** Line + dot color as a hex string (e.g. `"#0090FD"`). Default `"#0090FD"`. */
61 color?: string;
62 /** Maximum chart width in px. The chart preserves a 640:220 aspect ratio. Default `640`. */
63 width?: number;
64 /** Format the tooltip value. Receives the value and its index. */
65 formatValue?: (value: number, index: number) => React.ReactNode;
66 /** Index of the active point on initial render. Defaults to the last point. */
67 defaultIndex?: number;
68 /** Show X-axis tick labels at the bottom. Requires `labels`. Default `true`. */
69 showXAxis?: boolean;
70 /** Reveal the line + fill in color from left to the cursor (gray before, color after). Default `false`. */
71 reveal?: boolean;
72 /** Show the gray gradient fill under the line. Default `true`. */
73 showFill?: boolean;
74 /** Show the colored dot at the active data point. Default `true`. */
75 showDot?: boolean;
76 /** Smoothly animate the cursor, dot, and tooltip when the active point changes. Default `true`. */
77 animated?: boolean;
78 /** Target number of X-axis ticks. Default `6`. */
79 tickCount?: number;
80 /** Additional class names on the root container. */
81 className?: string;
82}
83
84export function Chart({
85 data,
86 labels,
87 name,
88 color = "#0090FD",
89 width = 640,
90 formatValue = (v) => v.toLocaleString(),
91 defaultIndex,
92 showXAxis = true,
93 tickCount = 6,
94 reveal = false,
95 showFill = true,
96 showDot = true,
97 animated = true,
98 className,
99}: ChartProps) {
100 const transition = animated ? TRANSITION : "0ms";
101 const reactId = React.useId();
102 const grayFillId = `${reactId}-gf`;
103 const clipId = `${reactId}-clip`;
104
105 const root = React.useRef<HTMLDivElement>(null);
106 const [activeIndex, setActiveIndex] = React.useState<number>(
107 defaultIndex ?? Math.max(0, data.length - 1),
108 );
109 const [containerWidth, setContainerWidth] = React.useState<number>(width);
110
111 React.useEffect(() => {
112 if (!root.current) return;
113 const ro = new ResizeObserver((entries) => {
114 const w = entries[0]?.contentRect.width;
115 if (w) setContainerWidth(w);
116 });
117 ro.observe(root.current);
118 return () => ro.disconnect();
119 }, []);
120
121 const points = React.useMemo(() => {
122 const n = data.length;
123 if (n === 0) return [];
124 const minV = Math.min(...data);
125 const maxV = Math.max(...data);
126 const range = maxV - minV || 1;
127 const innerW = VIEWBOX_W - 2 * PAD_X;
128 const innerH = VIEWBOX_H - PAD_Y_TOP - PAD_Y_BOTTOM;
129 return data.map((value, i) => ({
130 value,
131 index: i,
132 x: PAD_X + (n === 1 ? innerW / 2 : (i / (n - 1)) * innerW),
133 y: PAD_Y_TOP + (1 - (value - minV) / range) * innerH,
134 }));
135 }, [data]);
136
137 const { strokePath, fillPath } = React.useMemo(() => {
138 if (points.length === 0) return { strokePath: "", fillPath: "" };
139 const stroke = buildRoundedPath(points, CORNER_RADIUS);
140 const last = points[points.length - 1];
141 const first = points[0];
142 const baseY = VIEWBOX_H - PAD_Y_BOTTOM;
143 const fill = `${stroke} L${last.x.toFixed(3)} ${baseY} L${first.x.toFixed(3)} ${baseY} Z`;
144 return { strokePath: stroke, fillPath: fill };
145 }, [points]);
146
147 const active = points[Math.min(activeIndex, points.length - 1)] ?? points[0];
148 const activeXPct = active ? active.x / VIEWBOX_W : 0;
149 const activeYPct = active ? active.y / VIEWBOX_H : 0;
150
151 function onMove(e: React.MouseEvent<HTMLDivElement>) {
152 if (!root.current || points.length === 0) return;
153 const rect = root.current.getBoundingClientRect();
154 const rel = (e.clientX - rect.left) / rect.width;
155 const innerLeft = PAD_X / VIEWBOX_W;
156 const innerRight = (VIEWBOX_W - PAD_X) / VIEWBOX_W;
157 const t = (rel - innerLeft) / (innerRight - innerLeft);
158 const idx = Math.round(t * (points.length - 1));
159 setActiveIndex(Math.max(0, Math.min(points.length - 1, idx)));
160 }
161
162 const axisVisible = showXAxis && !!labels && labels.length > 0;
163 const tickIndices = React.useMemo(() => {
164 if (!axisVisible) return [];
165 const n = points.length;
166 // Estimate label width ~80px and require min gap so labels don't overlap.
167 const maxFit = Math.max(2, Math.floor(containerWidth / 80));
168 const count = Math.min(tickCount, maxFit, n);
169 if (count <= 1) return [0];
170 return Array.from({ length: count }, (_, i) =>
171 Math.round((i * (n - 1)) / (count - 1)),
172 );
173 }, [axisVisible, points.length, tickCount, containerWidth]);
174
175 if (points.length === 0 || !active) return null;
176
177 return (
178 <div
179 style={
180 {
181 maxWidth: width,
182 "--spell-color": color,
183 } as React.CSSProperties
184 }
185 className={cn(
186 "w-full select-none",
187 "[--spell-line:#c7c7c7] [--spell-badge:#e8e8e8]",
188 "dark:[--spell-line:#4f4f4f] dark:[--spell-badge:#2d2d2d]",
189 className,
190 )}
191 >
192 <div
193 ref={root}
194 onMouseMove={onMove}
195 className="relative w-full aspect-[640/220] touch-none"
196 >
197 <svg
198 width="100%"
199 height="100%"
200 viewBox={`0 0 ${VIEWBOX_W} ${VIEWBOX_H}`}
201 fill="none"
202 preserveAspectRatio="xMidYMid meet"
203 style={{ overflow: "visible" }}
204 >
205 <defs>
206 <linearGradient
207 id={grayFillId}
208 x1={VIEWBOX_W / 2}
209 y1={PAD_Y_TOP}
210 x2={VIEWBOX_W / 2}
211 y2={VIEWBOX_H}
212 gradientUnits="userSpaceOnUse"
213 >
214 <stop stopColor="var(--spell-badge)" />
215 <stop offset="1" stopColor="var(--spell-badge)" stopOpacity="0" />
216 </linearGradient>
217 <clipPath id={clipId} clipPathUnits="userSpaceOnUse">
218 <rect
219 x={0}
220 y={0}
221 width={VIEWBOX_W}
222 height={VIEWBOX_H}
223 style={{
224 transform: `scaleX(${activeXPct})`,
225 transformOrigin: "left center",
226 transition: `transform ${transition}`,
227 }}
228 />
229 </clipPath>
230 </defs>
231
232 {showFill && <path d={fillPath} fill={`url(#${grayFillId})`} />}
233
234 {reveal ? (
235 <>
236 <path
237 d={strokePath}
238 stroke="var(--spell-line)"
239 strokeWidth="2.2"
240 strokeLinecap="round"
241 strokeLinejoin="round"
242 />
243 <g clipPath={`url(#${clipId})`}>
244 <path
245 d={strokePath}
246 stroke="var(--spell-color)"
247 strokeWidth="2.2"
248 strokeLinecap="round"
249 strokeLinejoin="round"
250 />
251 </g>
252 </>
253 ) : (
254 <path
255 d={strokePath}
256 stroke="var(--spell-color)"
257 strokeWidth="2.2"
258 strokeLinecap="round"
259 strokeLinejoin="round"
260 />
261 )}
262 </svg>
263
264 {(() => {
265 const cursorPx = activeXPct * containerWidth;
266 const containerHeight = (containerWidth * VIEWBOX_H) / VIEWBOX_W;
267 const cursorYpx = activeYPct * containerHeight;
268 const tooltipOnLeft = activeXPct > 0.5;
269 return (
270 <>
271 <div
272 className="absolute pointer-events-none rounded-full bg-[var(--spell-line)] left-0"
273 style={{
274 width: LINE_WIDTH,
275 top: `${(PAD_Y_TOP / VIEWBOX_H) * 100}%`,
276 height: `${((VIEWBOX_H - PAD_Y_TOP - PAD_Y_BOTTOM / 2) / VIEWBOX_H) * 100}%`,
277 transform: `translate3d(${cursorPx - LINE_WIDTH / 2}px, 0, 0)`,
278 transition: `transform ${transition}`,
279 willChange: "transform",
280 }}
281 />
282
283 {showDot && (
284 <div
285 className="absolute pointer-events-none w-3 h-3 rounded-full bg-[var(--spell-color)] z-10 left-0 top-0"
286 style={{
287 transform: `translate3d(${cursorPx - 6}px, ${cursorYpx - 6}px, 0)`,
288 boxShadow: DOT_SHADOW,
289 transition: `transform ${transition}`,
290 willChange: "transform",
291 }}
292 />
293 )}
294
295 <div
296 className="absolute pointer-events-none z-20 grid min-w-32 items-start gap-1.5 rounded-lg bg-background px-2.5 py-1.5 text-xs left-0 top-0"
297 style={{
298 transform: tooltipOnLeft
299 ? `translate3d(calc(${cursorPx}px - 100% - 12px), calc(${cursorYpx}px - 50%), 0)`
300 : `translate3d(${cursorPx + 12}px, calc(${cursorYpx}px - 50%), 0)`,
301 transition: `transform ${transition}`,
302 willChange: "transform",
303 boxShadow: TOOLTIP_SHADOW,
304 }}
305 >
306 {labels?.[active.index] && (
307 <div className="font-medium text-foreground">
308 {labels[active.index]}
309 </div>
310 )}
311 <div className="flex w-full items-center gap-2">
312 <div
313 className="h-2.5 w-2.5 shrink-0 rounded-[2px]"
314 style={{ background: color }}
315 />
316 <div className="flex flex-1 items-center justify-between gap-3 leading-none">
317 {name && (
318 <span className="text-muted-foreground whitespace-nowrap">
319 {name}
320 </span>
321 )}
322 <span className="font-mono font-medium text-foreground tabular-nums ml-auto">
323 {formatValue(active.value, active.index)}
324 </span>
325 </div>
326 </div>
327 </div>
328 </>
329 );
330 })()}
331 </div>
332
333 {axisVisible && (
334 <div className="relative h-5 mt-2">
335 {tickIndices.map((i) => {
336 const pt = points[i];
337 const xPct = pt.x / VIEWBOX_W;
338 return (
339 <div
340 key={i}
341 className="absolute top-0 -translate-x-1/2 text-[11px] leading-none text-muted-foreground tabular-nums whitespace-nowrap"
342 style={{ left: `${xPct * 100}%` }}
343 >
344 {labels![i]}
345 </div>
346 );
347 })}
348 </div>
349 )}
350 </div>
351 );
352}
353