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

交互环形图

FreeRegistry
components/linyi/donut-chart.tsx
motionclass-variance-authority
"use client";
 
import * as React from "react";
import { motion } from "motion/react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/cn";
import { EASE_OUT } from "@/lib/motion";
import { playSound } from "@/lib/sound";
 
export interface DonutChartSegment {
id: string;
label: string;
value: number;
colorIndex?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
}
 
export const donutChartVariants = 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 DonutChartProps
extends Omit<React.ComponentPropsWithRef<"div">, "children">,
VariantProps<typeof donutChartVariants> {
data: DonutChartSegment[];
title?: string;
subtitle?: string;
totalLabel?: string;
size?: number;
thickness?: number;
showLegend?: boolean;
valueFormatter?: (value: number) => string;
}
 
function getChartColorVar(index: number): string {
const safe = ((index - 1) % 8) + 1;
return `var(--chart-${safe})`;
}
 
export function DonutChart({
data,
title,
subtitle,
totalLabel = "总计",
size = 164,
thickness = 20,
showLegend = true,
valueFormatter = (v) => v.toLocaleString(),
variant = "surface",
className,
...props
}: DonutChartProps) {
const [activeId, setActiveId] = React.useState<string | null>(null);
 
const total = React.useMemo(
() => data.reduce((acc, item) => acc + Math.max(0, item.value), 0),
[data]
);
 
const clampedThickness = Math.max(8, Math.min(thickness, size / 3));
const radius = (size - clampedThickness) / 2 - 4;
const circumference = 2 * Math.PI * radius;
const gapPx = data.length > 1 ? 3 : 0;
 
const segments = React.useMemo(() => {
let offset = 0;
return data.map((item, idx) => {
const val = Math.max(0, item.value);
const ratio = total > 0 ? val / total : 0;
const rawLen = ratio * circumference;
const segLen = Math.max(0, rawLen - gapPx);
const startOffset = offset;
offset += rawLen;
return {
...item,
ratio,
percent: (ratio * 100).toFixed(1),
segLen,
dashOffset: -startOffset,
color: getChartColorVar(item.colorIndex ?? idx + 1),
};
});
}, [data, total, circumference, gapPx]);
 
const activeSeg = segments.find((s) => s.id === activeId) ?? null;
 
const activate = (id: string, idx: number) => {
if (id !== activeId) {
setActiveId(id);
playSound("tap", { pitch: 0.94 + idx * 0.03, volume: 0.22 });
}
};
 
return (
<div className={cn(donutChartVariants({ variant }), className)} {...props}>
{(title || subtitle) && (
<div className="mb-3">
{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>
)}
 
<div
className="flex flex-col items-center gap-4 sm:flex-row sm:items-center"
onMouseLeave={() => setActiveId(null)}
>
{/* Ring SVG */}
<div
className="relative flex-shrink-0"
style={{ width: size, height: size }}
>
<svg
width={size}
height={size}
viewBox={`0 0 ${size} ${size}`}
role="group"
aria-label={title ? `${title}环形图` : "环形图"}
className="-rotate-90 overflow-visible"
>
{/* Track */}
<circle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
stroke="var(--bg-well)"
strokeWidth={clampedThickness}
/>
 
{segments.map((seg, idx) => {
const isActive = activeId === seg.id;
const isDimmed = activeId !== null && !isActive;
return (
<motion.circle
key={seg.id}
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
stroke={seg.color}
strokeWidth={isActive ? clampedThickness + 3 : clampedThickness}
strokeLinecap="butt"
strokeDasharray={`${seg.segLen} ${circumference}`}
strokeDashoffset={seg.dashOffset}
initial={{ opacity: 0 }}
animate={{ opacity: isDimmed ? 0.35 : 1 }}
transition={EASE_OUT}
tabIndex={0}
role="button"
aria-label={`${seg.label}:${valueFormatter(seg.value)}(${seg.percent}%)`}
onMouseEnter={() => activate(seg.id, idx)}
onClick={() => activate(seg.id, idx)}
onFocus={() => activate(seg.id, idx)}
onBlur={() => setActiveId(null)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
activate(seg.id, idx);
} else if (e.key === "Escape") {
setActiveId(null);
}
}}
className="cursor-pointer outline-none"
/>
);
})}
</svg>
 
{/* Center summary */}
<div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center px-3 text-center">
<span className="truncate max-w-full text-[11px] text-fg-muted">
{activeSeg ? activeSeg.label : totalLabel}
</span>
<span className="mt-0.5 font-mono-num text-base font-semibold tracking-tight text-fg">
{activeSeg ? valueFormatter(activeSeg.value) : valueFormatter(total)}
</span>
<span className="font-mono-num text-[10px] text-fg-secondary">
{activeSeg ? `${activeSeg.percent}%` : `${segments.length} 项分类`}
</span>
</div>
</div>
 
{/* Interactive legend */}
{showLegend && (
<div className="w-full min-w-0 flex-1 space-y-1">
{segments.map((seg, idx) => {
const isActive = activeId === seg.id;
return (
<button
key={seg.id}
type="button"
aria-pressed={isActive}
onMouseEnter={() => activate(seg.id, idx)}
onClick={() => setActiveId(isActive ? null : seg.id)}
onFocus={() => activate(seg.id, idx)}
onBlur={() => setActiveId(null)}
className={cn(
"flex w-full items-center justify-between gap-2 rounded-[8px] px-2 py-1.5 text-left text-xs transition-colors cursor-pointer outline-none",
"focus-visible:ring-2 focus-visible:ring-accent/30",
isActive ? "bg-well text-fg" : "text-fg-secondary hover:bg-well/60"
)}
>
<span className="flex min-w-0 items-center gap-2">
<span
className="h-2.5 w-2.5 flex-shrink-0 rounded-full"
style={{ backgroundColor: seg.color }}
aria-hidden="true"
/>
<span className="truncate font-medium text-fg">
{seg.label}
</span>
</span>
<span className="flex flex-shrink-0 items-center gap-2 font-mono-num text-[11px]">
<span className="text-fg">{valueFormatter(seg.value)}</span>
<span className="w-10 text-right text-fg-muted">
{seg.percent}%
</span>
</span>
</button>
);
})}
</div>
)}
</div>
</div>
);
}