跳至正文
获取 Pro
动效组件M.31

多系列面积图

FreeRegistry
components/linyi/area-chart.tsx
motionclass-variance-authority
"use client";
 
import * as React from "react";
import { motion, useMotionValue, useSpring } from "motion/react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/cn";
import { SPRING_PROGRESS } from "@/lib/motion";
import { playSound } from "@/lib/sound";
 
export interface AreaChartSeries {
key: string;
label: string;
colorIndex?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
}
 
export interface AreaChartDatum {
label: string;
values: Record<string, number>;
}
 
export const areaChartVariants = cva(
"w-full rounded-[16px] border border-line-strong bg-surface p-4 text-fg shadow-panel select-none",
{
variants: {
variant: {
surface: "bg-surface",
well: "bg-well/55 border-line-well shadow-none",
},
},
defaultVariants: {
variant: "surface",
},
}
);
 
export interface AreaChartProps
extends Omit<React.ComponentPropsWithRef<"div">, "children">,
VariantProps<typeof areaChartVariants> {
data: AreaChartDatum[];
series: AreaChartSeries[];
title?: string;
subtitle?: string;
smooth?: boolean;
height?: number;
showGrid?: boolean;
showLegend?: boolean;
valueFormatter?: (value: number) => string;
}
 
function getChartColorVar(index: number): string {
const safe = ((index - 1) % 8) + 1;
return `var(--chart-${safe})`;
}
 
function buildSeriesPaths(
pts: { x: number; y: number }[],
baselineY: number,
smooth: boolean
) {
if (pts.length === 0) return { line: "", area: "" };
let line = `M ${pts[0].x.toFixed(1)} ${pts[0].y.toFixed(1)}`;
for (let i = 0; i < pts.length - 1; i++) {
const p0 = pts[i];
const p1 = pts[i + 1];
if (smooth) {
const cx = (p0.x + p1.x) / 2;
line += ` C ${cx.toFixed(1)} ${p0.y.toFixed(1)}, ${cx.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`;
} else {
line += ` L ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`;
}
}
const last = pts[pts.length - 1];
const area = `${line} L ${last.x.toFixed(1)} ${baselineY.toFixed(1)} L ${pts[0].x.toFixed(1)} ${baselineY.toFixed(1)} Z`;
return { line, area };
}
 
export function AreaChart({
data,
series,
title,
subtitle,
smooth = true,
height = 210,
showGrid = true,
showLegend = true,
valueFormatter = (v) => v.toLocaleString(),
variant = "surface",
className,
...props
}: AreaChartProps) {
const uid = React.useId().replace(/:/g, "");
const containerRef = React.useRef<HTMLDivElement | null>(null);
const svgRef = React.useRef<SVGSVGElement | null>(null);
const [width, setWidth] = React.useState(440);
const [activeIndex, setActiveIndex] = React.useState<number | null>(null);
const [hiddenKeys, setHiddenKeys] = React.useState<Set<string>>(() => new Set());
 
React.useEffect(() => {
const el = containerRef.current;
if (!el || typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver((entries) => {
const next = Math.round(entries[0]?.contentRect.width ?? 0);
if (next > 0) setWidth(next);
});
ro.observe(el);
return () => ro.disconnect();
}, []);
 
const activeSeries = React.useMemo(
() => series.filter((s) => !hiddenKeys.has(s.key)),
[series, hiddenKeys]
);
 
const toggleSeries = (key: string) => {
setHiddenKeys((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else if (series.length - next.size > 1) next.add(key);
return next;
});
};
 
const padLeft = 40;
const padRight = 14;
const padTop = 14;
const padBottom = 26;
const plotW = Math.max(120, width - padLeft - padRight);
const plotH = Math.max(80, height - padTop - padBottom);
const baselineY = padTop + plotH;
 
const maxVal = React.useMemo(() => {
let peak = 0;
for (const d of data) {
for (const s of activeSeries) {
const val = Math.max(0, d.values[s.key] ?? 0);
if (val > peak) peak = val;
}
}
return peak > 0 ? peak * 1.12 : 100;
}, [data, activeSeries]);
 
const xCoords = React.useMemo(() => {
const count = Math.max(1, data.length - 1);
return data.map((_, idx) => padLeft + (idx / count) * plotW);
}, [data, plotW]);
 
const seriesGeometry = React.useMemo(() => {
return activeSeries.map((s) => {
const color = getChartColorVar(
s.colorIndex ?? series.findIndex((x) => x.key === s.key) + 1
);
const pts = data.map((d, idx) => {
const val = Math.max(0, d.values[s.key] ?? 0);
const y = baselineY - (val / maxVal) * plotH;
return { x: xCoords[idx] ?? padLeft, y, val };
});
const { line, area } = buildSeriesPaths(pts, baselineY, smooth);
return { series: s, color, pts, line, area };
});
}, [activeSeries, series, data, xCoords, baselineY, maxVal, plotH, smooth]);
 
const ticks = React.useMemo(() => {
const steps = 4;
return Array.from({ length: steps + 1 }, (_, i) => {
const ratio = i / steps;
return {
value: Math.round(maxVal * ratio),
y: padTop + plotH * (1 - ratio),
};
});
}, [maxVal, plotH]);
 
const guideX = useMotionValue(xCoords[xCoords.length - 1] ?? padLeft);
const smoothGuideX = useSpring(guideX, SPRING_PROGRESS);
 
React.useEffect(() => {
if (activeIndex !== null && xCoords[activeIndex] !== undefined) {
guideX.set(xCoords[activeIndex]);
}
}, [activeIndex, xCoords, guideX]);
 
const handlePointerMove = (e: React.PointerEvent<SVGSVGElement>) => {
const rect = svgRef.current?.getBoundingClientRect();
if (!rect || rect.width <= 0 || xCoords.length === 0) return;
const relX = ((e.clientX - rect.left) / rect.width) * width;
let nearest = 0;
let best = Infinity;
for (let i = 0; i < xCoords.length; i++) {
const dist = Math.abs(xCoords[i] - relX);
if (dist < best) {
best = dist;
nearest = i;
}
}
if (nearest !== activeIndex) {
setActiveIndex(nearest);
playSound("tap", { pitch: 0.92 + nearest * 0.025, volume: 0.2 });
}
};
 
const activeDatum = activeIndex !== null ? data[activeIndex] : null;
const activeX = activeIndex !== null ? xCoords[activeIndex] ?? padLeft : padLeft;
 
return (
<div className={cn(areaChartVariants({ variant }), className)} {...props}>
{(title || subtitle || showLegend) && (
<div className="mb-3 flex flex-wrap items-start justify-between gap-2">
<div>
{title && (
<div className="text-xs font-semibold tracking-tight text-fg">
{title}
</div>
)}
{subtitle && (
<div className="mt-0.5 text-[11px] text-fg-muted">{subtitle}</div>
)}
</div>
 
{showLegend && series.length > 0 && (
<div className="flex flex-wrap items-center gap-1.5">
{series.map((s, idx) => {
const color = getChartColorVar(s.colorIndex ?? idx + 1);
const hidden = hiddenKeys.has(s.key);
return (
<button
key={s.key}
type="button"
onClick={() => toggleSeries(s.key)}
aria-pressed={!hidden}
className={cn(
"inline-flex items-center gap-1.5 rounded-pill border px-2 py-0.5 text-[11px] transition-opacity cursor-pointer",
hidden
? "border-line bg-well/50 text-fg-muted opacity-50"
: "border-line bg-surface-2 text-fg-secondary hover:text-fg"
)}
>
<span
className="h-2 w-2 rounded-full"
style={{ backgroundColor: color }}
aria-hidden="true"
/>
<span>{s.label}</span>
</button>
);
})}
</div>
)}
</div>
)}
 
<div
ref={containerRef}
className="relative w-full"
onMouseLeave={() => setActiveIndex(null)}
>
<svg
ref={svgRef}
width="100%"
height={height}
viewBox={`0 0 ${width} ${height}`}
onPointerMove={handlePointerMove}
// 触屏:轻点即定位到最近数据点,抬起手指后保留读数(点击空白处清除);
// 采用 touch-pan-y 让纵向滚动页面不被图表拦截,横向滑动用于连续追踪。
onPointerDown={handlePointerMove}
onPointerLeave={(e) => {
if (e.pointerType === "mouse") setActiveIndex(null);
}}
role="img"
aria-label={title ? `${title}面积图` : "面积图"}
className="block overflow-visible cursor-crosshair touch-pan-y"
>
<defs>
{seriesGeometry.map((sg) => (
<linearGradient
key={`grad-${sg.series.key}`}
id={`area-grad-${uid}-${sg.series.key}`}
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop offset="0%" stopColor={sg.color} stopOpacity="0.28" />
<stop offset="100%" stopColor={sg.color} stopOpacity="0.01" />
</linearGradient>
))}
</defs>
 
{/* Horizontal hairline grid & Y ticks */}
{ticks.map((tick, i) => (
<g key={i}>
{showGrid && (
<line
x1={padLeft}
x2={width - padRight}
y1={tick.y}
y2={tick.y}
stroke="var(--line-subtle)"
strokeWidth="1"
strokeDasharray={i === 0 ? undefined : "2 3"}
/>
)}
<text
x={padLeft - 6}
y={tick.y + 3}
textAnchor="end"
fill="var(--fg-muted)"
className="font-mono-num text-[10px]"
>
{tick.value >= 1000
? `${(tick.value / 1000).toFixed(tick.value % 1000 === 0 ? 0 : 1)}k`
: tick.value}
</text>
</g>
))}
 
{/* Areas and lines */}
{seriesGeometry.map((sg) => (
<g key={sg.series.key}>
<motion.path
d={sg.area}
fill={`url(#area-grad-${uid}-${sg.series.key})`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
/>
<motion.path
d={sg.line}
fill="none"
stroke={sg.color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
initial={{ pathLength: 0.15, opacity: 0.4 }}
animate={{ pathLength: 1, opacity: 1 }}
transition={{ duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
/>
</g>
))}
 
{/* Spring crosshair + active dots */}
{activeIndex !== null && (
<>
<motion.line
x1={smoothGuideX}
x2={smoothGuideX}
y1={padTop}
y2={baselineY}
stroke="var(--line-strong)"
strokeWidth="1"
strokeDasharray="2 2"
/>
{seriesGeometry.map((sg) => {
const pt = sg.pts[activeIndex];
if (!pt) return null;
return (
<circle
key={`dot-${sg.series.key}`}
cx={pt.x}
cy={pt.y}
r={4}
fill="var(--bg-surface)"
stroke={sg.color}
strokeWidth="2"
/>
);
})}
</>
)}
 
{/* X-axis labels */}
{data.map((d, idx) => {
const step = data.length > 7 && width < 340 ? 2 : 1;
if (idx % step !== 0 && idx !== data.length - 1) return null;
return (
<text
key={`${d.label}-${idx}`}
x={xCoords[idx]}
y={height - 6}
textAnchor="middle"
fill={
activeIndex === idx ? "var(--fg-primary)" : "var(--fg-muted)"
}
className="font-mono-num text-[10px]"
>
{d.label}
</text>
);
})}
</svg>
 
{activeDatum && (
<div
role="status"
style={{
left: `${Math.min(Math.max(activeX, 82), Math.max(82, width - 82))}px`,
top: 4,
}}
className="pointer-events-none absolute -translate-x-1/2 rounded-[10px] border border-line-strong bg-surface/96 px-2.5 py-1.5 text-[11px] shadow-popover backdrop-blur-md"
>
<div className="mb-1 font-medium text-fg">{activeDatum.label}</div>
<div className="space-y-0.5">
{seriesGeometry.map((sg) => (
<div
key={sg.series.key}
className="flex items-center justify-between gap-3"
>
<span className="flex items-center gap-1.5 text-fg-secondary">
<span
className="h-2 w-2 rounded-full"
style={{ backgroundColor: sg.color }}
aria-hidden="true"
/>
{sg.series.label}
</span>
<span className="font-mono-num font-medium text-fg">
{valueFormatter(activeDatum.values[sg.series.key] ?? 0)}
</span>
</div>
))}
</div>
</div>
)}
</div>
</div>
);
}