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

交互走势微图表

FreeRegistry
components/linyi/sparkline-chart.tsx
motion
"use client";
 
import * as React from "react";
import { motion, useMotionValue, useSpring } from "motion/react";
import { cn } from "@/lib/cn";
import { SPRING_PROGRESS, SPRING_SNAPPY } from "@/lib/motion";
import { playSound } from "@/lib/sound";
 
export type ChartPeriod = "7d" | "30d" | "90d";
 
interface DataPoint {
label: string;
value: number;
}
 
const SERIES: Record<ChartPeriod, { delta: string; data: DataPoint[] }> = {
"7d": {
delta: "+14.2%",
data: [
{ label: "周一", value: 1240 },
{ label: "周二", value: 1410 },
{ label: "周三", value: 1360 },
{ label: "周四", value: 1580 },
{ label: "周五", value: 1790 },
{ label: "周六", value: 1710 },
{ label: "周日", value: 1940 },
],
},
"30d": {
delta: "+28.6%",
data: [
{ label: "第 1 周", value: 1120 },
{ label: "第 5 天", value: 1290 },
{ label: "第 9 天", value: 1250 },
{ label: "第 13 天", value: 1490 },
{ label: "第 17 天", value: 1620 },
{ label: "第 21 天", value: 1560 },
{ label: "第 25 天", value: 1890 },
{ label: "第 28 天", value: 2140 },
{ label: "今日", value: 2380 },
],
},
"90d": {
delta: "+62.4%",
data: [
{ label: "9 月", value: 980 },
{ label: "9 月中", value: 1180 },
{ label: "10 月", value: 1410 },
{ label: "10 月中", value: 1350 },
{ label: "11 月", value: 1760 },
{ label: "11 月中", value: 2120 },
{ label: "本月", value: 2640 },
],
},
};
 
const W = 280;
const H = 104;
const PAD_X = 8;
const PAD_Y = 12;
 
function buildPaths(points: { x: number; y: number }[]) {
if (!points.length) return { line: "", area: "" };
let line = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
for (let i = 0; i < points.length - 1; i++) {
const p0 = points[i];
const p1 = points[i + 1];
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)}`;
}
const last = points[points.length - 1];
const area = `${line} L ${last.x.toFixed(1)} ${H} L ${points[0].x.toFixed(1)} ${H} Z`;
return { line, area };
}
 
export interface SparklineChartProps {
defaultPeriod?: ChartPeriod;
title?: string;
compact?: boolean;
className?: string;
}
 
export function SparklineChart({
defaultPeriod = "30d",
title = "CLI 安装趋势",
compact = false,
className,
}: SparklineChartProps) {
const uid = React.useId().replace(/:/g, "");
const [period, setPeriod] = React.useState<ChartPeriod>(defaultPeriod);
const [activeIdx, setActiveIdx] = React.useState<number | null>(null);
const svgRef = React.useRef<SVGSVGElement>(null);
 
React.useEffect(() => {
setPeriod(defaultPeriod);
setActiveIdx(null);
}, [defaultPeriod]);
 
const series = SERIES[period];
const values = series.data.map((d) => d.value);
const minVal = Math.min(...values) * 0.92;
const maxVal = Math.max(...values) * 1.04;
 
const coords = React.useMemo(() => {
const count = series.data.length;
return series.data.map((d, idx) => {
const x = PAD_X + (idx / Math.max(1, count - 1)) * (W - PAD_X * 2);
const ratio = (d.value - minVal) / Math.max(1, maxVal - minVal);
const y = H - PAD_Y - ratio * (H - PAD_Y * 2);
return { x, y, ...d };
});
}, [series.data, minVal, maxVal]);
 
const { line, area } = React.useMemo(() => buildPaths(coords), [coords]);
const current = coords[activeIdx ?? coords.length - 1];
 
const dotX = useMotionValue(current.x);
const dotY = useMotionValue(current.y);
const smoothX = useSpring(dotX, SPRING_PROGRESS);
const smoothY = useSpring(dotY, SPRING_PROGRESS);
 
React.useEffect(() => {
dotX.set(current.x);
dotY.set(current.y);
}, [current.x, current.y, dotX, dotY]);
 
const handlePointerMove = (e: React.PointerEvent<SVGSVGElement>) => {
const rect = svgRef.current?.getBoundingClientRect();
if (!rect || rect.width <= 0) return;
const relX = ((e.clientX - rect.left) / rect.width) * W;
let nearest = 0;
let bestDist = Infinity;
for (let i = 0; i < coords.length; i++) {
const d = Math.abs(coords[i].x - relX);
if (d < bestDist) {
bestDist = d;
nearest = i;
}
}
if (nearest !== activeIdx) {
setActiveIdx(nearest);
playSound("tap", { pitch: 0.92 + nearest * 0.035, volume: 0.28 });
}
};
 
return (
<div
className={cn(
"w-full rounded-[14px] border border-line bg-surface p-3.5 select-none",
compact ? "max-w-[260px]" : "max-w-[340px]",
className
)}
>
<div className="flex items-start justify-between gap-2">
<div>
<div className="text-[11px] text-fg-muted">{title}</div>
<div className="mt-0.5 flex items-baseline gap-2">
<span className="font-mono-num text-lg font-semibold tracking-tight text-fg">
{current.value.toLocaleString()}
</span>
<span
className="rounded-full px-1.5 py-0.5 font-mono-num text-[10px] font-medium"
style={{
background: "var(--status-success-soft)",
color: "var(--status-success)",
}}
>
{activeIdx !== null ? current.label : series.delta}
</span>
</div>
</div>
 
<div
className="inline-flex rounded-full p-0.5"
style={{
background: "var(--bg-well)",
border: "1px solid var(--line-subtle)",
}}
>
{(["7d", "30d", "90d"] as const).map((p) => {
const selected = period === p;
return (
<button
key={p}
type="button"
onClick={() => {
playSound("tap", { volume: 0.45 });
setPeriod(p);
setActiveIdx(null);
}}
className="relative px-2 py-0.5 font-mono-num text-[10px] uppercase cursor-pointer rounded-full transition-colors"
style={{ color: selected ? "var(--fg-primary)" : "var(--fg-muted)" }}
>
{selected && (
<motion.span
layoutId={`spark-period-${uid}`}
transition={SPRING_SNAPPY}
className="absolute inset-0 rounded-full"
style={{
background: "var(--bg-surface)",
border: "1px solid var(--line-subtle)",
}}
/>
)}
<span className="relative z-10">{p}</span>
</button>
);
})}
</div>
</div>
 
<div className="mt-2.5">
<svg
ref={svgRef}
viewBox={`0 0 ${W} ${H}`}
onPointerMove={handlePointerMove}
// 触屏:轻点即定位到最近数据点,抬起手指后保留读数(点击空白处清除);
// 采用 touch-pan-y 让纵向滚动页面不被图表拦截,横向滑动用于连续追踪。
onPointerDown={handlePointerMove}
onPointerLeave={(e) => {
if (e.pointerType === "mouse") setActiveIdx(null);
}}
className="h-[88px] w-full overflow-visible cursor-crosshair touch-pan-y"
role="img"
aria-label={`${title} 走势图`}
>
<defs>
<linearGradient id={`spark-fill-${uid}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="var(--accent)" stopOpacity="0.24" />
<stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
</linearGradient>
</defs>
 
{/* Area fill */}
<motion.path
key={`area-${period}`}
d={area}
fill={`url(#spark-fill-${uid})`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
/>
 
{/* Smooth curve */}
<motion.path
key={`line-${period}`}
d={line}
fill="none"
stroke="var(--accent)"
strokeWidth="2"
strokeLinecap="round"
initial={{ pathLength: 0.2, opacity: 0.4 }}
animate={{ pathLength: 1, opacity: 1 }}
transition={{ duration: 0.48, ease: [0.16, 1, 0.3, 1] }}
/>
 
{/* Crosshair guide */}
<motion.line
x1={smoothX}
x2={smoothX}
y1={PAD_Y - 4}
y2={H}
stroke="var(--line-strong)"
strokeWidth="1"
strokeDasharray="2 2"
/>
 
{/* Spring-tracked focal point */}
<motion.circle
cx={smoothX}
cy={smoothY}
r={activeIdx !== null ? 5 : 3.5}
fill="var(--bg-surface)"
stroke="var(--accent)"
strokeWidth="2"
/>
</svg>
</div>
</div>
);
}