{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "donut-chart",
  "type": "registry:component",
  "title": "Donut Chart",
  "description": "A ring showing how one whole splits into at most five parts, with a label in the centre and each part's value and share in the legend.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-shape"
  ],
  "devDependencies": [
    "@types/d3-shape"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/donut-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/donut-chart.tsx",
      "content": "\"use client\";\n/**\n * @name donut-chart\n * @category viz\n * @description A ring showing how one whole splits into at most five parts, with a label in the centre and each part's value and share in the legend.\n * @when Parts of a whole at a glance, when there are few parts and they differ clearly. To compare parts that are close in size, or more than five, use bar-chart with `orientation=\"horizontal\"`; for one ratio against a limit use radial-progress.\n * @example\n * <DonutChart\n *   label=\"Traffic by source\"\n *   data={[\n *     { source: \"Search\", visits: 5200 },\n *     { source: \"Direct\", visits: 3100 },\n *     { source: \"Referral\", visits: 1400 },\n *   ]}\n *   name=\"source\"\n *   value=\"visits\"\n *   centerLabel=\"Visits\"\n * />\n */\nimport { arc as arcShape, pie as pieLayout } from \"d3-shape\";\nimport { useMemo, useState, type ComponentProps, type KeyboardEvent, type ReactNode } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { ChartContainer, ChartLegend, chartSeries, ChartSvg, ChartTooltip, formatNumber, readNumber, type ChartFormat } from \"@/components/viz/chart\";\n\nexport type DonutChartProps<T extends object> = Omit<ComponentProps<\"div\">, \"children\"> &\n  Omit<ChartFormat, \"timeZone\"> & {\n    /** One object per part. Parts that are zero, negative or missing are left out. */\n    data: readonly T[];\n    /** The field that names the part. */\n    name: keyof T & string;\n    /** The field that holds its amount. */\n    value: keyof T & string;\n    /** What the chart shows, for assistive technology. */\n    label: string;\n    /** The word under the total in the centre. */\n    centerLabel?: string;\n    /** Replaces the centre (the total and `centerLabel`) with your own content. */\n    children?: ReactNode;\n    /** The name of the slice that the smallest parts are folded into when there are more than five. */\n    otherLabel?: string;\n    /** The legend lists every part with its value and share. Default true. */\n    showLegend?: boolean;\n  };\n\ntype Slice = { name: string; value: number; index: number };\n\n/** More slices than this cannot be told apart; the rest become \"Other\". */\nconst MAX_SLICES = 5;\n/** The space between slices, in pixels: background showing through, so neighbours separate without colour. */\nconst GAP = 2;\n\nexport function DonutChart<T extends object>({\n  data,\n  name,\n  value,\n  label,\n  centerLabel = \"Total\",\n  children,\n  otherLabel = \"Other\",\n  showLegend = true,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: DonutChartProps<T>) {\n  const [active, setActive] = useState<number | null>(null);\n  const [keyboard, setKeyboard] = useState(false);\n\n  const { slices, total } = useMemo(() => {\n    const parts = data.flatMap((row) => {\n      const amount = readNumber(row, value);\n      return amount !== null && amount > 0 ? [{ name: String((row as Record<string, unknown>)[name] ?? \"\"), value: amount }] : [];\n    });\n    let kept: Slice[];\n    if (parts.length <= MAX_SLICES) {\n      kept = parts.map((part, index) => ({ ...part, index }));\n    } else {\n      // Keep the four largest, in the order they were given, and fold the rest into one neutral slice.\n      const largest = new Set([...parts].sort((a, b) => b.value - a.value).slice(0, MAX_SLICES - 1));\n      kept = parts.filter((part) => largest.has(part)).map((part, index) => ({ ...part, index }));\n      const rest = parts.filter((part) => !largest.has(part)).reduce((sum, part) => sum + part.value, 0);\n      kept.push({ name: otherLabel, value: rest, index: -1 });\n    }\n    return { slices: kept, total: kept.reduce((sum, slice) => sum + slice.value, 0) };\n  }, [data, name, value, otherLabel]);\n\n  const number = formatValue ?? ((amount: number) => formatNumber(amount, locale));\n  const share = (amount: number): string => formatNumber(total > 0 ? amount / total : 0, locale, { style: \"percent\", maximumFractionDigits: 0 });\n  const table = { caption: label, columns: [name, value, \"Share\"], rows: slices.map((slice) => [slice.name, number(slice.value), share(slice.value)]) };\n  const current = active === null ? undefined : slices[active];\n  const announcement = keyboard && current ? `${current.name}: ${number(current.value)}, ${share(current.value)}` : \"\";\n\n  const move = (step: number): void => {\n    if (slices.length === 0) return;\n    setKeyboard(true);\n    setActive((index) => (index === null ? (step > 0 ? 0 : slices.length - 1) : (index + step + slices.length) % slices.length));\n  };\n  const onKeyDown = (event: KeyboardEvent<SVGSVGElement>): void => {\n    if (event.key === \"ArrowRight\" || event.key === \"ArrowDown\") move(1);\n    else if (event.key === \"ArrowLeft\" || event.key === \"ArrowUp\") move(-1);\n    else if (event.key === \"Escape\") setActive(null);\n    else return;\n    event.preventDefault();\n  };\n\n  return (\n    <div data-slot=\"donut-chart\" className={cn(\"@container w-full min-w-0\", className)} {...props}>\n      <div className=\"flex flex-col items-center gap-4 @sm:flex-row @sm:gap-6\">\n        <ChartContainer aspect={1} table={table} announcement={announcement} className=\"max-w-56 shrink-0\">\n          {(size) => {\n            const outer = Math.min(size.width, size.height) / 2;\n            const inner = outer - Math.max(10, Math.min(28, outer * 0.26));\n            const arcs = pieLayout<Slice>()\n              .value((slice) => slice.value)\n              .sort(null)\n              .padAngle(slices.length > 1 ? GAP / outer : 0)(slices);\n            const path = arcShape<(typeof arcs)[number]>().innerRadius(inner).outerRadius(outer).padRadius(outer);\n            const hovered = active === null ? undefined : arcs[active];\n            const centroid = hovered ? path.centroid(hovered) : [0, 0];\n            const tooltipX = size.width / 2 + (centroid[0] ?? 0);\n            return (\n              <>\n                <ChartSvg\n                  label={label}\n                  width={size.width}\n                  height={size.height}\n                  interactive\n                  onKeyDown={onKeyDown}\n                  onPointerLeave={() => setActive(null)}\n                  onFocus={(event) => {\n                    if (event.currentTarget.matches(\":focus-visible\")) move(1);\n                  }}\n                  onBlur={() => setActive(null)}\n                >\n                  <g aria-hidden=\"true\" transform={`translate(${size.width / 2},${size.height / 2})`}>\n                    {arcs.map((arc, index) => (\n                      <path\n                        key={index}\n                        d={path(arc) ?? undefined}\n                        className={cn(chartSeries(arc.data.index).fill, \"transition-opacity duration-instant motion-reduce:transition-none\", active !== null && active !== index && \"opacity-45\")}\n                        onPointerEnter={() => {\n                          setKeyboard(false);\n                          setActive(index);\n                        }}\n                      />\n                    ))}\n                  </g>\n                </ChartSvg>\n                <div data-slot=\"donut-chart-center\" className=\"pointer-events-none absolute inset-0 flex flex-col items-center justify-center px-8 text-center\">\n                  {children ?? (\n                    <>\n                      <span className=\"text-2xl font-semibold text-foreground\">{number(total)}</span>\n                      <span className=\"text-xs text-muted-foreground\">{centerLabel}</span>\n                    </>\n                  )}\n                </div>\n                {current ? (\n                  <ChartTooltip\n                    x={tooltipX}\n                    y={size.height / 2 + (centroid[1] ?? 0)}\n                    side={tooltipX > size.width / 2 ? \"left\" : \"right\"}\n                    rows={[{ label: current.name, value: `${number(current.value)} · ${share(current.value)}`, index: current.index, mark: \"rect\" }]}\n                  />\n                ) : null}\n              </>\n            );\n          }}\n        </ChartContainer>\n        {showLegend ? (\n          <ChartLegend\n            orientation=\"vertical\"\n            mark=\"rect\"\n            className=\"w-full min-w-0 @sm:flex-1\"\n            items={slices.map((slice) => ({ label: slice.name, index: slice.index, value: `${number(slice.value)} · ${share(slice.value)}` }))}\n          />\n        ) : null}\n      </div>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Parts of a whole at a glance, when there are few parts and they differ clearly. To compare parts that are close in size, or more than five, use bar-chart with `orientation=\"horizontal\"`; for one ratio against a limit use radial-progress.",
    "example": "<DonutChart\n  label=\"Traffic by source\"\n  data={[\n    { source: \"Search\", visits: 5200 },\n    { source: \"Direct\", visits: 3100 },\n    { source: \"Referral\", visits: 1400 },\n  ]}\n  name=\"source\"\n  value=\"visits\"\n  centerLabel=\"Visits\"\n/>",
    "client": true
  }
}
