components/linyi/bar-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 BarChartSeries { key: string; label: string; colorIndex?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;} export interface BarChartDatum { label: string; values: Record<string, number>;} export const barChartVariants = 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 BarChartProps extends Omit<React.ComponentPropsWithRef<"div">, "children">, VariantProps<typeof barChartVariants> { data: BarChartDatum[]; series: BarChartSeries[]; title?: string; subtitle?: string; layout?: "grouped" | "stacked"; 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})`;} export function BarChart({ data, series, title, subtitle, layout = "grouped", height = 210, showGrid = true, showLegend = true, valueFormatter = (v) => v.toLocaleString(), variant = "surface", className, ...props}: BarChartProps) { const containerRef = React.useRef<HTMLDivElement | 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 = 12; const padTop = 14; const padBottom = 26; const plotW = Math.max(120, width - padLeft - padRight); const plotH = Math.max(80, height - padTop - padBottom); const maxVal = React.useMemo(() => { let peak = 0; for (const d of data) { if (layout === "stacked") { const sum = activeSeries.reduce((acc, s) => acc + Math.max(0, d.values[s.key] ?? 0), 0); if (sum > peak) peak = sum; } else { 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, layout]); 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 groupStep = data.length > 0 ? plotW / data.length : plotW; const groupPad = Math.min(18, groupStep * 0.22); const usableGroupW = Math.max(10, groupStep - groupPad); const handleActivate = (idx: number) => { if (idx !== activeIndex) { setActiveIndex(idx); playSound("tap", { pitch: 0.94 + idx * 0.025, volume: 0.22 }); } }; const activeDatum = activeIndex !== null ? data[activeIndex] : null; const tooltipX = activeIndex !== null ? padLeft + groupStep * (activeIndex + 0.5) : 0; return ( <div className={cn(barChartVariants({ 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 width="100%" height={height} viewBox={`0 0 ${width} ${height}`} role="group" aria-label={title ? `${title}柱状图` : "柱状图"} className="block overflow-visible" > {/* Horizontal hairline grid & Y-axis 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> ))} {/* Hover band + bars */} {data.map((datum, dIdx) => { const gx = padLeft + dIdx * groupStep; const isHovered = activeIndex === dIdx; let stackAccH = 0; return ( <g key={datum.label} tabIndex={0} role="button" aria-label={`${datum.label}:${activeSeries .map((s) => `${s.label} ${valueFormatter(datum.values[s.key] ?? 0)}`) .join(",")}`} onMouseEnter={() => handleActivate(dIdx)} onClick={() => handleActivate(dIdx)} onFocus={() => handleActivate(dIdx)} onBlur={() => setActiveIndex(null)} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); handleActivate(dIdx); } else if (e.key === "Escape") { setActiveIndex(null); } }} className="cursor-pointer outline-none" > <rect x={gx + 2} y={padTop} width={Math.max(4, groupStep - 4)} height={plotH} rx={6} fill={isHovered ? "var(--bg-well)" : "transparent"} fillOpacity={isHovered ? 0.65 : 0} /> {layout === "stacked" ? activeSeries.map((s, sIdx) => { const val = Math.max(0, datum.values[s.key] ?? 0); const barH = (val / maxVal) * plotH; const barW = Math.min(34, usableGroupW); const bx = gx + (groupStep - barW) / 2; const by = padTop + plotH - stackAccH - barH; stackAccH += barH; const color = getChartColorVar( s.colorIndex ?? series.findIndex((x) => x.key === s.key) + 1 ); return ( <motion.rect key={`${datum.label}-${s.key}`} x={bx} y={by} width={barW} height={Math.max(0, barH)} rx={sIdx === activeSeries.length - 1 ? 4 : 1} fill={color} fillOpacity={ activeIndex === null || isHovered ? 0.92 : 0.45 } style={{ transformOrigin: `${bx + barW / 2}px ${padTop + plotH}px` }} initial={{ scaleY: 0 }} animate={{ scaleY: 1 }} transition={{ ...EASE_OUT, delay: dIdx * 0.025 }} /> ); }) : activeSeries.map((s, sIdx) => { const val = Math.max(0, datum.values[s.key] ?? 0); const barH = (val / maxVal) * plotH; const gap = activeSeries.length > 1 ? 3 : 0; const singleW = Math.min( 24, Math.max( 4, (usableGroupW - gap * (activeSeries.length - 1)) / Math.max(1, activeSeries.length) ) ); const totalBarsW = singleW * activeSeries.length + gap * Math.max(0, activeSeries.length - 1); const startX = gx + (groupStep - totalBarsW) / 2; const bx = startX + sIdx * (singleW + gap); const by = padTop + plotH - barH; const color = getChartColorVar( s.colorIndex ?? series.findIndex((x) => x.key === s.key) + 1 ); return ( <motion.rect key={`${datum.label}-${s.key}`} x={bx} y={by} width={singleW} height={Math.max(0, barH)} rx={4} fill={color} fillOpacity={ activeIndex === null || isHovered ? 0.94 : 0.45 } style={{ transformOrigin: `${bx + singleW / 2}px ${padTop + plotH}px` }} initial={{ scaleY: 0 }} animate={{ scaleY: 1 }} transition={{ ...EASE_OUT, delay: dIdx * 0.025 + sIdx * 0.015 }} /> ); })} {/* X-axis label */} <text x={gx + groupStep / 2} y={height - 6} textAnchor="middle" fill={isHovered ? "var(--fg-primary)" : "var(--fg-muted)"} className="font-mono-num text-[10px]" > {datum.label} </text> </g> ); })} </svg> {/* Floating tooltip */} {activeDatum && ( <div role="status" style={{ left: `${Math.min(Math.max(tooltipX, 80), Math.max(80, width - 80))}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"> {activeSeries.map((s) => { const color = getChartColorVar( s.colorIndex ?? series.findIndex((x) => x.key === s.key) + 1 ); return ( <div key={s.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: color }} aria-hidden="true" /> {s.label} </span> <span className="font-mono-num font-medium text-fg"> {valueFormatter(activeDatum.values[s.key] ?? 0)} </span> </div> ); })} </div> </div> )} </div> </div> );}