{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "donut-chart",
  "title": "Donut chart",
  "description": "Donut or pie whose slices sweep in clockwise, re-share the ring when a legend item is toggled, push out on hover and roll the center total to the slice under the pointer.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/chart-legend.json",
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json",
    "https://goodui.dev/r/number-flow.json"
  ],
  "files": [
    {
      "path": "registry/components/charts/donut-chart.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { motion, useReducedMotion } from \"motion/react\"\nimport { cn } from \"@/lib/utils\"\nimport { ChartLegend } from \"@/components/goodui/chart-legend\"\nimport { NumberFlow } from \"@/components/goodui/number-flow\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { spring as springs } from \"@/lib/goodui-motion\"\n\nexport type DonutSlice = {\n  /** Defaults to the label. */\n  key?: string\n  label: string\n  value: number\n  /** Any CSS color. Defaults to the theme chart colors in order (--chart-1 … --chart-5). */\n  color?: string\n}\n\nexport type DonutChartLabels = {\n  summary: (name: string, total: string, parts: string) => string\n  /** Announced for the active slice. */\n  slice: (label: string, value: string, share: string) => string\n  total: string\n  legend: string\n  columnLabel: string\n  columnValue: string\n  columnShare: string\n  noData: string\n}\nconst DEFAULT_LABELS: DonutChartLabels = {\n  summary: (name, total, parts) => `${name ? name + \": \" : \"\"}total ${total}. ${parts}`,\n  slice: (label, value, share) => `${label}: ${value}, ${share}`,\n  total: \"Total\",\n  legend: \"Slices\",\n  columnLabel: \"Label\",\n  columnValue: \"Value\",\n  columnShare: \"Share\",\n  noData: \"No data\",\n}\n\nexport type DonutChartProps = Omit<React.ComponentProps<\"div\">, \"title\" | \"hidden\"> & {\n  data: DonutSlice[]\n  /** Name shown under the center number and used by screen readers. */\n  title?: React.ReactNode\n  /** donut (ring with the total in the middle) or pie (full disc, readout under it). */\n  variant?: \"donut\" | \"pie\"\n  /** Diameter in px. */\n  size?: number\n  /** Ring thickness in px (donut). */\n  thickness?: number\n  /** Surface gap between slices in px. */\n  gap?: number\n  /** Legend placement, with each slice's share. */\n  legend?: \"end\" | \"bottom\" | \"none\"\n  /** Show \"42%\" next to legend labels. */\n  showPercent?: boolean\n  /** Keys of hidden slices (controlled); hidden slices leave the ring and the others re-share it. */\n  hidden?: string[]\n  defaultHidden?: string[]\n  onHiddenChange?: (hidden: string[]) => void\n  /** Intl.NumberFormat options for the values, e.g. { style: \"currency\", currency: \"USD\" }. */\n  format?: Intl.NumberFormatOptions\n  locale?: string\n  formatValue?: (value: number) => string\n  /** Seconds the whole ring takes to sweep in. */\n  duration?: number\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<DonutChartLabels>\n}\n\nfunction useReduce() {\n  const prefers = useReducedMotion()\n  const [mounted, setMounted] = React.useState(false)\n  React.useEffect(() => setMounted(true), [])\n  return mounted && !!prefers\n}\n\nfunction useInView(ref: React.RefObject<Element | null>, threshold = 0.2) {\n  const [inView, setInView] = React.useState(false)\n  React.useEffect(() => {\n    const el = ref.current\n    if (!el || inView) return\n    if (typeof IntersectionObserver === \"undefined\") {\n      setInView(true)\n      return\n    }\n    const io = new IntersectionObserver(\n      ([e]) => {\n        if (e?.isIntersecting) {\n          setInView(true)\n          io.disconnect()\n        }\n      },\n      { threshold },\n    )\n    io.observe(el)\n    return () => io.disconnect()\n  }, [ref, inView, threshold])\n  return inView\n}\n\n/** Donut or pie whose slices sweep in on view, re-share the ring when one is toggled, expand on hover and roll the center total. */\nexport function DonutChart({\n  data,\n  title,\n  variant = \"donut\",\n  size = 200,\n  thickness = 24,\n  gap = 2,\n  legend = \"end\",\n  showPercent = true,\n  hidden: hiddenProp,\n  defaultHidden,\n  onHiddenChange,\n  format,\n  locale = \"en-US\",\n  formatValue,\n  duration = 1,\n  labels,\n  className,\n  \"aria-label\": ariaLabel,\n  ...props\n}: DonutChartProps) {\n  const l = useLabels(\"donut-chart\", DEFAULT_LABELS, labels)\n  const reduce = useReduce()\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const inView = useInView(rootRef)\n  const [innerHidden, setInnerHidden] = React.useState<string[]>(defaultHidden ?? [])\n  const hidden = hiddenProp ?? innerHidden\n  const [active, setActive] = React.useState<string | null>(null)\n  const [entered, setEntered] = React.useState(false)\n  React.useEffect(() => {\n    if (!inView) return\n    const id = window.setTimeout(() => setEntered(true), reduce ? 0 : duration * 1000 + 100)\n    return () => window.clearTimeout(id)\n  }, [inView, reduce, duration])\n\n  const pie = variant === \"pie\"\n  const stroke = pie ? size / 2 : Math.min(thickness, size / 2)\n  const r = (size - stroke) / 2\n  const c = size / 2\n  const circumference = 2 * Math.PI * r\n  const keyOf = (s: DonutSlice) => s.key ?? s.label\n  const colorOf = (i: number) => data[i]?.color ?? `var(--chart-${(i % 5) + 1})`\n  const slices = data.map((s, i) => ({ ...s, key: keyOf(s), color: colorOf(i), index: i }))\n  const visible = slices.filter((s) => !hidden.includes(s.key) && s.value > 0)\n  const total = visible.reduce((sum, s) => sum + s.value, 0)\n  const grand = slices.reduce((sum, s) => sum + s.value, 0)\n  const fmt = React.useMemo(() => formatValue ?? ((v: number) => new Intl.NumberFormat(locale, format).format(v)), [formatValue, locale, format])\n  const pct = React.useMemo(() => new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 0 }), [locale])\n  const gapFrac = visible.length > 1 ? gap / circumference : 0\n\n  let acc = 0\n  const arcs = visible.map((s) => {\n    const share = total > 0 ? s.value / total : 0\n    const start = acc\n    acc += share\n    return { ...s, share, start, length: Math.max(0.0001, share - gapFrac), offset: start + gapFrac / 2 }\n  })\n  const activeSlice = active !== null ? arcs.find((a) => a.key === active) : undefined\n  const shownValue = activeSlice ? activeSlice.value : total\n  const name = typeof title === \"string\" ? title : \"\"\n  const summary = ariaLabel ?? (visible.length ? l.summary(name, fmt(total), arcs.map((a) => `${a.label} ${pct.format(a.share)}`).join(\", \")) : l.noData)\n  const announce = activeSlice ? l.slice(activeSlice.label, fmt(activeSlice.value), pct.format(activeSlice.share)) : \"\"\n\n  const setHidden = (next: string[]) => {\n    if (hiddenProp === undefined) setInnerHidden(next)\n    onHiddenChange?.(next)\n  }\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (!arcs.length) return\n    if ([\"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", \"ArrowDown\"].includes(e.key)) {\n      e.preventDefault()\n      const dir = e.key === \"ArrowLeft\" || e.key === \"ArrowUp\" ? -1 : 1\n      const i = arcs.findIndex((a) => a.key === active)\n      setActive(arcs[(i + dir + arcs.length) % arcs.length]?.key ?? null)\n    } else if (e.key === \"Home\" || e.key === \"End\") {\n      e.preventDefault()\n      setActive((e.key === \"Home\" ? arcs[0] : arcs[arcs.length - 1])?.key ?? null)\n    } else if (e.key === \"Escape\") setActive(null)\n  }\n\n  const ready = inView || reduce\n  const spring = reduce ? { duration: 0 } : springs.morph\n  const legendNode =\n    legend !== \"none\" && slices.length > 0 ? (\n      <ChartLegend\n        items={slices.map((s) => ({ key: s.key, label: s.label, color: s.color, value: showPercent ? pct.format(total > 0 && !hidden.includes(s.key) ? s.value / total : 0) : undefined, shape: \"dot\" }))}\n        hidden={hidden}\n        onHiddenChange={setHidden}\n        active={active}\n        onActiveChange={setActive}\n        layout={legend === \"end\" ? \"column\" : \"row\"}\n        size=\"sm\"\n        labels={{ legend: l.legend }}\n        className={legend === \"end\" ? \"min-w-32\" : \"justify-center\"}\n      />\n    ) : null\n\n  return (\n    <div ref={rootRef} className={cn(\"pc-donut-chart flex w-full min-w-0 flex-wrap items-center gap-x-8 gap-y-4\", legend === \"end\" ? \"flex-row justify-center\" : \"flex-col\", className)} {...props}>\n      <div className=\"flex flex-col items-center gap-2\">\n        <div\n          role=\"group\"\n          aria-roledescription={pie ? \"pie chart\" : \"donut chart\"}\n          aria-label={summary}\n          tabIndex={0}\n          onKeyDown={onKeyDown}\n          onBlur={() => setActive(null)}\n          className=\"relative shrink-0 rounded-full outline-none focus-visible:ring-3 focus-visible:ring-ring/50\"\n          style={{ width: size, height: size }}\n        >\n          <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className=\"overflow-visible\" aria-hidden=\"true\">\n            {!pie && <circle cx={c} cy={c} r={r} fill=\"none\" strokeWidth={stroke} className=\"stroke-muted\" />}\n            <g transform={`rotate(-90 ${c} ${c})`}>\n              {arcs.map((a) => {\n                const isActive = active === a.key\n                const dim = active !== null && !isActive\n                return (\n                  <motion.circle\n                    key={a.key}\n                    cx={c}\n                    cy={c}\n                    r={r}\n                    fill=\"none\"\n                    style={{ stroke: a.color }}\n                    strokeWidth={stroke}\n                    className=\"cursor-pointer\"\n                    initial={false}\n                    animate={{ pathLength: ready ? a.length : 0.0001, pathOffset: a.offset, r: isActive && !pie ? r + 4 : r, opacity: dim ? 0.45 : 1 }}\n                    transition={{\n                      pathLength: reduce ? { duration: 0 } : entered ? spring : { duration: duration * a.share, delay: duration * a.start, ease: \"linear\" },\n                      pathOffset: reduce ? { duration: 0 } : entered ? spring : { duration: 0 },\n                      r: reduce ? { duration: 0 } : springs.play,\n                      opacity: { duration: reduce ? 0 : 0.2 },\n                    }}\n                    onPointerEnter={() => setActive(a.key)}\n                    onPointerLeave={() => setActive(null)}\n                  />\n                )\n              })}\n            </g>\n          </svg>\n          {!pie && (\n            <div className=\"pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-0.5 text-center\" style={{ padding: stroke + 8 }}>\n              <NumberFlow value={shownValue} format={format} locale={locale} className=\"text-2xl leading-none font-semibold tracking-tight\" />\n              <span className=\"max-w-full truncate text-xs text-muted-foreground\">{activeSlice ? activeSlice.label : (title ?? l.total)}</span>\n              <span className=\"h-4 text-xs font-medium tabular-nums\" aria-hidden=\"true\">\n                {activeSlice ? pct.format(activeSlice.share) : \"\"}\n              </span>\n            </div>\n          )}\n          {visible.length === 0 && <div className=\"absolute inset-0 grid place-items-center text-sm text-muted-foreground\">{l.noData}</div>}\n          <span className=\"sr-only\" aria-live=\"polite\">\n            {announce}\n          </span>\n        </div>\n        {pie && (\n          <div className=\"flex h-10 flex-col items-center justify-center text-center\">\n            <span className=\"text-lg leading-none font-semibold tabular-nums\">{activeSlice ? `${fmt(activeSlice.value)} · ${pct.format(activeSlice.share)}` : fmt(total)}</span>\n            <span className=\"text-xs text-muted-foreground\">{activeSlice ? activeSlice.label : (title ?? l.total)}</span>\n          </div>\n        )}\n      </div>\n      {legendNode}\n      {slices.length > 0 && (\n        <div className=\"sr-only\">\n          <table>\n          <caption>{summary}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">{l.columnLabel}</th>\n              <th scope=\"col\">{l.columnValue}</th>\n              <th scope=\"col\">{l.columnShare}</th>\n            </tr>\n          </thead>\n          <tbody>\n            {slices.map((s) => (\n              <tr key={s.key}>\n                <th scope=\"row\">{s.label}</th>\n                <td>{fmt(s.value)}</td>\n                <td>{pct.format(grand > 0 ? s.value / grand : 0)}</td>\n              </tr>\n            ))}\n          </tbody>\n        </table>\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/donut-chart.tsx"
    }
  ],
  "categories": [
    "components",
    "charts"
  ],
  "type": "registry:component"
}
