{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"donut-chart","type":"registry:block","title":"Donut chart","description":"Revenue by plan donut whose segments draw around the ring, with a count-up centre and a lens glint at the start angle.","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"registry/prequel/donut-chart/donut-chart.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n  AnimatePresence,\n  MotionConfig,\n  animate,\n  motion,\n  useInView,\n  useReducedMotion,\n} from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\n\nconst COMPACT_NUMBER = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\n\nexport type DonutChartSegment = {\n  id: string;\n  label: string;\n  value: number;\n  /** Small caption under the plan name, e.g. \"212 accounts\". */\n  detail?: string;\n  /** Chart colour token 1–5. Defaults to the segment index + 1. */\n  tone?: number;\n};\n\nexport type DonutChartProps = {\n  className?: string;\n  title?: string;\n  description?: string;\n  segments?: DonutChartSegment[];\n  valuePrefix?: string;\n  /** Label shown in the centre when no segment is active. */\n  totalLabel?: string;\n  formatValue?: (value: number) => string;\n  /** Formats the big centre value; defaults to compact notation (e.g. \"$100k\"). */\n  formatCenterValue?: (value: number) => string;\n  formatShare?: (share: number) => string;\n};\n\n/* ------------------------------------------------------------------ */\n/* deterministic demo data                                             */\n/* ------------------------------------------------------------------ */\n\nconst DEFAULT_SEGMENTS: DonutChartSegment[] = [\n  { id: \"scale\", label: \"Scale\", value: 45000, detail: \"212 accounts\", tone: 1 },\n  { id: \"growth\", label: \"Growth\", value: 30000, detail: \"498 accounts\", tone: 2 },\n  { id: \"starter\", label: \"Starter\", value: 18000, detail: \"574 accounts\", tone: 3 },\n  { id: \"addons\", label: \"Add-ons\", value: 7000, detail: \"88 accounts\", tone: 4 },\n];\n\n/* ------------------------------------------------------------------ */\n/* helpers                                                             */\n/* ------------------------------------------------------------------ */\n\nfunction clamp(v: number, min: number, max: number) {\n  return Math.min(max, Math.max(min, v));\n}\n\nfunction trimZero(n: number) {\n  const s = n.toFixed(1);\n  return s.endsWith(\".0\") ? s.slice(0, -2) : s;\n}\n\nfunction polar(cx: number, cy: number, r: number, deg: number) {\n  const a = (deg * Math.PI) / 180;\n  /* Round before rendering: trig last digits can differ server/browser. */\n  const round = (n: number) => Math.round(n * 1000) / 1000;\n  return {\n    x: round(cx + r * Math.cos(a)),\n    y: round(cy + r * Math.sin(a)),\n  };\n}\n\nfunction arcPath(cx: number, cy: number, r: number, startDeg: number, endDeg: number) {\n  const s = polar(cx, cy, r, startDeg);\n  const e = polar(cx, cy, r, endDeg);\n  const large = endDeg - startDeg > 180 ? 1 : 0;\n  return `M ${s.x.toFixed(3)} ${s.y.toFixed(3)} A ${r} ${r} 0 ${large} 1 ${e.x.toFixed(3)} ${e.y.toFixed(3)}`;\n}\n\n/* geometry for one segment: angles measured clockwise from the top (12 o'clock) */\ntype SegmentGeom = {\n  id: string;\n  label: string;\n  detail?: string;\n  color: string;\n  value: number;\n  share: number;\n  d: string;\n  midDeg: number;\n  dx: number;\n  dy: number;\n};\n\nconst SIZE = 200;\nconst CX = 100;\nconst CY = 100;\nconst R = 68;\nconst STROKE = 26;\nconst GAP_PX = 3;\nconst PULL = 6;\n\nfunction computeSegments(\n  segments: DonutChartSegment[],\n  total: number\n): SegmentGeom[] {\n  const gapDeg = (GAP_PX / R) * (180 / Math.PI);\n  let angle = -90;\n\n  return segments.map((seg, i) => {\n    const fraction = total > 0 ? seg.value / total : 0;\n    const sweep = Math.max(0, fraction * 360 - gapDeg);\n    const startDeg = angle;\n    const endDeg = startDeg + sweep;\n    const midDeg = startDeg + sweep / 2;\n    const dir = polar(0, 0, 1, midDeg);\n    angle += fraction * 360;\n\n    return {\n      id: seg.id,\n      label: seg.label,\n      detail: seg.detail,\n      color: `var(--chart-${clamp(seg.tone ?? i + 1, 1, 5)})`,\n      value: seg.value,\n      share: fraction * 100,\n      d: arcPath(CX, CY, R, startDeg, endDeg),\n      midDeg,\n      dx: dir.x * PULL,\n      dy: dir.y * PULL,\n    };\n  });\n}\n\n/* ------------------------------------------------------------------ */\n/* count-up                                                            */\n/* ------------------------------------------------------------------ */\n\nfunction useAnimatedNumber(target: number, opts: { inView: boolean; reduce: boolean }) {\n  const [value, setValue] = useState(target);\n  const valueRef = useRef(target);\n  const animRef = useRef<ReturnType<typeof animate> | null>(null);\n  const firstRef = useRef(true);\n\n  useEffect(() => {\n    if (!opts.inView) return;\n    if (opts.reduce) {\n      valueRef.current = target;\n      setValue(target);\n      return;\n    }\n    const from = firstRef.current ? 0 : valueRef.current;\n    firstRef.current = false;\n    animRef.current?.stop();\n    animRef.current = animate(from, target, {\n      duration: 0.8,\n      ease: EASE,\n      onUpdate: (v) => {\n        valueRef.current = v;\n        setValue(v);\n      },\n      onComplete: () => {\n        valueRef.current = target;\n        setValue(target);\n      },\n    });\n    return () => animRef.current?.stop();\n  }, [target, opts.inView, opts.reduce]);\n\n  return value;\n}\n\n/* ------------------------------------------------------------------ */\n/* component                                                           */\n/* ------------------------------------------------------------------ */\n\nexport function DonutChart({\n  className,\n  title = \"Revenue by plan\",\n  description = \"Share of MRR by plan.\",\n  segments = DEFAULT_SEGMENTS,\n  valuePrefix = \"$\",\n  totalLabel = \"Total MRR\",\n  formatValue,\n  formatCenterValue,\n  formatShare,\n}: DonutChartProps) {\n  const cardRef = useRef<HTMLDivElement>(null);\n\n  const inView = useInView(cardRef, { once: true, margin: \"-10% 0px\" });\n  const reduce = Boolean(useReducedMotion());\n  const show = inView;\n\n  const [active, setActive] = useState<string | null>(null);\n\n  const format =\n    formatValue ??\n    ((n: number) => valuePrefix + Math.round(n).toLocaleString(\"en-US\"));\n  const formatPct =\n    formatShare ?? ((share: number) => `${trimZero(share)}%`);\n  const formatCenter =\n    formatCenterValue ?? ((n: number) => valuePrefix + COMPACT_NUMBER.format(n));\n\n  const total = useMemo(\n    () => segments.reduce((sum, s) => sum + s.value, 0),\n    [segments]\n  );\n\n  const geoms = useMemo(\n    () => computeSegments(segments, total),\n    [segments, total]\n  );\n\n  const activeGeom = active\n    ? geoms.find((g) => g.id === active) ?? null\n    : null;\n\n  const displayValue = useAnimatedNumber(\n    activeGeom ? activeGeom.value : total,\n    { inView, reduce }\n  );\n\n  const centerLabel = activeGeom ? activeGeom.label : totalLabel;\n  const centerSub = activeGeom\n    ? `${formatPct(activeGeom.share)} of total`\n    : `${segments.length} plans`;\n\n  /* where the glint dot rests: the ring's very first angle (top) */\n  const glint = polar(CX, CY, R, -90);\n\n  const ariaLabel = `${title}. Donut chart of ${segments\n    .map((s) => `${s.label} ${formatPct(total > 0 ? (s.value / total) * 100 : 0)}`)\n    .join(\", \")}. Total ${format(total)}.`;\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <motion.div\n        ref={cardRef}\n        initial={{ opacity: 0, y: 20 }}\n        animate={show ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}\n        transition={{ duration: 0.6, ease: EASE }}\n        className={cn(\n          \"rounded-xl border border-border bg-card text-card-foreground shadow-sm\",\n          className\n        )}\n      >\n        <div className=\"p-5 sm:p-6\">\n          <div>\n            <h2 className=\"text-[15px] font-semibold tracking-tight\">{title}</h2>\n            {description ? (\n              <p className=\"mt-0.5 text-[13px] text-muted-foreground\">\n                {description}\n              </p>\n            ) : null}\n          </div>\n\n          <div className=\"mt-5 flex flex-col items-center gap-6 sm:flex-row sm:gap-8\">\n            <div className=\"relative h-48 w-48 shrink-0 sm:h-52 sm:w-52\">\n              <svg\n                viewBox={`0 0 ${SIZE} ${SIZE}`}\n                role=\"img\"\n                aria-label={ariaLabel}\n                tabIndex={0}\n                onKeyDown={(e) => {\n                  const n = geoms.length;\n                  if (!n) return;\n                  const idx = active\n                    ? geoms.findIndex((g) => g.id === active)\n                    : -1;\n                  if (e.key === \"ArrowRight\" || e.key === \"ArrowDown\") {\n                    e.preventDefault();\n                    setActive(geoms[(idx + 1) % n].id);\n                  } else if (e.key === \"ArrowLeft\" || e.key === \"ArrowUp\") {\n                    e.preventDefault();\n                    setActive(geoms[(idx - 1 + n) % n].id);\n                  } else if (e.key === \"Home\") {\n                    e.preventDefault();\n                    setActive(geoms[0].id);\n                  } else if (e.key === \"End\") {\n                    e.preventDefault();\n                    setActive(geoms[n - 1].id);\n                  } else if (e.key === \"Escape\") {\n                    setActive(null);\n                  }\n                }}\n                onFocus={() => {\n                  if (active == null && geoms.length) setActive(geoms[0].id);\n                }}\n                onBlur={() => setActive(null)}\n                className=\"block h-full w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n              >\n                {/* the track behind the segments */}\n                <circle\n                  cx={CX}\n                  cy={CY}\n                  r={R}\n                  fill=\"none\"\n                  stroke=\"var(--muted)\"\n                  strokeWidth={STROKE}\n                />\n\n                {geoms.map((seg, i) => {\n                  const isActive = active === seg.id;\n                  const dimmed = active != null && !isActive;\n                  const delay = 0.15 + i * 0.1;\n                  return (\n                    <motion.g\n                      key={seg.id}\n                      initial={false}\n                      animate={{\n                        translateX: isActive ? seg.dx : 0,\n                        translateY: isActive ? seg.dy : 0,\n                        opacity: dimmed ? 0.35 : 1,\n                      }}\n                      transition={{\n                        translateX: { type: \"spring\", stiffness: 340, damping: 26 },\n                        translateY: { type: \"spring\", stiffness: 340, damping: 26 },\n                        opacity: { duration: 0.25 },\n                      }}\n                    >\n                      <motion.path\n                        d={seg.d}\n                        fill=\"none\"\n                        stroke={seg.color}\n                        strokeWidth={STROKE}\n                        initial={{ pathLength: reduce ? 1 : 0 }}\n                        animate={{ pathLength: show ? 1 : 0 }}\n                        transition={\n                          reduce\n                            ? { duration: 0 }\n                            : { duration: 0.7, delay, ease: EASE }\n                        }\n                      />\n                      {/* generous, invisible hit area */}\n                      <path\n                        d={seg.d}\n                        fill=\"none\"\n                        stroke=\"transparent\"\n                        strokeWidth={STROKE + 12}\n                        style={{ pointerEvents: \"stroke\" }}\n                        onPointerEnter={() => setActive(seg.id)}\n                        onPointerLeave={() =>\n                          setActive((a) => (a === seg.id ? null : a))\n                        }\n                        onClick={() => setActive(seg.id)}\n                      />\n                    </motion.g>\n                  );\n                })}\n\n                {/* the lens: one small glint dot on the ring at the start angle */}\n                <motion.g\n                  initial={{ opacity: 0, scale: 0.6 }}\n                  animate={{ opacity: show ? 1 : 0, scale: show ? 1 : 0.6 }}\n                  transition={\n                    reduce\n                      ? { duration: 0 }\n                      : {\n                          delay: 0.15 + (geoms.length - 1) * 0.1 + 0.5,\n                          duration: 0.45,\n                          ease: EASE,\n                        }\n                  }\n                  style={{ transformOrigin: `${glint.x}px ${glint.y}px` }}\n                >\n                  <circle\n                    cx={glint.x}\n                    cy={glint.y}\n                    r={4.5}\n                    fill=\"none\"\n                    stroke=\"var(--foreground)\"\n                    strokeOpacity={0.22}\n                    strokeWidth={1}\n                  />\n                  <circle cx={glint.x} cy={glint.y} r={2} fill=\"var(--foreground)\" />\n                </motion.g>\n              </svg>\n\n              {/* centre readout */}\n              <div className=\"pointer-events-none absolute inset-0 flex flex-col items-center justify-center px-3 text-center\">\n                <div className=\"whitespace-nowrap text-[24px] font-semibold leading-none tracking-tight tabular-nums\">\n                  {formatCenter(displayValue)}\n                </div>\n                <AnimatePresence mode=\"wait\" initial={false}>\n                  <motion.div\n                    key={active ?? \"total\"}\n                    initial={{ opacity: 0, y: 4 }}\n                    animate={{ opacity: 1, y: 0 }}\n                    exit={{ opacity: 0, y: -4 }}\n                    transition={{ duration: 0.18, ease: EASE }}\n                    className=\"mt-1.5 flex flex-col items-center\"\n                  >\n                    <span className=\"text-[11.5px] font-medium text-muted-foreground\">\n                      {centerLabel}\n                    </span>\n                    <span className=\"mt-0.5 text-[11px] tabular-nums text-muted-foreground\">\n                      {centerSub}\n                    </span>\n                  </motion.div>\n                </AnimatePresence>\n              </div>\n            </div>\n\n            {/* legend */}\n            <ul className=\"w-full flex-1 space-y-0.5\" role=\"list\">\n              {geoms.map((seg) => {\n                const isActive = active === seg.id;\n                return (\n                  <li key={seg.id}>\n                    <button\n                      type=\"button\"\n                      aria-pressed={isActive}\n                      onClick={() => setActive(seg.id)}\n                      onPointerEnter={() => setActive(seg.id)}\n                      onPointerLeave={() =>\n                        setActive((a) => (a === seg.id ? null : a))\n                      }\n                      onFocus={() => setActive(seg.id)}\n                      onBlur={() => setActive((a) => (a === seg.id ? null : a))}\n                      className={cn(\n                        \"flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n                        isActive ? \"bg-muted/70\" : \"hover:bg-muted/40\"\n                      )}\n                    >\n                      <span\n                        aria-hidden=\"true\"\n                        className=\"h-2.5 w-2.5 shrink-0 rounded-full\"\n                        style={{ background: seg.color }}\n                      />\n                      <span className=\"min-w-0 flex-1\">\n                        <span className=\"block truncate text-[13px] font-medium\">\n                          {seg.label}\n                        </span>\n                        {seg.detail ? (\n                          <span className=\"block truncate text-[11.5px] text-muted-foreground\">\n                            {seg.detail}\n                          </span>\n                        ) : null}\n                      </span>\n                      <span className=\"shrink-0 text-right\">\n                        <span className=\"block text-[13px] font-semibold tabular-nums\">\n                          {format(seg.value)}\n                        </span>\n                        <span className=\"block text-[11.5px] tabular-nums text-muted-foreground\">\n                          {formatPct(seg.share)}\n                        </span>\n                      </span>\n                    </button>\n                  </li>\n                );\n              })}\n            </ul>\n          </div>\n        </div>\n      </motion.div>\n    </MotionConfig>\n  );\n}\n\nexport default DonutChart;\n"}]}