{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "donut-chart",
  "type": "registry:component",
  "title": "Share chart",
  "description": "Explain the makeup of a total with a center summary and a readable legend.",
  "categories": [
    "charts"
  ],
  "dependencies": [
    "recharts-analytics@npm:recharts@3.10.1"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/donut-chart.tsx",
      "type": "registry:component",
      "target": "components/overtrue/donut-chart.tsx",
      "content": "/** Adapted from dashboardcn (MIT), copyright 2026 dashboardcn contributors.\n * Source: https://github.com/NoahGdev/dashboardcn/tree/b1ffacbca0f7a0be60135c8665b9e8c267205c48\n *\n * MIT License\n *\n * Copyright (c) 2026 dashboardcn contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * ---\n *\n * Portions of this project are derived from shadcn/ui and shadcn/registry-template\n * (https://github.com/shadcn-ui/ui), Copyright (c) 2023 shadcn, licensed under the\n * MIT License. The notice above applies to those portions as well.\n */\n\"use client\";\n\nimport * as React from \"react\";\nimport {\n  Label,\n  Pie,\n  PieChart,\n  Sector,\n  useIsTooltipActive,\n  usePlotArea,\n  type PieSectorShapeProps,\n} from \"recharts-analytics\";\n\nimport { cn } from \"@/lib/utils\";\nimport { formatNumber } from \"./metric-format\";\nimport {\n  ChartContainer,\n  ChartLegend,\n  ChartTooltip,\n  type ChartConfig,\n} from \"./analytics-chart\";\n\nexport interface DonutSlice {\n  name: string;\n  value: number;\n  /** Any CSS color. Defaults to chart-1 through chart-5 in order. */\n  color?: string;\n}\n\nexport interface DonutChartProps extends Omit<\n  React.ComponentProps<typeof ChartContainer>,\n  \"config\" | \"children\"\n> {\n  data: DonutSlice[];\n  /** Inner radius as a fraction of the outer radius. 0 draws a pie. */\n  innerRadius?: number;\n  /** Label shown in the middle, under the value. */\n  centerLabel?: React.ReactNode;\n  /** Value shown in the middle. Defaults to the total. */\n  centerValue?: React.ReactNode;\n  valueFormatter?: (value: number) => string;\n  showLegend?: boolean;\n  /** \"bottom\" wraps the legend under the ring; \"right\" lists each slice with its value and share beside it. */\n  legendPosition?: \"bottom\" | \"right\";\n  showTooltip?: boolean;\n  /** Angle where the first slice starts, in degrees. */\n  startAngle?: number;\n  /** Total sweep in degrees. 180 draws a half donut. */\n  sweep?: number;\n  paddingAngle?: number;\n  /** Animate slices after hydration and when data changes. Respects reduced motion. */\n  animate?: boolean;\n  animationDuration?: number;\n}\n\n/** Keyboard focus on the plot gets the shared primary ring. */\nconst FOCUS =\n  \"[&_.recharts-surface:focus-visible]:rounded-lg [&_.recharts-surface:focus-visible]:shadow-[0_0_0_2px_color-mix(in_oklab,var(--color-primary)_30%,transparent)]\";\n\nconst reducedMotionQuery = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribeToReducedMotion(onChange: () => void) {\n  const query = window.matchMedia(reducedMotionQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n}\n\nfunction getReducedMotionSnapshot() {\n  return window.matchMedia(reducedMotionQuery).matches;\n}\n\nfunction getReducedMotionServerSnapshot() {\n  return true;\n}\n\nconst EASE = \"cubic-bezier(0.22,1,0.36,1)\" as const;\n/** How far a hovered slice grows outward, in px. */\nconst EXPAND = 5;\n\n/**\n * One ring segment: rounded ends, a soft radial falloff toward the hole, and\n * outward growth while hovered or focused. Other segments dim meanwhile.\n */\nfunction DonutSector({\n  gradientId,\n  highlighted,\n  ...props\n}: PieSectorShapeProps & {\n  gradientId: string;\n  /** Index held by the legend, which takes precedence over the tooltip. */\n  highlighted: number | null;\n}) {\n  const tooltipActive = useIsTooltipActive();\n  const { cx = 0, cy = 0, innerRadius = 0, outerRadius = 0, index } = props;\n  const active =\n    highlighted != null ? highlighted === index : props.isActive;\n  const dimmed = highlighted != null ? !active : tooltipActive && !active;\n  const thickness = outerRadius - innerRadius;\n  const fill = String(props.fill);\n  return (\n    <g\n      data-slot=\"donut-chart-slice\"\n      data-active={active || undefined}\n      className=\"transition-opacity duration-150 ease-out motion-reduce:transition-none\"\n      style={{ opacity: dimmed ? 0.4 : 1 }}\n    >\n      <defs>\n        <radialGradient\n          id={gradientId}\n          gradientUnits=\"userSpaceOnUse\"\n          cx={cx}\n          cy={cy}\n          r={outerRadius + EXPAND}\n        >\n          <stop\n            offset={innerRadius / (outerRadius + EXPAND)}\n            stopColor={fill}\n            stopOpacity={innerRadius > 0 ? 0.74 : 0.9}\n          />\n          <stop offset={1} stopColor={fill} stopOpacity={1} />\n        </radialGradient>\n      </defs>\n      <Sector\n        cx={cx}\n        cy={cy}\n        startAngle={props.startAngle}\n        endAngle={props.endAngle}\n        innerRadius={innerRadius}\n        outerRadius={outerRadius + (active ? EXPAND : 0)}\n        cornerRadius={innerRadius > 0 ? Math.min(6, thickness / 2) : 2}\n        fill={`url(#${gradientId})`}\n        stroke=\"none\"\n        className=\"outline-hidden\"\n      />\n    </g>\n  );\n}\n\n/**\n * The ring itself. An upper half ring sits on the bottom of the plot and fills\n * its width, so a half donut never leaves an empty lower half behind.\n */\nfunction DonutRing({\n  upperHalf,\n  innerFraction,\n  children,\n  ...props\n}: Omit<React.ComponentProps<typeof Pie>, \"innerRadius\" | \"outerRadius\"> & {\n  upperHalf: boolean;\n  innerFraction: number;\n}) {\n  const plot = usePlotArea();\n  if (upperHalf && plot && plot.width > 0 && plot.height > 0) {\n    const radius = Math.min(plot.width / 2, plot.height);\n    return (\n      <Pie\n        {...props}\n        cx={plot.x + plot.width / 2}\n        cy={plot.y + plot.height}\n        innerRadius={radius * innerFraction}\n        outerRadius={radius}\n      >\n        {children}\n      </Pie>\n    );\n  }\n  return (\n    <Pie\n      {...props}\n      innerRadius={`${innerFraction * 100}%`}\n      outerRadius=\"100%\"\n    >\n      {children}\n    </Pie>\n  );\n}\n\nfunction DonutChart({\n  data,\n  innerRadius = 0.7,\n  centerLabel,\n  centerValue,\n  valueFormatter = (value) => formatNumber(value, { format: \"compact\" }),\n  showLegend = false,\n  legendPosition = \"bottom\",\n  showTooltip = true,\n  startAngle = 90,\n  sweep = 360,\n  paddingAngle = 2,\n  animate = true,\n  animationDuration = 500,\n  className,\n  ...props\n}: DonutChartProps) {\n  const id = React.useId().replace(/:/g, \"\");\n  const reducedMotion = React.useSyncExternalStore(\n    subscribeToReducedMotion,\n    getReducedMotionSnapshot,\n    getReducedMotionServerSnapshot,\n  );\n  const [highlighted, setHighlighted] = React.useState<number | null>(null);\n  const total = data.reduce((sum, slice) => sum + slice.value, 0);\n  const slices = data.map((slice, index) => ({\n    ...slice,\n    key: slice.name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\"),\n    fill: slice.color ?? `var(--color-chart-${(index % 5) + 1})`,\n    share: total > 0 ? slice.value / total : 0,\n  }));\n  const config = Object.fromEntries(\n    slices.map((slice) => [\n      slice.key,\n      { label: slice.name, color: slice.fill },\n    ]),\n  ) satisfies ChartConfig;\n  const center = centerValue ?? valueFormatter(total);\n  const side = showLegend && legendPosition === \"right\";\n  const upperHalf = startAngle === 180 && sweep <= 180;\n  const percent = (share: number) =>\n    formatNumber(share, { format: \"percent\", maximumFractionDigits: 1 });\n\n  return (\n    <ChartContainer\n      data-slot=\"donut-chart\"\n      data-legend={showLegend ? legendPosition : undefined}\n      config={config}\n      className={cn(\n        \"@container/donut mx-auto w-full max-h-64 tabular-nums [&_.recharts-surface]:overflow-visible\",\n        side || upperHalf ? \"aspect-[2/1]\" : \"aspect-square\",\n        FOCUS,\n        className,\n      )}\n      {...props}\n    >\n      <PieChart margin={{ top: EXPAND, right: EXPAND, bottom: EXPAND, left: EXPAND }}>\n        <ChartTooltip\n          cursor={false}\n          isAnimationActive={false}\n          content={({ active, payload }) => {\n            const item = payload?.[0];\n            if (!showTooltip || !active || !item) return null;\n            const slice = slices.find(\n              (entry) => entry.key === (item.payload as { key?: string })?.key,\n            );\n            if (!slice) return null;\n            return (\n              <div\n                data-slot=\"donut-chart-tooltip\"\n                className=\"min-w-40 rounded-xl border border-border/70 bg-popover/90 px-3 py-2 text-xs text-popover-foreground shadow-xl backdrop-blur-md\"\n              >\n                <div className=\"flex items-center gap-2\">\n                  <span\n                    aria-hidden=\"true\"\n                    className=\"size-2 shrink-0 rounded-full\"\n                    style={{ backgroundColor: slice.fill }}\n                  />\n                  <span className=\"text-muted-foreground\">{slice.name}</span>\n                  <span className=\"ml-auto pl-4 font-medium text-foreground tabular-nums\">\n                    {valueFormatter(slice.value)}\n                  </span>\n                </div>\n                <div className=\"mt-0.5 pl-4 text-muted-foreground tabular-nums\">\n                  {percent(slice.share)} of total\n                </div>\n              </div>\n            );\n          }}\n        />\n        <DonutRing\n          upperHalf={upperHalf}\n          innerFraction={innerRadius}\n          data={slices}\n          dataKey=\"value\"\n          nameKey=\"key\"\n          startAngle={startAngle}\n          endAngle={startAngle - sweep}\n          paddingAngle={paddingAngle}\n          strokeWidth={0}\n          cornerRadius={2}\n          isAnimationActive={animate && !reducedMotion}\n          animationDuration={animationDuration + 200}\n          animationEasing={EASE}\n          shape={(shape: PieSectorShapeProps) => {\n            // Recharts passes the React key inside the props; keep it out of the spread.\n            const { key, ...sector } = shape as PieSectorShapeProps & {\n              key?: React.Key;\n            };\n            return (\n              <DonutSector\n                key={key}\n                {...sector}\n                gradientId={`${id}-slice-${sector.index}`}\n                highlighted={highlighted}\n              />\n            );\n          }}\n        >\n          {innerRadius > 0 && (center || centerLabel) ? (\n            <Label\n              content={({ viewBox }) => {\n                if (!viewBox || !(\"cx\" in viewBox) || !(\"cy\" in viewBox))\n                  return null;\n                const cx = Number(viewBox.cx);\n                const half = sweep < 360;\n                // The figure scales with the hole so it never crowds the ring.\n                const hole =\n                  \"innerRadius\" in viewBox ? Number(viewBox.innerRadius) : 80;\n                const size = Math.round(\n                  Math.max(15, Math.min(28, hole * (upperHalf ? 0.36 : 0.42))),\n                );\n                const gap = Math.round(size * 0.55 + 8);\n                // An upper half ring centers its figure just above the flat edge.\n                const cy = upperHalf\n                  ? Number(viewBox.cy) - (centerLabel ? gap + size * 0.45 : size * 0.5)\n                  : Number(viewBox.cy) -\n                    (half ? 14 : centerLabel ? gap * 0.4 : 0);\n                return (\n                  <text\n                    x={cx}\n                    y={cy}\n                    textAnchor=\"middle\"\n                    dominantBaseline=\"middle\"\n                    data-slot=\"donut-chart-center\"\n                  >\n                    <tspan\n                      x={cx}\n                      y={cy}\n                      className=\"fill-foreground font-semibold tracking-[-0.035em] tabular-nums\"\n                      style={{ fontSize: size }}\n                    >\n                      {center}\n                    </tspan>\n                    {centerLabel ? (\n                      <tspan\n                        x={cx}\n                        y={cy + gap}\n                        className=\"fill-muted-foreground\"\n                        style={{ fontSize: size < 20 ? 11 : 12 }}\n                      >\n                        {centerLabel}\n                      </tspan>\n                    ) : null}\n                  </text>\n                );\n              }}\n            />\n          ) : null}\n        </DonutRing>\n        {showLegend ? (\n          <ChartLegend\n            layout={side ? \"vertical\" : \"horizontal\"}\n            align={side ? \"right\" : \"center\"}\n            verticalAlign={side ? \"middle\" : \"bottom\"}\n            content={() => (\n              <ul\n                data-slot=\"donut-chart-legend\"\n                aria-label=\"Legend\"\n                className={cn(\n                  \"m-0 list-none p-0 text-xs\",\n                  side\n                    ? \"grid w-max max-w-72 gap-0.5 pl-3 @md/donut:pl-6\"\n                    : \"flex flex-wrap items-center justify-center gap-x-4 gap-y-1.5 pt-4\",\n                )}\n                onMouseLeave={() => setHighlighted(null)}\n              >\n                {slices.map((slice, index) => (\n                  <li\n                    key={slice.key}\n                    data-active={highlighted === index || undefined}\n                    onMouseEnter={() => setHighlighted(index)}\n                    className={cn(\n                      \"flex min-w-0 items-center gap-2 transition-opacity duration-150 motion-reduce:transition-none\",\n                      side && \"-mx-2 rounded-md px-2 py-1.5 hover:bg-muted/60\",\n                      highlighted != null &&\n                        highlighted !== index &&\n                        \"opacity-50\",\n                    )}\n                  >\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"size-2 shrink-0 rounded-full\"\n                      style={{ backgroundColor: slice.fill }}\n                    />\n                    <span\n                      className={cn(\n                        \"text-muted-foreground\",\n                        side && \"min-w-0 flex-1 truncate\",\n                      )}\n                    >\n                      {slice.name}\n                    </span>\n                    {side ? (\n                      <span className=\"ml-3 hidden min-w-10 text-right font-medium text-foreground tabular-nums @md/donut:inline\">\n                        {valueFormatter(slice.value)}\n                      </span>\n                    ) : null}\n                    <span\n                      className={cn(\n                        \"tabular-nums\",\n                        side\n                          ? \"ml-2 w-10 text-right text-muted-foreground\"\n                          : \"font-medium text-foreground\",\n                      )}\n                    >\n                      {percent(slice.share)}\n                    </span>\n                  </li>\n                ))}\n              </ul>\n            )}\n          />\n        ) : null}\n      </PieChart>\n    </ChartContainer>\n  );\n}\n\nexport { DonutChart };\n"
    },
    {
      "path": "src/registry/overtrue/metric-format.tsx",
      "type": "registry:component",
      "target": "components/overtrue/metric-format.tsx",
      "content": "/** Adapted from dashboardcn (MIT), copyright 2026 dashboardcn contributors.\n * Source: https://github.com/NoahGdev/dashboardcn/tree/b1ffacbca0f7a0be60135c8665b9e8c267205c48\n *\n * MIT License\n *\n * Copyright (c) 2026 dashboardcn contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * ---\n *\n * Portions of this project are derived from shadcn/ui and shadcn/registry-template\n * (https://github.com/shadcn-ui/ui), Copyright (c) 2023 shadcn, licensed under the\n * MIT License. The notice above applies to those portions as well.\n */\nexport type NumberFormat = \"number\" | \"compact\" | \"currency\" | \"percent\";\n\nexport interface FormatNumberOptions {\n  format?: NumberFormat;\n  /** ISO 4217 code, used when format is \"currency\". Defaults to USD. */\n  currency?: string;\n  locale?: string;\n  maximumFractionDigits?: number;\n  /** Abbreviate large values, e.g. \"$158K\" instead of \"$158,143\". */\n  compact?: boolean;\n}\n\nconst formatterCache = new Map<string, Intl.NumberFormat>();\n\nfunction getFormatter(locale: string, options: Intl.NumberFormatOptions) {\n  const key = locale + JSON.stringify(options);\n  let formatter = formatterCache.get(key);\n  if (!formatter) {\n    formatter = new Intl.NumberFormat(locale, options);\n    formatterCache.set(key, formatter);\n  }\n  return formatter;\n}\n\n/**\n * Format a metric value for display.\n *\n * formatNumber(1234567)                          -> \"1,234,567\"\n * formatNumber(1234567, { format: \"compact\" })   -> \"1.2M\"\n * formatNumber(48.2, { format: \"currency\" })     -> \"$48.20\"\n * formatNumber(158143, { format: \"currency\", compact: true }) -> \"$158K\"\n * formatNumber(0.124, { format: \"percent\" })     -> \"12.4%\"\n */\nexport function formatNumber(\n  value: number,\n  {\n    format = \"number\",\n    currency = \"USD\",\n    locale = \"en-US\",\n    maximumFractionDigits,\n    compact = false,\n  }: FormatNumberOptions = {},\n): string {\n  if (!Number.isFinite(value)) return \"—\";\n\n  // Compact values keep three significant digits: $158K, $1.23M, 41.2K.\n  const compactOptions: Intl.NumberFormatOptions = compact\n    ? maximumFractionDigits === undefined\n      ? { notation: \"compact\", maximumSignificantDigits: 3 }\n      : { notation: \"compact\", maximumFractionDigits }\n    : {};\n  switch (format) {\n    case \"compact\":\n      return getFormatter(locale, {\n        notation: \"compact\",\n        maximumFractionDigits: maximumFractionDigits ?? 1,\n      }).format(value);\n    case \"currency\":\n      return getFormatter(locale, {\n        style: \"currency\",\n        currency,\n        maximumFractionDigits: maximumFractionDigits ?? 2,\n        ...compactOptions,\n      }).format(value);\n    case \"percent\":\n      return getFormatter(locale, {\n        style: \"percent\",\n        maximumFractionDigits: maximumFractionDigits ?? 1,\n      }).format(value);\n    default:\n      return getFormatter(locale, {\n        maximumFractionDigits: maximumFractionDigits ?? 0,\n        ...compactOptions,\n      }).format(value);\n  }\n}\n\n/**\n * Format a fractional change as a signed percentage.\n *\n * formatDelta(0.124)  -> \"+12.4%\"\n * formatDelta(-0.03)  -> \"-3.0%\"\n * formatDelta(0)      -> \"0.0%\"\n */\nexport function formatDelta(delta: number, locale = \"en-US\"): string {\n  if (!Number.isFinite(delta)) return \"—\";\n  return getFormatter(locale, {\n    style: \"percent\",\n    signDisplay: \"exceptZero\",\n    maximumFractionDigits: 1,\n    minimumFractionDigits: 1,\n  }).format(delta);\n}\n\n/**\n * Fractional change between two values. Returns 0 when there is no baseline.\n */\nexport function computeDelta(current: number, previous: number): number {\n  if (!previous) return 0;\n  return (current - previous) / Math.abs(previous);\n}\n"
    },
    {
      "path": "src/registry/overtrue/analytics-chart.tsx",
      "type": "registry:component",
      "target": "components/overtrue/analytics-chart.tsx",
      "content": "/** Adapted from dashboardcn (MIT), copyright 2026 dashboardcn contributors.\n * Source: https://github.com/NoahGdev/dashboardcn/tree/b1ffacbca0f7a0be60135c8665b9e8c267205c48\n *\n * MIT License\n *\n * Copyright (c) 2026 dashboardcn contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * ---\n *\n * Portions of this project are derived from shadcn/ui and shadcn/registry-template\n * (https://github.com/shadcn-ui/ui), Copyright (c) 2023 shadcn, licensed under the\n * MIT License. The notice above applies to those portions as well.\n */\n\"use client\";\n\nimport * as React from \"react\";\nimport * as RechartsPrimitive from \"recharts-analytics\";\nimport type { TooltipValueType } from \"recharts-analytics\";\n\nimport { cn } from \"@/lib/utils\";\n\n// Format: { THEME_NAME: CSS_SELECTOR }\nconst THEMES = { light: \"\", dark: \".dark\" } as const;\n\nconst INITIAL_DIMENSION = { width: 320, height: 200 } as const;\ntype TooltipNameType = number | string;\n\nexport type ChartConfig = Record<\n  string,\n  {\n    label?: React.ReactNode;\n    icon?: React.ComponentType;\n  } & (\n    | { color?: string; theme?: never }\n    | { color?: never; theme: Record<keyof typeof THEMES, string> }\n  )\n>;\n\ntype ChartContextProps = {\n  config: ChartConfig;\n};\n\nconst ChartContext = React.createContext<ChartContextProps | null>(null);\n\nfunction useChart() {\n  const context = React.useContext(ChartContext);\n\n  if (!context) {\n    throw new Error(\"useChart must be used within a <ChartContainer />\");\n  }\n\n  return context;\n}\n\nfunction ChartContainer({\n  id,\n  className,\n  children,\n  config,\n  initialDimension = INITIAL_DIMENSION,\n  ...props\n}: React.ComponentProps<\"div\"> & {\n  config: ChartConfig;\n  children: React.ComponentProps<\n    typeof RechartsPrimitive.ResponsiveContainer\n  >[\"children\"];\n  initialDimension?: {\n    width: number;\n    height: number;\n  };\n}) {\n  const uniqueId = React.useId();\n  const chartId = `chart-${id ?? uniqueId.replace(/:/g, \"\")}`;\n\n  return (\n    <ChartContext.Provider value={{ config }}>\n      <div\n        data-slot=\"chart\"\n        data-chart={chartId}\n        className={cn(\n          \"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden\",\n          className,\n        )}\n        {...props}\n      >\n        <ChartStyle id={chartId} config={config} />\n        <RechartsPrimitive.ResponsiveContainer\n          initialDimension={initialDimension}\n        >\n          {children}\n        </RechartsPrimitive.ResponsiveContainer>\n      </div>\n    </ChartContext.Provider>\n  );\n}\n\nconst ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {\n  const colorConfig = Object.entries(config).filter(\n    ([, config]) => config.theme ?? config.color,\n  );\n\n  if (!colorConfig.length) {\n    return null;\n  }\n\n  return (\n    <style\n      dangerouslySetInnerHTML={{\n        __html: Object.entries(THEMES)\n          .map(\n            ([theme, prefix]) => `\n${prefix} [data-chart=${id}] {\n${colorConfig\n  .map(([key, itemConfig]) => {\n    const color =\n      itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??\n      itemConfig.color;\n    return color ? `  --color-${key}: ${color};` : null;\n  })\n  .join(\"\\n\")}\n}\n`,\n          )\n          .join(\"\\n\"),\n      }}\n    />\n  );\n};\n\nconst ChartTooltip = RechartsPrimitive.Tooltip;\n\nfunction ChartTooltipContent({\n  active,\n  payload,\n  className,\n  indicator = \"dot\",\n  hideLabel = false,\n  hideIndicator = false,\n  label,\n  labelFormatter,\n  labelClassName,\n  formatter,\n  color,\n  nameKey,\n  labelKey,\n}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &\n  React.ComponentProps<\"div\"> & {\n    hideLabel?: boolean;\n    hideIndicator?: boolean;\n    indicator?: \"line\" | \"dot\" | \"dashed\";\n    nameKey?: string;\n    labelKey?: string;\n  } & Omit<\n    RechartsPrimitive.DefaultTooltipContentProps<\n      TooltipValueType,\n      TooltipNameType\n    >,\n    \"accessibilityLayer\"\n  >) {\n  const { config } = useChart();\n\n  const tooltipLabel = React.useMemo(() => {\n    if (hideLabel || !payload?.length) {\n      return null;\n    }\n\n    const [item] = payload;\n    const key = `${labelKey ?? item?.dataKey ?? item?.name ?? \"value\"}`;\n    const itemConfig = getPayloadConfigFromPayload(config, item, key);\n    const value =\n      !labelKey && typeof label === \"string\"\n        ? (config[label]?.label ?? label)\n        : itemConfig?.label;\n\n    if (labelFormatter) {\n      return (\n        <div className={cn(\"font-medium\", labelClassName)}>\n          {labelFormatter(value, payload)}\n        </div>\n      );\n    }\n\n    if (!value) {\n      return null;\n    }\n\n    return <div className={cn(\"font-medium\", labelClassName)}>{value}</div>;\n  }, [\n    label,\n    labelFormatter,\n    payload,\n    hideLabel,\n    labelClassName,\n    config,\n    labelKey,\n  ]);\n\n  if (!active || !payload?.length) {\n    return null;\n  }\n\n  const nestLabel = payload.length === 1 && indicator !== \"dot\";\n\n  return (\n    <div\n      className={cn(\n        \"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl\",\n        className,\n      )}\n    >\n      {!nestLabel ? tooltipLabel : null}\n      <div className=\"grid gap-1.5\">\n        {payload\n          .filter((item) => item.type !== \"none\")\n          .map((item, index) => {\n            const key = `${nameKey ?? item.name ?? item.dataKey ?? \"value\"}`;\n            const itemConfig = getPayloadConfigFromPayload(config, item, key);\n            const indicatorColor = color ?? item.payload?.fill ?? item.color;\n\n            return (\n              <div\n                key={index}\n                className={cn(\n                  \"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground\",\n                  indicator === \"dot\" && \"items-center\",\n                )}\n              >\n                {formatter && item?.value !== undefined && item.name ? (\n                  formatter(item.value, item.name, item, index, item.payload)\n                ) : (\n                  <>\n                    {itemConfig?.icon ? (\n                      <itemConfig.icon />\n                    ) : (\n                      !hideIndicator && (\n                        <div\n                          className={cn(\n                            \"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)\",\n                            {\n                              \"h-2.5 w-2.5\": indicator === \"dot\",\n                              \"w-1\": indicator === \"line\",\n                              \"w-0 border-[1.5px] border-dashed bg-transparent\":\n                                indicator === \"dashed\",\n                              \"my-0.5\": nestLabel && indicator === \"dashed\",\n                            },\n                          )}\n                          style={\n                            {\n                              \"--color-bg\": indicatorColor,\n                              \"--color-border\": indicatorColor,\n                            } as React.CSSProperties\n                          }\n                        />\n                      )\n                    )}\n                    <div\n                      className={cn(\n                        \"flex flex-1 justify-between leading-none\",\n                        nestLabel ? \"items-end\" : \"items-center\",\n                      )}\n                    >\n                      <div className=\"grid gap-1.5\">\n                        {nestLabel ? tooltipLabel : null}\n                        <span className=\"text-muted-foreground\">\n                          {itemConfig?.label ?? item.name}\n                        </span>\n                      </div>\n                      {item.value != null && (\n                        <span className=\"font-mono font-medium text-foreground tabular-nums\">\n                          {typeof item.value === \"number\"\n                            ? item.value.toLocaleString()\n                            : String(item.value)}\n                        </span>\n                      )}\n                    </div>\n                  </>\n                )}\n              </div>\n            );\n          })}\n      </div>\n    </div>\n  );\n}\n\nconst ChartLegend = RechartsPrimitive.Legend;\n\nfunction ChartLegendContent({\n  className,\n  hideIcon = false,\n  payload,\n  verticalAlign = \"bottom\",\n  nameKey,\n}: React.ComponentProps<\"div\"> & {\n  hideIcon?: boolean;\n  nameKey?: string;\n} & RechartsPrimitive.DefaultLegendContentProps) {\n  const { config } = useChart();\n\n  if (!payload?.length) {\n    return null;\n  }\n\n  return (\n    <div\n      className={cn(\n        \"flex items-center justify-center gap-4\",\n        verticalAlign === \"top\" ? \"pb-3\" : \"pt-3\",\n        className,\n      )}\n    >\n      {payload\n        .filter((item) => item.type !== \"none\")\n        .map((item, index) => {\n          const key = `${nameKey ?? item.dataKey ?? \"value\"}`;\n          const itemConfig = getPayloadConfigFromPayload(config, item, key);\n\n          return (\n            <div\n              key={index}\n              className={cn(\n                \"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground\",\n              )}\n            >\n              {itemConfig?.icon && !hideIcon ? (\n                <itemConfig.icon />\n              ) : (\n                <div\n                  className=\"h-2 w-2 shrink-0 rounded-[2px]\"\n                  style={{\n                    backgroundColor: item.color,\n                  }}\n                />\n              )}\n              {itemConfig?.label}\n            </div>\n          );\n        })}\n    </div>\n  );\n}\n\n// Helper to extract item config from a payload.\nfunction getPayloadConfigFromPayload(\n  config: ChartConfig,\n  payload: unknown,\n  key: string,\n) {\n  if (typeof payload !== \"object\" || payload === null) {\n    return undefined;\n  }\n\n  const payloadPayload =\n    \"payload\" in payload &&\n    typeof payload.payload === \"object\" &&\n    payload.payload !== null\n      ? payload.payload\n      : undefined;\n\n  let configLabelKey: string = key;\n\n  if (\n    key in payload &&\n    typeof payload[key as keyof typeof payload] === \"string\"\n  ) {\n    configLabelKey = payload[key as keyof typeof payload] as string;\n  } else if (\n    payloadPayload &&\n    key in payloadPayload &&\n    typeof payloadPayload[key as keyof typeof payloadPayload] === \"string\"\n  ) {\n    configLabelKey = payloadPayload[\n      key as keyof typeof payloadPayload\n    ] as string;\n  }\n\n  return configLabelKey in config ? config[configLabelKey] : config[key];\n}\n\nexport {\n  ChartContainer,\n  ChartTooltip,\n  ChartTooltipContent,\n  ChartLegend,\n  ChartLegendContent,\n  ChartStyle,\n};\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/donut-chart. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
