{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"donut-chart","type":"registry:component","title":"Donut chart","description":"Draws itself in, then lifts whichever slice you point at.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/donut-chart.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n  animate,\n  motion,\n  useInView,\n  useMotionValue,\n  useSpring,\n  useTransform,\n  type MotionValue,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type DonutSlice = { label: string; value: number; color: string };\n\nconst SIZE = 200;\nconst STROKE = 28;\n// Leaves room inside the box for a pulled-out segment: 100 - 14 - 7.\nconst R = SIZE / 2 - STROKE / 2 - 7;\nconst C = 2 * Math.PI * R;\n// A 2px surface gap separates segments; no stroke is drawn around them.\nconst GAP = 2;\n// Far enough to read as lifted, close enough to still sit in the ring.\nconst PULL = 6;\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// No bounce: a total that overshoots briefly claims a number that isn't true.\nconst COUNT = { visualDuration: 0.4, bounce: 0 };\n\nconst number = new Intl.NumberFormat(\"en-US\");\nconst percent = new Intl.NumberFormat(\"en-US\", { style: \"percent\" });\n\nexport function DonutChart({\n  data,\n  label,\n  totalLabel = \"Total\",\n  className,\n}: {\n  data: DonutSlice[];\n  /** Names the chart for screen readers, e.g. \"Visits by source\". */\n  label: string;\n  totalLabel?: string;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const ringRef = useRef<SVGSVGElement>(null);\n  const inView = useInView(ringRef, { once: true, amount: 0.5 });\n  const [hovered, setHovered] = useState<number | null>(null);\n  const [pinned, setPinned] = useState<number | null>(null);\n  const active = hovered ?? pinned;\n\n  const total = data.reduce((sum, d) => sum + d.value, 0);\n  const arcs = data.map((d, i) => {\n    const start = (data.slice(0, i).reduce((sum, p) => sum + p.value, 0) / total) * C;\n    const length = (d.value / total) * C;\n    // Mid-angle in screen space (0 is 3 o'clock), since the ring starts at 12.\n    return { start, length, mid: ((start + length / 2) / C) * Math.PI * 2 - Math.PI / 2 };\n  });\n\n  const progress = useMotionValue(0);\n  const count = useSpring(0, COUNT);\n  const shown = useTransform(count, (v) => number.format(Math.round(v)));\n\n  useEffect(() => {\n    if (!inView) return;\n    if (reduceMotion) {\n      progress.jump(1);\n      return;\n    }\n    // A one-time entrance that traces the whole ring. It runs longer than\n    // the 300ms UI budget because the sweep itself explains the parts\n    // adding up to a whole; nothing waits on it.\n    const controls = animate(progress, 1, { duration: 0.8, ease: EASE_OUT });\n    return () => controls.stop();\n  }, [inView, reduceMotion, progress]);\n\n  const target = active === null ? total : data[active].value;\n  useEffect(() => {\n    if (!inView) return;\n    if (reduceMotion) count.jump(target);\n    else count.set(target);\n  }, [inView, target, reduceMotion, count]);\n\n  const toggle = (i: number) => setPinned((p) => (p === i ? null : i));\n  const centreLabel = active === null ? totalLabel : data[active].label;\n\n  return (\n    <div className={cn(\"flex flex-wrap items-center justify-center gap-x-8 gap-y-6\", className)}>\n      <div className=\"relative shrink-0\" style={{ width: SIZE, height: SIZE }}>\n        <svg\n          ref={ringRef}\n          aria-hidden\n          width={SIZE}\n          height={SIZE}\n          viewBox={`0 0 ${SIZE} ${SIZE}`}\n          className=\"overflow-visible\"\n          // Leaving the whole ring resets, not each segment, so sweeping\n          // across a gap never flickers the centre back to the total.\n          onPointerLeave={(e) => {\n            if (e.pointerType !== \"touch\") setHovered(null);\n          }}\n        >\n          {data.map((d, i) => (\n            <Segment\n              key={d.label}\n              color={d.color}\n              start={arcs[i].start}\n              length={arcs[i].length}\n              mid={arcs[i].mid}\n              progress={progress}\n              active={active === i}\n              dimmed={active !== null && active !== i}\n              reduceMotion={!!reduceMotion}\n              onPointerEnter={(e) => {\n                if (e.pointerType !== \"touch\") setHovered(i);\n              }}\n              onClick={() => toggle(i)}\n            />\n          ))}\n        </svg>\n        <div\n          aria-hidden\n          className=\"pointer-events-none absolute inset-0 flex flex-col items-center justify-center\"\n        >\n          <motion.span className=\"text-3xl font-semibold tracking-tight text-foreground tabular-nums\">\n            {shown}\n          </motion.span>\n          {/* Remounts on change, so each new name fades in from a soft blur\n              instead of snapping. */}\n          <span\n            key={centreLabel}\n            className=\"max-w-[120px] truncate text-sm text-muted-foreground transition-[opacity,filter] duration-200 ease-out starting:opacity-0 starting:blur-[4px]\"\n          >\n            {centreLabel}\n          </span>\n        </div>\n      </div>\n\n      <ul className=\"flex w-[200px] max-w-full flex-col\">\n        {data.map((d, i) => (\n          <li key={d.label}>\n            <button\n              type=\"button\"\n              aria-pressed={pinned === i}\n              onPointerEnter={(e) => {\n                if (e.pointerType !== \"touch\") setHovered(i);\n              }}\n              onPointerLeave={(e) => {\n                if (e.pointerType !== \"touch\") setHovered(null);\n              }}\n              // Keyboard focus previews like hover does; a tap's focus shouldn't,\n              // or unpinning would leave the segment highlighted.\n              onFocus={(e) => {\n                if (e.currentTarget.matches(\":focus-visible\")) setHovered(i);\n              }}\n              onBlur={() => setHovered(null)}\n              onClick={() => toggle(i)}\n              className={cn(\n                \"flex h-9 w-full touch-manipulation items-center gap-2.5 rounded-lg px-2 text-left text-sm transition-[scale,opacity,background-color] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[opacity,background-color]\",\n                active !== null && active !== i ? \"opacity-40\" : \"opacity-100\",\n                pinned === i && \"bg-muted\",\n              )}\n            >\n              <span aria-hidden className=\"size-2.5 shrink-0 rounded-[3px]\" style={{ background: d.color }} />\n              <span className=\"min-w-0 flex-1 truncate text-foreground\">{d.label}</span>\n              <span className=\"text-foreground tabular-nums\">{number.format(d.value)}</span>\n              <span className=\"w-9 text-right text-muted-foreground tabular-nums\">\n                {percent.format(d.value / total)}\n              </span>\n            </button>\n          </li>\n        ))}\n      </ul>\n\n      <table className=\"sr-only\">\n        <caption>{label}</caption>\n        <thead>\n          <tr>\n            <th scope=\"col\">Category</th>\n            <th scope=\"col\">Value</th>\n            <th scope=\"col\">Share</th>\n          </tr>\n        </thead>\n        <tbody>\n          {data.map((d) => (\n            <tr key={d.label}>\n              <th scope=\"row\">{d.label}</th>\n              <td>{number.format(d.value)}</td>\n              <td>{percent.format(d.value / total)}</td>\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  );\n}\n\nfunction Segment({\n  color,\n  start,\n  length,\n  mid,\n  progress,\n  active,\n  dimmed,\n  reduceMotion,\n  onPointerEnter,\n  onClick,\n}: {\n  color: string;\n  start: number;\n  length: number;\n  mid: number;\n  progress: MotionValue<number>;\n  active: boolean;\n  dimmed: boolean;\n  reduceMotion: boolean;\n  onPointerEnter: (e: React.PointerEvent) => void;\n  onClick: () => void;\n}) {\n  // Each segment draws its own share of one sweep, so the ring fills as a\n  // single stroke going round rather than every piece growing at once.\n  const dash = useTransform(progress, (p) => {\n    const drawn = Math.min(Math.max(p * C - start, 0), Math.max(length - GAP, 0));\n    return `${drawn} ${C}`;\n  });\n  const pull = active && !reduceMotion ? PULL : 0;\n  const centre = SIZE / 2;\n\n  return (\n    <g\n      style={{\n        transform: `translate(${Math.cos(mid) * pull}px, ${Math.sin(mid) * pull}px)`,\n        opacity: dimmed ? 0.3 : 1,\n        transition: `transform 200ms cubic-bezier(${EASE_OUT.join(\",\")}), opacity 150ms ease-out`,\n      }}\n    >\n      {/* A circle's stroke starts at 3 o'clock; turning it starts the ring\n          at 12, where people read a pie from. */}\n      <g transform={`rotate(-90 ${centre} ${centre})`}>\n        <motion.circle\n          cx={centre}\n          cy={centre}\n          r={R}\n          fill=\"none\"\n          strokeWidth={STROKE}\n          strokeDashoffset={-start}\n          // Through style, not the attribute: light-dark() and color-mix()\n          // are only reliable as CSS values.\n          style={{ stroke: color, strokeDasharray: dash }}\n          className=\"cursor-pointer\"\n          onPointerEnter={onPointerEnter}\n          onClick={onClick}\n        />\n      </g>\n    </g>\n  );\n}\n\n// Validated categorical slots 1 to 4 (adjacent CVD separation >= 8.4 in\n// both themes), each stepped for its theme. The tail folds into a neutral\n// \"Other\" rather than a fifth hue.\nconst SOURCES: DonutSlice[] = [\n  { label: \"Organic search\", value: 4820, color: \"light-dark(#2a78d6, #3987e5)\" },\n  { label: \"Direct\", value: 3140, color: \"light-dark(#eb6834, #d95926)\" },\n  { label: \"Referral\", value: 1760, color: \"light-dark(#1baf7a, #199e70)\" },\n  { label: \"Social\", value: 1190, color: \"light-dark(#eda100, #c98500)\" },\n  { label: \"Other\", value: 640, color: \"color-mix(in oklab, var(--foreground) 22%, transparent)\" },\n];\n\nexport default function DonutChartDemo() {\n  return (\n    <div className=\"flex w-[460px] max-w-full flex-col gap-6\">\n      <div>\n        <p className=\"text-[15px] font-medium text-foreground\">Visits by source</p>\n        <p className=\"text-sm text-muted-foreground\">Last 30 days</p>\n      </div>\n      <DonutChart data={SOURCES} label=\"Visits by source, last 30 days\" totalLabel=\"Total visits\" />\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"categories":["data"],"docs":"From ui lab: https://lab.xevrion.dev/lab/donut-chart"}