import { useMemo } from 'react'; import type { Node } from '../types'; import { computeSlices } from '../slices'; import { formatSize, percent } from '../format'; interface DonutChartProps { children: Node[]; apparent: boolean; useSIPrefix: boolean; hoveredPath: string | null; onHover: (path: string | null) => void; onSelect: (node: Node) => void; } const SIZE = 240; const CENTER = SIZE / 2; const RADIUS = 90; const STROKE = 34; const CIRCUMFERENCE = 2 * Math.PI * RADIUS; export function DonutChart({ children, apparent, useSIPrefix, hoveredPath, onHover, onSelect, }: DonutChartProps) { const { slices, total } = useMemo( () => computeSlices(children, apparent), [children, apparent], ); const hovered = slices.find((s) => s.node?.path === hoveredPath) ?? null; const centerPrimary = hovered ? hovered.label : formatSize(total, useSIPrefix); const centerSecondary = hovered ? `${formatSize(hovered.value, useSIPrefix)} ยท ${percent(hovered.value, total).toFixed(1)}%` : `${slices.length} item${slices.length === 1 ? '' : 's'}`; let offsetFraction = 0; return (
{total > 0 && slices.map((slice) => { const fraction = slice.value / total; const dash = fraction * CIRCUMFERENCE; const dashOffset = -offsetFraction * CIRCUMFERENCE; offsetFraction += fraction; const key = slice.node ? slice.node.path : '__other__'; const isHovered = hoveredPath !== null && slice.node?.path === hoveredPath; const dimmed = hoveredPath !== null && !isHovered; const clickable = slice.node?.isDir ?? false; return ( slice.node && onHover(slice.node.path)} onMouseLeave={() => onHover(null)} onClick={() => { if (slice.node && slice.node.isDir) { onSelect(slice.node); } }} /> ); })}
{centerPrimary}
{centerSecondary}
); }