{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "donut-chart",
  "title": "Donut Chart",
  "description": "Parts of a whole as a ring with the total in the middle and a keyboard-navigable legend of values and shares.",
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/use-entrance"
  ],
  "files": [
    {
      "path": "registry/default/ui/donut-chart.tsx",
      "content": "\"use client\";\n\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type KeyboardEvent,\n  type PointerEvent,\n  type ReactNode,\n} from \"react\";\n\nimport { useEntrance } from \"@/registry/default/hooks/use-entrance\";\nimport { cn } from \"@/registry/default/lib/utils\";\n\n// Size of the drawing until the browser has measured it, in px.\nconst SIZE = 200;\n// Space between segments, in px along the ring.\nconst GAP = 2;\nconst DRAW = \"cubic-bezier(0.65, 0, 0.35, 1)\";\n\nconst n = (value: number) => Math.round(value * 100) / 100;\n\n/**\n * The default colour of segment `index` out of `count`: the primary colour\n * for the first, then the primary colour mixed with the background, lighter\n * for each segment down to 30%.\n */\nfunction defaultColor(index: number, count: number) {\n  if (index === 0) return \"var(--primary)\";\n  const share = Math.round(100 - (index / Math.max(count - 1, 1)) * 70);\n  return `color-mix(in oklab, var(--primary) ${share}%, var(--background))`;\n}\n\ninterface DonutChartItem {\n  /** Name of the part, shown in the legend. */\n  label: string;\n  /** Its size. Negative values count as 0. */\n  value: number;\n  /** Segment colour; any CSS colour. See `DonutChart` for the defaults. */\n  color?: string;\n}\n\ninterface DonutChartProps extends Omit<ComponentProps<\"div\">, \"children\"> {\n  /** The parts of the whole, drawn clockwise from the top. */\n  data: DonutChartItem[];\n  /** Name of the chart, used as the accessible name of the legend. */\n  name?: string;\n  /** Width of the ring, in px. */\n  thickness?: number;\n  /** Shown small in the hole. Defaults to the highlighted part's label, or `totalLabel`. */\n  centerLabel?: ReactNode;\n  /** Shown large in the hole. Defaults to the highlighted part's value, or the total. */\n  centerValue?: ReactNode;\n  /** Label for the total in the hole. */\n  totalLabel?: string;\n  /**\n   * Locale and options for the numbers, as in `Intl.NumberFormat`. Both can\n   * be passed from a server component; a fixed default keeps the server and\n   * the browser in agreement.\n   */\n  locale?: string;\n  numberFormat?: Intl.NumberFormatOptions;\n  /** Options for the percentages in the legend, as in `Intl.NumberFormat`. */\n  percentFormat?: Intl.NumberFormatOptions;\n  /**\n   * Formats values in the legend and the hole; overrides `locale` and\n   * `numberFormat`. `index` is -1 for the total.\n   */\n  formatValue?: (value: number, index: number) => ReactNode;\n  /** The part highlighted at first. Defaults to none. */\n  defaultIndex?: number;\n  /** Called when the highlighted part changes, by pointer or keyboard; `null` when none is. */\n  onIndexChange?: (index: number | null) => void;\n  /** Sweep the segments in the first time the chart comes into view. */\n  animated?: boolean;\n}\n\n/**\n * A donut chart for the parts of a whole, with a legend listing each part's\n * value and share. The ring is decorative; the legend carries the data. Each\n * legend entry is a toggle button that highlights its segment: Tab reaches\n * the list, the arrow keys, Home and End move between entries, Enter or\n * Space pins one and Escape clears it. Hovering a segment or an entry\n * highlights it too, dims the rest and shows its value in the hole, which\n * otherwise shows the total. The segments sweep in the first time the chart\n * scrolls into view; with `prefers-reduced-motion` they are simply shown.\n *\n * Parts without a `color` get the primary colour, then lighter mixes of it\n * with the background, so the chart follows the theme; pass colours to tell\n * many parts apart.\n *\n * @example\n * <DonutChart\n *   name=\"Cargo by hold\"\n *   data={[\n *     { label: \"Fore\", value: 42 },\n *     { label: \"Main\", value: 31 },\n *     { label: \"Aft\", value: 18 },\n *   ]}\n * />\n */\nfunction DonutChart({\n  data,\n  name,\n  thickness = 24,\n  centerLabel,\n  centerValue,\n  totalLabel = \"Total\",\n  locale = \"en-US\",\n  numberFormat,\n  percentFormat,\n  formatValue,\n  defaultIndex,\n  onIndexChange,\n  animated = true,\n  className,\n  \"aria-label\": ariaLabel,\n  ...props\n}: DonutChartProps) {\n  const id = useId().replace(/[^\\w-]/g, \"\");\n  const [box, setBox] = useState<HTMLDivElement | null>(null);\n  const [size, setSize] = useState(SIZE);\n  const [pinned, setPinned] = useState<number | null>(defaultIndex ?? null);\n  const [hovered, setHovered] = useState<number | null>(null);\n  const buttons = useRef<(HTMLButtonElement | null)[]>([]);\n  const [observe, phase] = useEntrance<HTMLDivElement>({ play: animated ? undefined : true });\n  const entrance = animated ? phase : \"static\";\n\n  const boxRef = useCallback(\n    (node: HTMLDivElement | null) => {\n      setBox(node);\n      observe(node);\n    },\n    [observe]\n  );\n\n  useEffect(() => {\n    if (!box || typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(([entry]) => {\n      if (entry?.contentRect.width) setSize(entry.contentRect.width);\n    });\n    observer.observe(box);\n    return () => observer.disconnect();\n  }, [box]);\n\n  const ring = Math.max(1, Math.min(thickness, size / 2 - 1));\n  const radius = (size - ring) / 2;\n  const circumference = 2 * Math.PI * radius;\n\n  const segments = useMemo(() => {\n    const values = data.map((item) => Math.max(0, item.value));\n    const total = values.reduce((sum, value) => sum + value, 0);\n    const shown = values.filter((value) => value > 0).length;\n    const shares = values.map((value) => (total ? value / total : 0));\n    // Where each segment ends, as a fraction of the ring.\n    const ends = shares.map((_, index) =>\n      shares.slice(0, index + 1).reduce((sum, share) => sum + share, 0)\n    );\n    return {\n      total,\n      items: data.map((item, index) => {\n        const share = shares[index]!;\n        const from = ends[index]! - share;\n        return {\n          label: item.label,\n          value: values[index]!,\n          color: item.color ?? defaultColor(index, data.length),\n          share,\n          from,\n          to: ends[index]!,\n          // Leave a gap between segments, never more than the segment itself.\n          length: Math.max(0, share * circumference - (shown > 1 ? GAP : 0)),\n          offset: from * circumference,\n        };\n      }),\n    };\n  }, [data, circumference]);\n\n  const numbers = useMemo(\n    () => new Intl.NumberFormat(locale, numberFormat),\n    [locale, numberFormat]\n  );\n  const percents = useMemo(\n    () =>\n      new Intl.NumberFormat(\n        locale,\n        percentFormat ?? { style: \"percent\", maximumFractionDigits: 1 }\n      ),\n    [locale, percentFormat]\n  );\n\n  if (data.length === 0) return null;\n\n  const clamp = (index: number | null) =>\n    index === null ? null : Math.min(Math.max(index, 0), data.length - 1);\n  const active = clamp(hovered ?? pinned);\n  const update = (nextPinned: number | null, nextHovered: number | null) => {\n    const next = clamp(nextHovered ?? nextPinned);\n    setPinned(nextPinned);\n    setHovered(nextHovered);\n    if (next !== active) onIndexChange?.(next);\n  };\n\n  const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {\n    const rect = event.currentTarget.getBoundingClientRect();\n    if (rect.width === 0 || segments.total === 0) return;\n    const scale = rect.width / size;\n    const dx = event.clientX - (rect.left + rect.width / 2);\n    const dy = event.clientY - (rect.top + rect.height / 2);\n    const distance = Math.hypot(dx, dy) / scale;\n    if (distance < radius - ring / 2 || distance > radius + ring / 2) {\n      if (hovered !== null) update(pinned, null);\n      return;\n    }\n    // Clockwise from the top, from 0 to 1.\n    const turn = (Math.atan2(dx, -dy) / (2 * Math.PI) + 1) % 1;\n    const index = segments.items.findIndex((item) => item.share > 0 && turn < item.to);\n    const next = index === -1 ? null : index;\n    if (next !== hovered) update(pinned, next);\n  };\n\n  const format = (value: number, index: number) =>\n    formatValue ? formatValue(value, index) : numbers.format(value);\n\n  const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {\n    if (event.key === \"Escape\") {\n      if (pinned === null) return;\n      event.preventDefault();\n      update(null, hovered);\n      return;\n    }\n    const moves: Record<string, number> = {\n      ArrowUp: index - 1,\n      ArrowLeft: index - 1,\n      ArrowDown: index + 1,\n      ArrowRight: index + 1,\n      Home: 0,\n      End: data.length - 1,\n    };\n    const move = moves[event.key];\n    if (move === undefined) return;\n    event.preventDefault();\n    const next = clamp(move)!;\n    buttons.current[next]?.focus();\n    update(next, hovered);\n  };\n\n  const focusable = clamp(pinned) ?? 0;\n  const highlighted = active === null ? null : segments.items[active]!;\n  const center = size / 2;\n\n  return (\n    <div\n      data-slot=\"donut-chart\"\n      className={cn(\"grid w-full items-center gap-6 sm:grid-cols-[minmax(0,14rem)_1fr]\", className)}\n      {...props}\n    >\n      <div\n        ref={boxRef}\n        data-slot=\"donut-chart-ring\"\n        data-state={entrance}\n        className=\"relative mx-auto aspect-square w-full max-w-56\"\n        onPointerMove={onPointerMove}\n        onPointerLeave={() => {\n          if (hovered !== null) update(pinned, null);\n        }}\n      >\n        <svg\n          aria-hidden=\"true\"\n          viewBox={`0 0 ${n(size)} ${n(size)}`}\n          className=\"absolute inset-0 size-full\"\n          fill=\"none\"\n        >\n          <defs>\n            <mask\n              id={`${id}-draw`}\n              maskUnits=\"userSpaceOnUse\"\n              x={0}\n              y={0}\n              width={n(size)}\n              height={n(size)}\n            >\n              <circle\n                cx={n(center)}\n                cy={n(center)}\n                r={n(radius)}\n                stroke=\"white\"\n                strokeWidth={n(ring + 4)}\n                strokeDasharray={`${n(circumference)} ${n(circumference)}`}\n                className=\"motion-reduce:!transition-none motion-reduce:![stroke-dashoffset:0]\"\n                style={{\n                  strokeDashoffset: entrance === \"armed\" ? n(circumference) : 0,\n                  transition: entrance === \"play\" ? `stroke-dashoffset 900ms ${DRAW}` : undefined,\n                }}\n              />\n            </mask>\n          </defs>\n          <g transform={`rotate(-90 ${n(center)} ${n(center)})`} mask={`url(#${id}-draw)`}>\n            {segments.total === 0 ? (\n              <circle\n                data-slot=\"donut-chart-track\"\n                cx={n(center)}\n                cy={n(center)}\n                r={n(radius)}\n                stroke=\"var(--muted)\"\n                strokeWidth={n(ring)}\n              />\n            ) : null}\n            {segments.items.map((item, at) =>\n              item.length > 0 ? (\n                <circle\n                  key={at}\n                  data-slot=\"donut-chart-segment\"\n                  data-active={active === at ? \"\" : undefined}\n                  data-dimmed={active !== null && active !== at ? \"\" : undefined}\n                  cx={n(center)}\n                  cy={n(center)}\n                  r={n(radius)}\n                  stroke={item.color}\n                  strokeWidth={n(ring)}\n                  strokeDasharray={`${n(item.length)} ${n(circumference - item.length)}`}\n                  strokeDashoffset={n(-item.offset)}\n                  className=\"transition-opacity data-[dimmed]:opacity-40 motion-reduce:transition-none\"\n                />\n              ) : null\n            )}\n          </g>\n        </svg>\n\n        <div\n          data-slot=\"donut-chart-center\"\n          className=\"pointer-events-none absolute inset-0 flex flex-col items-center justify-center text-center\"\n          style={{ padding: ring + 8 }}\n        >\n          <span className=\"text-muted-foreground max-w-full truncate text-xs\">\n            {centerLabel ?? highlighted?.label ?? totalLabel}\n          </span>{\" \"}\n          <span className=\"font-mono text-2xl font-semibold tabular-nums\">\n            {centerValue ??\n              (highlighted\n                ? format(highlighted.value, active!)\n                : formatValue\n                  ? formatValue(segments.total, -1)\n                  : numbers.format(segments.total))}\n          </span>\n        </div>\n      </div>\n\n      <ul\n        aria-label={ariaLabel ?? name}\n        data-slot=\"donut-chart-legend\"\n        className=\"grid min-w-0 gap-0.5\"\n      >\n        {segments.items.map((item, at) => (\n          <li key={at} data-slot=\"donut-chart-legend-item\">\n            <button\n              ref={(node) => {\n                buttons.current[at] = node;\n              }}\n              type=\"button\"\n              tabIndex={at === focusable ? 0 : -1}\n              aria-pressed={pinned === at}\n              data-active={active === at ? \"\" : undefined}\n              data-slot=\"donut-chart-legend-button\"\n              className=\"hover:bg-accent data-[active]:bg-accent focus-visible:ring-ring/50 flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm outline-none focus-visible:ring-[3px]\"\n              onClick={() => update(pinned === at ? null : at, hovered)}\n              onKeyDown={(event) => onKeyDown(event, at)}\n              onPointerEnter={() => update(pinned, at)}\n              onPointerLeave={() => update(pinned, null)}\n            >\n              <span\n                aria-hidden=\"true\"\n                className=\"size-2.5 shrink-0 rounded-[3px]\"\n                style={{ backgroundColor: item.color }}\n              />\n              {/* The spaces keep the accessible name apart: \"Fore 50 50%\". Flex layout drops them. */}\n              <span className=\"min-w-0 flex-1 truncate\">{item.label}</span>{\" \"}\n              <span className=\"font-mono font-medium tabular-nums\">{format(item.value, at)}</span>{\" \"}\n              <span className=\"text-muted-foreground w-12 text-right font-mono text-xs tabular-nums\">\n                {percents.format(item.share)}\n              </span>\n            </button>\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n\nexport { DonutChart, type DonutChartItem, type DonutChartProps };\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}