{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "donut-chart",
  "type": "registry:component",
  "title": "Donut chart",
  "description": "One whole in up to six parts, with the total in the middle and a value legend.",
  "dependencies": [],
  "registryDependencies": [
    "https://chartslibraryui.com/r/core.json"
  ],
  "files": [
    {
      "path": "registry/charts/donut-chart.tsx",
      "type": "registry:component",
      "target": "components/charts/donut-chart.tsx",
      "content": "\"use client\";\n// donut-chart.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n\nimport { useMemo } from \"react\";\nimport { color as tokens } from \"./core/color\";\nimport { readNum, type Issue, type Row } from \"./core/data\";\nimport { formatShare, formatValue, labelFormatter, type FormatInput } from \"./core/format\";\nimport { ChartFrame, ChartTooltip, KeySwatch, useActiveIndex, type FrameProps } from \"./core/frame\";\nimport { arcPath } from \"./core/path\";\nimport { useWords } from \"./core/words\";\n\nexport interface DonutChartProps extends FrameProps {\n  /** Rows to draw, one object per row. See the Data section for the shape. */\n  data: Row[];\n  /** Key of the slice name. */\n  label: string;\n  /** Key of the slice value. Must be zero or positive. */\n  value: string;\n  /** Number format for values: \"currency\", \"percent\", \"integer\", \"compact\" or a format object. */\n  format?: FormatInput;\n  /** Fold the smallest slices into \"Other\" beyond this many. Default 6. The fold is stated in a note. */\n  maxSlices?: number;\n  /** Text in the centre. Default: the total. Pass null to hide. */\n  centerLabel?: string | null;\n  /** Small caption under the centre value. */\n  centerCaption?: string;\n  /** Inner radius as a share of the outer radius. 0 draws a pie. Default 0.62. */\n  innerRadius?: number;\n  /** Slice names to emphasise; others are grey. */\n  highlight?: string | string[];\n  /** Name for the folded slice. */\n  otherLabel?: string;\n}\n\ninterface Slice {\n  name: string;\n  value: number;\n  share: number;\n  color: string;\n  folded?: number;\n}\n\n/**\n * One whole in at most six parts, with the total in the middle. Slices keep their data order (sort your data if\n * you want them ranked). Negative values are rejected because a share can't be negative.\n */\nexport function DonutChart({\n  data,\n  label,\n  value,\n  format,\n  maxSlices = 6,\n  centerLabel,\n  centerCaption,\n  innerRadius = 0.62,\n  highlight,\n  otherLabel: otherLabelProp,\n  height = 240,\n  ...frame\n}: DonutChartProps) {\n  const L = useWords(frame.words);\n  const otherLabel = otherLabelProp ?? L.other;\n  const { slices, issues, total } = useMemo(() => {\n    const issues: Issue[] = [];\n    if (!Array.isArray(data) || data.length === 0)\n      return { slices: [] as Slice[], issues: [{ level: \"error\", message: \"No data to display.\" }] as Issue[], total: 0 };\n    const items: { name: string; value: number }[] = [];\n    let missing = 0;\n    const negatives: string[] = [];\n    const invalid: string[] = [];\n    for (const row of data) {\n      const name = String(row?.[label] ?? \"\");\n      const r = readNum(row?.[value]);\n      if (r.state === \"missing\") missing++;\n      else if (r.state === \"invalid\") invalid.push(name);\n      else if (r.value! < 0) negatives.push(name);\n      else items.push({ name, value: r.value! });\n    }\n    if (invalid.length)\n      issues.push({ level: \"error\", message: `Non-numeric values for: ${invalid.slice(0, 3).join(\", \")}.` });\n    if (negatives.length)\n      issues.push({\n        level: \"error\",\n        message: `Negative values can't be shown as shares of a whole (${negatives.slice(0, 3).join(\", \")}). Use a bar chart.`,\n      });\n    if (missing) issues.push({ level: \"warning\", message: `${missing} slice(s) with no value are left out.` });\n    const total = items.reduce((a, b) => a + b.value, 0);\n    if (!issues.some((i) => i.level === \"error\") && total === 0)\n      issues.push({ level: \"error\", message: \"All values are zero, so there is no whole to divide.\" });\n    const zeros = items.filter((d) => d.value === 0).length;\n    if (zeros) issues.push({ level: \"note\", message: `${zeros} slice(s) are zero and draw nothing.` });\n\n    let kept = items;\n    let folded: { name: string; value: number } | null = null;\n    if (items.length > maxSlices) {\n      const ranked = [...items].sort((a, b) => b.value - a.value);\n      const keep = new Set(ranked.slice(0, maxSlices - 1).map((d) => d.name));\n      kept = items.filter((d) => keep.has(d.name));\n      const rest = items.filter((d) => !keep.has(d.name));\n      folded = { name: otherLabel, value: rest.reduce((a, b) => a + b.value, 0) };\n      issues.push({\n        level: \"note\",\n        message: `${rest.length} smallest slices are combined into \"${otherLabel}\" (${formatShare(folded.value / (total || 1))}).`,\n      });\n    }\n    const hl = highlight === undefined ? null : new Set(Array.isArray(highlight) ? highlight : [highlight]);\n    let slot = 0;\n    const slices: Slice[] = kept.map((d) => ({\n      ...d,\n      share: total ? d.value / total : 0,\n      color: hl ? (hl.has(d.name) ? tokens.series(slot++) : tokens.context) : tokens.series(slot++),\n    }));\n    if (folded)\n      slices.push({\n        ...folded,\n        share: total ? folded.value / total : 0,\n        color: tokens.contextSoft,\n        folded: items.length - kept.length,\n      });\n    return { slices, issues, total };\n  }, [data, label, value, maxSlices, highlight, otherLabel]);\n\n  const table = {\n    columns: [\n      { key: \"name\", label },\n      { key: \"value\", label: value, align: \"right\" as const, format: (v: unknown) => formatValue(v as number, format, { context: \"table\" }) },\n      { key: \"share\", label: L.share, align: \"right\" as const, format: (v: unknown) => formatShare(v as number, 1) },\n    ],\n    rows: slices.map((s) => ({ name: s.name, value: s.value, share: s.share })),\n  };\n  const summary = `${innerRadius > 0 ? \"Donut\" : \"Pie\"} chart of ${slices.length} parts totalling ${formatValue(\n    total,\n    format,\n  )}. ${slices\n    .slice(0, 6)\n    .map((s) => `${s.name} ${formatShare(s.share)}`)\n    .join(\", \")}.`;\n\n  return (\n    <ChartFrame {...frame} height={height} issues={issues} table={table} summary={summary}>\n      {({ width }) => (\n        <DonutPlot\n          width={width}\n          height={height}\n          slices={slices}\n          total={total}\n          format={format}\n          inner={innerRadius}\n          centerLabel={centerLabel}\n          centerCaption={centerCaption}\n        />\n      )}\n    </ChartFrame>\n  );\n}\n\nfunction DonutPlot({\n  width,\n  height,\n  slices,\n  total,\n  format,\n  inner,\n  centerLabel,\n  centerCaption,\n}: {\n  width: number;\n  height: number;\n  slices: Slice[];\n  total: number;\n  format?: FormatInput;\n  inner: number;\n  centerLabel?: string | null;\n  centerCaption?: string;\n}) {\n  const L = useWords();\n  const { active, setActive, keyProps } = useActiveIndex(slices.length, { describe: (i) => ({ label: String(arcs[i].name) }) });\n  const stacked = width < 440;\n  const size = stacked ? Math.min(width, height) : Math.min(height, width * 0.45);\n  const outer = size / 2 - 4;\n  const ir = outer * Math.max(0, Math.min(0.9, inner));\n  const cx = stacked ? width / 2 : size / 2;\n  const cy = size / 2;\n  const gap = slices.length > 1 ? 0.012 : 0; // surface gap between slices, in radians at the outer edge\n\n  const arcs: (Slice & { a0: number; a1: number; mid: number })[] = [];\n  for (let i = 0, angle = 0; i < slices.length; i++) {\n    const sl = slices[i];\n    const sweep = sl.share * Math.PI * 2;\n    const pad = sweep > gap * 2 ? gap / 2 : 0;\n    arcs.push({ ...sl, a0: angle + pad, a1: angle + sweep - pad, mid: angle + sweep / 2 });\n    angle += sweep;\n  }\n\n  const center = centerLabel === undefined ? formatValue(total, format) : centerLabel;\n\n  return (\n    <div style={{ display: \"flex\", flexDirection: stacked ? \"column\" : \"row\", gap: stacked ? 12 : 28, alignItems: stacked ? \"stretch\" : \"center\" }}>\n      <div style={{ position: \"relative\", width: stacked ? width : size, height: size, flexShrink: 0 }}>\n        <svg width={stacked ? width : size} height={size} role=\"group\" aria-roledescription=\"chart\" aria-label=\"Use arrow keys to read each part.\" {...keyProps}>\n          {arcs.map((a, i) => (\n            <path\n              key={a.name + i}\n              d={arcPath(cx, cy, ir, active === i ? outer + 3 : outer, a.a0, a.a1)}\n              style={{ fill: a.color }}\n              className={`clui-mark${active !== null && active !== i ? \" clui-dim\" : \"\"}`}\n              onPointerEnter={() => setActive(i)}\n              onPointerLeave={() => setActive(null)}\n            />\n          ))}\n          {ir > 24 && center !== null && (\n            <g aria-hidden>\n              <text x={cx} y={cy} dy={centerCaption ? \"-0.1em\" : \"0.35em\"} textAnchor=\"middle\" className=\"clui-label-strong\" style={{ fontSize: Math.min(22, ir / 2.6) }}>\n                {center}\n              </text>\n              {centerCaption && (\n                <text x={cx} y={cy} dy=\"1.4em\" textAnchor=\"middle\" className=\"clui-annot\">\n                  {centerCaption}\n                </text>\n              )}\n            </g>\n          )}\n        </svg>\n        {active !== null && arcs[active] && (\n          <ChartTooltip\n            x={cx + Math.sin(arcs[active].mid) * outer * 0.8}\n            y={cy - Math.cos(arcs[active].mid) * outer * 0.8}\n            width={stacked ? width : size * 2}\n            height={size}\n            data={{\n              title: arcs[active].name,\n              rows: [\n                { label: L.value, value: formatValue(arcs[active].value, format, { context: \"tooltip\" }) },\n                { label: L.share, value: formatShare(arcs[active].share, 1) },\n              ],\n              footer: arcs[active].folded ? `${arcs[active].folded} smaller parts combined` : undefined,\n            }}\n          />\n        )}\n      </div>\n      <ul className=\"clui-legend\" style={{ flexDirection: \"column\", gap: 6, margin: 0, flex: 1, minWidth: 0 }} aria-hidden>\n        {arcs.map((a, i, all) => (\n          <li\n            key={a.name + i}\n            style={{ display: \"grid\", gridTemplateColumns: \"auto 1fr auto auto\", gap: 8, alignItems: \"center\", opacity: active !== null && active !== i ? 0.5 : 1 }}\n            onPointerEnter={() => setActive(i)}\n            onPointerLeave={() => setActive(null)}\n          >\n            <KeySwatch color={a.color} />\n            <span style={{ overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\", color: \"var(--clui-ink)\" }} title={a.name}>\n              {a.name}\n            </span>\n            <span style={{ fontVariantNumeric: \"tabular-nums\" }}>{labelFormatter(format, all.map((x) => x.value))(a.value)}</span>\n            <span style={{ fontVariantNumeric: \"tabular-nums\", minWidth: 36, textAlign: \"right\", color: \"var(--clui-ink)\" }}>{formatShare(a.share)}</span>\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "version": "1.1.0",
    "tier": "free",
    "category": "composition",
    "component": "DonutChart"
  }
}