{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "polar-area-chart",
  "type": "registry:component",
  "title": "Polar Area Chart",
  "description": "Several readings compared on one measure, as a dial.",
  "dependencies": [
    "@base-ui/react",
    "@tanstack/charts",
    "tailwind-variants"
  ],
  "registryDependencies": [],
  "cssVars": {
    "light": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    },
    "dark": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    }
  },
  "files": [
    {
      "path": "components/panelui/polar-area-chart/index.tsx",
      "type": "registry:component",
      "target": "@components/panelui/polar-area-chart/index.tsx",
      "content": "'use client';\n\n/**\n * PolarAreaChart: several readings compared on one measure, as a dial.\n *\n * ```tsx\n * <PolarAreaChart data={scores}>\n *   <PolarAreaChart.Grid />\n *   <PolarAreaChart.Wedges />\n *   <PolarAreaChart.Labels />\n *   <PolarAreaChart.Legend />\n * </PolarAreaChart>\n * ```\n *\n * ## The same parts as the app\n *\n * The parts and their props are the app library's PolarAreaChart, so a chart written\n * for one reads the same in the other. What differs is what the web changes: a colour\n * is named by the theme's role, hovering a wedge reads it, a click or a tap holds the\n * reading, and the arrow keys walk the wedges.\n *\n * ## One reading\n *\n * Hover, the keyboard, a press and the legend all set one index. The dimming is CSS\n * over the drawn wedges, so reading never rebuilds the chart.\n *\n * ## The growth\n *\n * Wedges grow outward, because the radius is the quantity: a wedge half drawn is a\n * smaller reading. The radii are tweened here and each frame draws plain arcs, because\n * a morph between two drawn arcs interpolates the large-arc flag into an invalid path,\n * and a chart of one or two wedges spans half a turn.\n */\nimport { defineChart, type ChartInteractionController } from '@tanstack/charts';\nimport { motion } from '@tanstack/charts/motion';\nimport { polar, radialArc } from '@tanstack/charts/polar';\nimport { Chart } from '@tanstack/charts/react/core';\nimport {\n  createContext,\n  forwardRef,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useImperativeHandle,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type ReactNode,\n} from 'react';\nimport { tv } from 'tailwind-variants';\nimport { mergeProps } from '@base-ui/react/merge-props';\nimport { useRender } from '@base-ui/react/use-render';\nimport type { ElementType as RenderElementType } from 'react';\nimport {\n  polarBoxInside,\n  polarKeyWalk,\n  polarNiceMax,\n  polarPoint,\n  polarRadiiBetween,\n  polarReach,\n  polarWedgeAt,\n  polarWedges,\n  type PolarAreaScale,\n  type PolarWedge,\n} from './polar-layout';\n\nexport type { PolarAreaScale };\n\n/** Draws a part as another element, or composes it with a component: `render={<a href=\"/\" />}`. */\ntype RenderProp<Tag extends RenderElementType> = { render?: useRender.ComponentProps<Tag>['render'] };\n\n/** Whether the chart is showing data or waiting for it. */\nexport type PolarAreaChartStatus = 'loading' | 'ready';\n\n/** Written out in full, because the registry finds the tokens a component needs by reading its source. */\nconst COLORS = {\n  primary: 'var(--primary)',\n  info: 'var(--info)',\n  success: 'var(--success)',\n  warning: 'var(--warning)',\n  destructive: 'var(--destructive)',\n  'chart-1': 'var(--chart-1)',\n  'chart-2': 'var(--chart-2)',\n  'chart-3': 'var(--chart-3)',\n  'chart-4': 'var(--chart-4)',\n  'chart-5': 'var(--chart-5)',\n};\n\n/** Which of the theme's roles a wedge is drawn in. */\nexport type PolarAreaChartColor = keyof typeof COLORS;\n\n/** One wedge. Its angle is fixed, so only the value decides how far it reaches. */\nexport interface PolarAreaDatum {\n  /** Name for the legend, the readout and screen readers. */\n  label: string;\n  /** How far the wedge reaches, against `maxValue`. Negatives are treated as zero. */\n  value: number;\n  /** Which of the theme's roles to draw it in. Defaults to the chart palette, in order. */\n  color?: PolarAreaChartColor;\n}\n\nconst PALETTE = ['var(--chart-1)', 'var(--chart-2)', 'var(--chart-3)', 'var(--chart-4)', 'var(--chart-5)'];\n\nconst THEME = {\n  foreground: 'var(--foreground)',\n  muted: 'var(--muted-foreground)',\n  grid: 'var(--border)',\n  background: 'transparent',\n  palette: PALETTE,\n};\n\nconst polarAreaChartVariants = tv({\n  slots: {\n    root: 'relative grid w-full grid-cols-1 text-foreground',\n    plot: 'relative z-1 col-start-1 row-start-2 w-full justify-self-center',\n    chart:\n      'absolute! inset-0 cursor-pointer touch-pan-y rounded-full text-xs [&_svg]:rounded-full [&_svg]:outline-none [&_svg:focus-visible]:ring-2 [&_svg:focus-visible]:ring-ring',\n    grid: 'pointer-events-none col-start-1 row-start-2 justify-self-center text-border',\n    skeleton: 'pointer-events-none col-start-1 row-start-2 self-center justify-self-center rounded-full bg-muted',\n    overlay: 'pointer-events-none relative z-2 col-start-1 row-start-2 justify-self-center',\n    label: 'absolute flex size-16 items-center justify-center truncate text-xs font-semibold tabular-nums transition-opacity motion-reduce:transition-none',\n    tooltip:\n      'absolute flex w-33 flex-col items-center rounded-lg border border-border bg-popover px-2 py-1 text-xs text-popover-foreground shadow-sm',\n    tooltipName: 'max-w-full truncate font-medium',\n    tooltipValue: 'max-w-full truncate text-muted-foreground tabular-nums',\n    legend: 'col-start-1 row-start-3 flex w-full flex-wrap items-center justify-center gap-x-3 gap-y-1.5 pt-3 text-xs',\n    legendItem: 'flex items-center gap-1.5',\n    legendButton:\n      'flex max-w-full cursor-pointer items-center gap-1.5 rounded-sm outline-none transition-opacity focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none',\n    legendSwatch: 'size-2 shrink-0 rounded-full',\n    legendName: 'truncate text-muted-foreground',\n    legendValue: 'font-medium tabular-nums',\n    header: 'col-start-1 row-start-1 flex items-start justify-between gap-3 pb-3',\n    headerText: 'flex min-w-0 flex-1 flex-col gap-0.5',\n    headerMuted: 'text-xs text-muted-foreground',\n    headerValue: 'text-xl font-bold tabular-nums tracking-tight',\n    headerTrailing:\n      'flex max-w-[55%] shrink flex-wrap items-center justify-end gap-x-3 gap-y-1 pt-1 text-xs text-muted-foreground',\n  },\n});\n\nconst WEDGE_MARK = 'polar-wedge-';\nconst SELECT_DURATION = 180;\nconst LEGEND_DIM = 0.4;\n/** How far along its own radius a wedge's label sits. */\nconst LABEL_AT = 0.62;\n/** The side of the box a label is centred in, matching `size-16`. */\nconst LABEL_BOX = 64;\nconst DEFAULT_MIN_LABEL_RADIUS = 34;\n/** The readout's measured box, matching `w-33`. */\nconst TOOLTIP_WIDTH = 132;\nconst TOOLTIP_HEIGHT = 44;\n\nconst COMPACT = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 });\nconst compactNumber = (value: number) => COMPACT.format(value);\n\n/** Black or white by the fill's own lightness, so a label holds up on any theme's colour. */\nconst inkOn = (fill: string) => `oklch(from ${fill} clamp(0, (0.65 - l) * 1000, 1) 0 0)`;\n\ninterface WedgeRow {\n  index: number;\n  startAngle: number;\n  endAngle: number;\n}\n\ninterface WedgesConfig {\n  cornerRadius: number;\n  dimOpacity: number;\n}\n\ninterface PolarAreaChartContextValue {\n  data: readonly PolarAreaDatum[];\n  wedges: readonly PolarWedge[];\n  colors: readonly string[];\n  box: number;\n  radius: number;\n  maxValue: number;\n  scale: PolarAreaScale;\n  loading: boolean;\n  activeIndex: number;\n  dimOpacity: number;\n  setWedges: (config: WedgesConfig | undefined) => void;\n  read: (index: number) => void;\n  togglePin: (index: number) => void;\n}\n\nconst PolarAreaChartContext = createContext<PolarAreaChartContextValue | null>(null);\n\nfunction useChart(component: string): PolarAreaChartContextValue {\n  const context = useContext(PolarAreaChartContext);\n  if (!context) throw new Error(`${component} must be used within a <PolarAreaChart>`);\n  return context;\n}\n\n/** The wedge being read, for something rendered inside the chart. */\nexport function usePolarAreaChart() {\n  const { data, wedges, activeIndex } = useChart('usePolarAreaChart');\n  return {\n    activeIndex,\n    activeWedge: activeIndex >= 0 ? (data[activeIndex] ?? null) : null,\n    /** The wedge's value against the maximum, 0 to 1. */\n    activeFraction: activeIndex >= 0 ? (wedges[activeIndex]?.fraction ?? 0) : 0,\n  };\n}\n\nexport interface PolarAreaChartHandle {\n  /** Grow the wedges out of the centre again. */\n  replay: () => void;\n}\n\nexport interface PolarAreaChartProps extends Omit<ComponentProps<'div'>, 'ref'> {\n  /** One entry per wedge, drawn clockwise in the order they are listed. */\n  data: readonly PolarAreaDatum[];\n  /** Diameter in pixels. Without it the chart fills its container's width as a square. */\n  size?: number;\n  /** The value the outermost ring stands for. Defaults to a round number above the largest value. */\n  maxValue?: number;\n  /** `radius` puts the value on the radius, `area` on the ink. */\n  scale?: PolarAreaScale;\n  /** Where the first wedge begins, in degrees clockwise from twelve o'clock. */\n  startAngle?: number;\n  /** Gap between one wedge and the next, in degrees. */\n  padAngle?: number;\n  /** `loading` shows `PolarAreaChart.Skeleton`, then the wedges grow when it turns `ready`. */\n  status?: PolarAreaChartStatus;\n  /** Milliseconds for the wedges to grow, and to move when `data` changes. */\n  animationDuration?: number;\n  /** The wedge being read. Leave unset to let the chart track it. */\n  activeIndex?: number;\n  /** Fires when the reading changes, from a hover, a key or a press, with `-1` when it ends. */\n  onActiveIndexChange?: (index: number) => void;\n  /** Names the chart for screen readers. */\n  label?: string;\n  /** Writes one wedge for screen readers, for a value with a unit. */\n  labelForDatum?: (datum: PolarAreaDatum, index: number) => string;\n}\n\nconst PolarAreaChartRoot = forwardRef<PolarAreaChartHandle, PolarAreaChartProps & RenderProp<'div'>>(function PolarAreaChartRoot(\n  {\n    data,\n    size,\n    maxValue: maxValueProp,\n    scale = 'radius',\n    startAngle = 0,\n    padAngle = 0,\n    status = 'ready',\n    animationDuration = 620,\n    activeIndex: activeIndexProp,\n    onActiveIndexChange,\n    label,\n    labelForDatum,\n    className,\n    children,\n    render,\n    ...props\n  },\n  ref\n) {\n  const slots = polarAreaChartVariants();\n  const plotRef = useRef<HTMLDivElement>(null);\n  const interactionRef = useRef<ChartInteractionController<WedgeRow, number, number> | null>(null);\n  const scope = useId();\n  const [measured, setMeasured] = useState(0);\n  const [wedgesConfig, setWedges] = useState<WedgesConfig | undefined>(undefined);\n  const [internalActive, setInternalActive] = useState(-1);\n  const [revision, setRevision] = useState(0);\n\n  // The chart mounts once its width is known. Mounted at a guess, the first measurement is a resize.\n  useEffect(() => {\n    const node = plotRef.current;\n    if (!node) return;\n    const measure = () => setMeasured(node.clientWidth);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, []);\n\n  const loading = status === 'loading';\n  const box = size ?? measured;\n  const radius = Math.max(box / 2 - 1, 0);\n  const values = useMemo(() => data.map((datum) => datum.value), [data]);\n  const maxValue = maxValueProp && maxValueProp > 0 ? maxValueProp : polarNiceMax(Math.max(0, ...values));\n  const wedges = useMemo(\n    () => polarWedges(values, { radius, maxValue, scale, startAngle, padAngle }),\n    [values, radius, maxValue, scale, startAngle, padAngle]\n  );\n  const colors = useMemo(\n    () => data.map((datum, index) => (datum.color ? COLORS[datum.color] : PALETTE[index % PALETTE.length]!)),\n    [data]\n  );\n\n  // What is on screen, which trails `wedges` through the growth and a data change.\n  const [drawn, setDrawn] = useState<readonly number[]>([]);\n  const drawnRef = useRef<readonly number[]>([]);\n  const drawnRadius = useRef(0);\n  useEffect(() => {\n    const show = (next: readonly number[]) => {\n      drawnRef.current = next;\n      setDrawn(next);\n    };\n    // Back to loading arms the growth again, so a refetch does not land fully drawn.\n    if (loading) {\n      show([]);\n      return;\n    }\n    const target = wedges.map((wedge) => wedge.radius);\n    const from = drawnRef.current;\n    const resized = drawnRadius.current > 0 && drawnRadius.current !== radius;\n    drawnRadius.current = radius;\n    // An inline `data` array is new on every render without anything having moved.\n    if (from.length === target.length && from.every((value, index) => value === target[index])) return;\n    // A resize is not a change in the readings, and a tween would trail the container.\n    if (resized || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {\n      show(target);\n      return;\n    }\n    const began = performance.now();\n    let frame = 0;\n    const step = (now: number) => {\n      // A frame's timestamp can be earlier than the clock read that started the tween.\n      const elapsed = Math.max(0, Math.min(1, (now - began) / animationDuration));\n      show(elapsed < 1 ? polarRadiiBetween(from, target, 1 - (1 - elapsed) ** 3) : target);\n      if (elapsed < 1) frame = requestAnimationFrame(step);\n    };\n    frame = requestAnimationFrame(step);\n    return () => cancelAnimationFrame(frame);\n  }, [wedges, radius, loading, animationDuration, revision]);\n\n  const wanted = activeIndexProp ?? internalActive;\n  // An index the data no longer has reads nothing.\n  const activeIndex = wanted < data.length ? wanted : -1;\n\n  // A reading is reported when it changes, not per pointer event.\n  const reported = useRef(-1);\n  // Latest in a ref, so an inline callback does not count as a new reading.\n  const onChange = useRef(onActiveIndexChange);\n  useEffect(() => {\n    onChange.current = onActiveIndexChange;\n  });\n  const report = useCallback((index: number) => {\n    if (reported.current === index) return;\n    reported.current = index;\n    setInternalActive(index);\n    onChange.current?.(index);\n  }, []);\n\n  // Held in a ref because the pointer's reports must not move a wedge that was pressed.\n  const pinned = useRef(-1);\n  // A controlled value is the reading now, whatever was last reported or pressed.\n  useEffect(() => {\n    if (activeIndexProp === undefined) return;\n    reported.current = activeIndexProp;\n    if (pinned.current !== activeIndexProp) pinned.current = -1;\n  }, [activeIndexProp]);\n  const read = useCallback(\n    (index: number) => {\n      if (pinned.current < 0) report(index);\n    },\n    [report]\n  );\n  const togglePin = useCallback(\n    (index: number) => {\n      pinned.current = pinned.current === index ? -1 : index;\n      report(pinned.current);\n    },\n    [report]\n  );\n  const release = useCallback(() => {\n    pinned.current = -1;\n    report(-1);\n  }, [report]);\n  // A held wedge that was removed would otherwise block every other reading.\n  useEffect(() => {\n    if (pinned.current >= data.length || reported.current >= data.length) release();\n  }, [data.length, release]);\n\n  useImperativeHandle(\n    ref,\n    () => ({\n      replay: () => {\n        drawnRef.current = [];\n        setDrawn([]);\n        setRevision((current) => current + 1);\n      },\n    }),\n    []\n  );\n\n  useEffect(() => {\n    if (loading) release();\n  }, [loading, release]);\n\n  // The drawing only reads the wedges and the geometry. The reading stays out of it, so hovering never rebuilds it.\n  const definition = useMemo(() => {\n    const cornerRadius = wedgesConfig?.cornerRadius ?? 0;\n    return defineChart({\n      theme: THEME,\n      marks: [\n        polar({\n          scales: { angle: null, radius: null },\n          // One mark per wedge, because a mark's radius is one number.\n          marks: wedges.map((wedge, index) =>\n            radialArc(\n              [{ index, startAngle: wedge.from * Math.PI * 2, endAngle: wedge.to * Math.PI * 2 } satisfies WedgeRow],\n              {\n                id: `${WEDGE_MARK}${index}`,\n                key: 'index',\n                innerRadius: 0,\n                outerRadius: drawn[index] ?? 0,\n                cornerRadius,\n                fill: () => colors[index] ?? PALETTE[0]!,\n              }\n            )\n          ),\n        }),\n      ],\n      scales: { x: null, y: null },\n      margin: 0,\n      guides: false,\n      focusRing: false,\n      keyboard: true,\n      pointer: true,\n      // By the wedge under the pointer. The arrow keys are walked in `onKeyDownCapture`.\n      focus: {\n        resolve: (points, { x, y }) => {\n          // Against what is drawn, so a wedge still growing is not hit where it has yet to reach.\n          const shown = wedges.map((wedge, index) => ({ ...wedge, radius: drawn[index] ?? 0 }));\n          const hit = polarWedgeAt(shown, x - box / 2, y - box / 2);\n          return points.filter((point) => point.datum.index === hit);\n        },\n        group: (_points, { point }) => [point],\n        navigation: (points) => points,\n      },\n      motion: false,\n    });\n  }, [wedges, drawn, colors, box, wedgesConfig?.cornerRadius]);\n\n  const renderer = useMemo(() => motion({ transition: { type: 'tween', duration: 160, easing: 'ease-out' } }), []);\n\n  const summary = label ?? `Polar area chart, ${data.length} ${data.length === 1 ? 'wedge' : 'wedges'}`;\n  const spoken = (datum: PolarAreaDatum, index: number) => labelForDatum?.(datum, index) ?? `${datum.label}, ${compactNumber(datum.value)}`;\n  const dimOpacity = wedgesConfig?.dimOpacity ?? 0.35;\n\n  const context = useMemo<PolarAreaChartContextValue>(\n    () => ({ data, wedges, colors, box, radius, maxValue, scale, loading, activeIndex, dimOpacity, setWedges, read, togglePin }),\n    [data, wedges, colors, box, radius, maxValue, scale, loading, activeIndex, dimOpacity, read, togglePin]\n  );\n\n  // Wedges are found by the key the mark gives them, which holds the mark's index and nothing the caller wrote.\n  // The path only, because the mark's group carries the same prefix and would dim the wedge being read.\n  const allWedges = `[data-polar-scope=\"${scope}\"] path[data-ts-key^=\"${WEDGE_MARK}\"]`;\n  const reading =\n    `${allWedges}{transition:fill-opacity ${SELECT_DURATION}ms ease-out}` +\n    (activeIndex >= 0 ? `${allWedges}:not([data-ts-key^=\"${WEDGE_MARK}${activeIndex}:\"]){fill-opacity:${dimOpacity}}` : '');\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'polar-area-chart',\n        className: slots.root({ className }),\n        children: (\n          <>\n            {loading ? null : (\n              <ul aria-label={summary} className=\"sr-only\">\n                {data.map((datum, index) => (\n                  <li key={index}>{spoken(datum, index)}</li>\n                ))}\n              </ul>\n            )}\n            <div aria-live=\"polite\" className=\"sr-only\">\n              {activeIndex >= 0 && data[activeIndex] ? spoken(data[activeIndex], activeIndex) : ''}\n            </div>\n            <div\n              ref={plotRef}\n              data-slot=\"polar-area-chart-plot\"\n              data-polar-scope={scope}\n              className={slots.plot()}\n              style={size ? { width: size, height: size } : { aspectRatio: 1 }}\n              onClick={(event) => {\n                const point = interactionRef.current?.resolvePointer(event.clientX, event.clientY)?.point;\n                if (point) togglePin(point.datum.index);\n                else if (pinned.current >= 0) release();\n              }}\n              // From the pointer rather than the chart's focus: a finger reads by pressing, its drags are the page\n              // scrolling, and the chart stays silent about a wedge it still counts as focused after the keys moved on.\n              onPointerMove={(event) => {\n                if (event.pointerType === 'touch') return;\n                const point = interactionRef.current?.resolvePointer(event.clientX, event.clientY)?.point;\n                read(point ? point.datum.index : -1);\n              }}\n              onPointerLeave={(event) => {\n                if (event.pointerType !== 'touch') read(-1);\n              }}\n              onBlur={() => read(-1)}\n              // Walked from the reading, and kept from the chart, which would walk from its own focus.\n              onKeyDownCapture={(event) => {\n                // The browser's own shortcuts, such as going back.\n                if (event.altKey || event.ctrlKey || event.metaKey) return;\n                const next = polarKeyWalk(activeIndex, data.length, event.key);\n                if (next === undefined) return;\n                event.preventDefault();\n                event.stopPropagation();\n                pinned.current = -1;\n                report(next);\n              }}\n              onKeyDown={(event) => {\n                if (event.key === 'Escape') {\n                  interactionRef.current?.setControlledFocus(null);\n                  release();\n                }\n                if ((event.key === 'Enter' || event.key === ' ') && activeIndex >= 0) {\n                  event.preventDefault();\n                  togglePin(activeIndex);\n                }\n              }}\n            >\n              <style>{reading}</style>\n              {box > 0 && !loading && wedgesConfig && data.length ? (\n                <Chart\n                  definition={definition}\n                  renderer={renderer}\n                  ariaLabel={summary}\n                  aspectRatio={1}\n                  initialWidth={box}\n                  className={slots.chart()}\n                  onRender={({ interaction }) => {\n                    interactionRef.current = interaction;\n                  }}\n                />\n              ) : null}\n            </div>\n            {children}\n          </>\n        ),\n      },\n      props\n    ),\n  });\n\n  return <PolarAreaChartContext.Provider value={context}>{element}</PolarAreaChartContext.Provider>;\n});\nPolarAreaChartRoot.displayName = 'PolarAreaChart';\n\nexport interface PolarAreaChartGridProps {\n  /** How many rings, including the outermost. */\n  rings?: number;\n  /** Which of the theme's roles to draw it in. Defaults to the border colour. */\n  color?: PolarAreaChartColor;\n  /** Draw a line from the centre out along each wedge's edge. */\n  spokes?: boolean;\n}\n\n/**\n * The scale, drawn as rings. Each ring stands for an even step of the value and sits\n * where that value falls, which under `scale=\"area\"` is not an even step of the radius.\n */\nfunction PolarAreaChartGrid({ rings = 4, color, spokes = false }: PolarAreaChartGridProps) {\n  const { box, radius, maxValue, scale, wedges } = useChart('PolarAreaChart.Grid');\n  if (radius <= 0 || rings < 1) return null;\n  const center = box / 2;\n  const stroke = color ? COLORS[color] : 'currentColor';\n\n  return (\n    <svg\n      data-slot=\"polar-area-chart-grid\"\n      aria-hidden\n      className={polarAreaChartVariants().grid()}\n      width={box}\n      height={box}\n      fill=\"none\"\n      stroke={stroke}\n    >\n      {Array.from({ length: rings }, (_, index) => (\n        <circle\n          key={index}\n          cx={center}\n          cy={center}\n          r={polarReach(((index + 1) / rings) * maxValue, { radius, maxValue, scale })}\n        />\n      ))}\n      {spokes\n        ? wedges.map((wedge, index) => {\n            const point = polarPoint(center, radius, wedge.from);\n            return <line key={index} x1={center} y1={center} x2={point.x} y2={point.y} />;\n          })\n        : null}\n    </svg>\n  );\n}\nPolarAreaChartGrid.displayName = 'PolarAreaChart.Grid';\n\nexport interface PolarAreaChartWedgesProps {\n  /** Rounds the turns of each wedge, in pixels. */\n  cornerRadius?: number;\n  /** Opacity of the other wedges while one is read. */\n  dimOpacity?: number;\n}\n\n/**\n * Every wedge, in the order the data lists them. One part rather than one per datum,\n * because the wedges share a dial, a maximum and a scale by definition.\n */\nfunction PolarAreaChartWedges({ cornerRadius = 0, dimOpacity = 0.35 }: PolarAreaChartWedgesProps) {\n  const { setWedges } = useChart('PolarAreaChart.Wedges');\n  useEffect(() => {\n    setWedges({ cornerRadius, dimOpacity });\n    return () => setWedges(undefined);\n  }, [cornerRadius, dimOpacity, setWedges]);\n  return null;\n}\nPolarAreaChartWedges.displayName = 'PolarAreaChart.Wedges';\n\nexport interface PolarAreaChartLabelsProps {\n  /** Format the value. Defaults to a compact number. */\n  formatValue?: (value: number, datum: PolarAreaDatum) => string;\n  /** Wedges reaching less far than this, in pixels, are left unlabelled. */\n  minRadius?: number;\n  /** Added to each label. */\n  className?: string;\n}\n\n/**\n * The reading on each wedge with room for it. A shorter wedge is left blank, because\n * its label would sit beside a neighbour it does not describe. Those are read through\n * `Tooltip` and the legend.\n */\nfunction PolarAreaChartLabels({ formatValue, minRadius = DEFAULT_MIN_LABEL_RADIUS, className }: PolarAreaChartLabelsProps) {\n  const { data, wedges, colors, box, loading, activeIndex, dimOpacity } = useChart('PolarAreaChart.Labels');\n  if (loading || box <= 0 || !wedges.length) return null;\n  const slots = polarAreaChartVariants();\n  const format = formatValue ?? ((value: number) => compactNumber(value));\n\n  return (\n    <div data-slot=\"polar-area-chart-labels\" aria-hidden className={slots.overlay()} style={{ width: box, height: box }}>\n      {wedges.map((wedge, index) => {\n        const datum = data[index];\n        if (!datum || wedge.radius < minRadius) return null;\n        const point = polarPoint(box / 2, wedge.radius * LABEL_AT, wedge.mid);\n        return (\n          <div\n            key={index}\n            className={slots.label({ className })}\n            style={{\n              left: point.x - LABEL_BOX / 2,\n              top: point.y - LABEL_BOX / 2,\n              color: inkOn(colors[index]!),\n              opacity: activeIndex >= 0 && activeIndex !== index ? dimOpacity : 1,\n            }}\n          >\n            {format(datum.value, datum)}\n          </div>\n        );\n      })}\n    </div>\n  );\n}\nPolarAreaChartLabels.displayName = 'PolarAreaChart.Labels';\n\nexport interface PolarAreaChartTooltipProps {\n  /** Format the value. Defaults to a compact number. */\n  formatValue?: (value: number, datum: PolarAreaDatum) => string;\n  /** Added to the readout. */\n  className?: string;\n}\n\n/** The readout for the wedge being read, floating over the dial, and how the short wedges are named. */\nfunction PolarAreaChartTooltip({ formatValue, className }: PolarAreaChartTooltipProps) {\n  const { data, wedges, box, loading, activeIndex } = useChart('PolarAreaChart.Tooltip');\n  const datum = data[activeIndex];\n  const wedge = wedges[activeIndex];\n  if (loading || !datum || !wedge) return null;\n  const slots = polarAreaChartVariants();\n  const format = formatValue ?? ((value: number) => compactNumber(value));\n  const point = polarPoint(box / 2, wedge.radius * LABEL_AT, wedge.mid);\n\n  return (\n    <div data-slot=\"polar-area-chart-tooltip\" className={slots.overlay()} style={{ width: box, height: box }}>\n      <div\n        className={slots.tooltip({ className })}\n        style={{\n          left: polarBoxInside(point.x, TOOLTIP_WIDTH, box),\n          top: polarBoxInside(point.y, TOOLTIP_HEIGHT, box),\n        }}\n      >\n        <span className={slots.tooltipName()}>{datum.label}</span>\n        <span className={slots.tooltipValue()}>{format(datum.value, datum)}</span>\n      </div>\n    </div>\n  );\n}\nPolarAreaChartTooltip.displayName = 'PolarAreaChart.Tooltip';\n\nexport interface PolarAreaChartSkeletonProps extends ComponentProps<'div'> {\n  /** Which of the theme's roles to draw the disc in. Defaults to the muted surface. */\n  color?: PolarAreaChartColor;\n}\n\n/**\n * The loading state: one plain disc, because placeholder wedges would be a made-up set\n * of readings.\n */\nfunction PolarAreaChartSkeleton({ color, className, style, render, ...props }: PolarAreaChartSkeletonProps & RenderProp<'div'>) {\n  const { radius, loading } = useChart('PolarAreaChart.Skeleton');\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'polar-area-chart-skeleton',\n        'aria-hidden': true,\n        className: polarAreaChartVariants().skeleton({ className }),\n        style: {\n          width: radius * 1.24,\n          height: radius * 1.24,\n          ...(color ? { background: COLORS[color] } : {}),\n          ...style,\n        },\n      },\n      props\n    ),\n  });\n  return loading && radius > 0 ? element : null;\n}\nPolarAreaChartSkeleton.displayName = 'PolarAreaChart.Skeleton';\n\nexport interface PolarAreaChartLegendProps extends ComponentProps<'div'> {\n  /** Show each wedge's reading beside its name. */\n  showValue?: boolean;\n  /** Format the value. Defaults to a compact number. */\n  formatValue?: (value: number, datum: PolarAreaDatum) => string;\n}\n\n/**\n * A swatch, a name and a reading per wedge, under the dial. The reading rather than a\n * share, because these values need not add up to anything. Each entry is a button for\n * the same reading as its wedge, and the easier target for a short one.\n */\nfunction PolarAreaChartLegend({ showValue = true, formatValue, className, render, ...props }: PolarAreaChartLegendProps & RenderProp<'div'>) {\n  const { data, colors, activeIndex, read, togglePin } = useChart('PolarAreaChart.Legend');\n  const slots = polarAreaChartVariants();\n  const format = formatValue ?? ((value: number) => compactNumber(value));\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'polar-area-chart-legend',\n        className: slots.legend({ className }),\n        children: data.map((datum, index) => (\n          <button\n            key={index}\n            type=\"button\"\n            aria-pressed={activeIndex === index}\n            aria-label={`${datum.label}, ${format(datum.value, datum)}`}\n            className={slots.legendButton()}\n            style={{ opacity: activeIndex >= 0 && activeIndex !== index ? LEGEND_DIM : 1 }}\n            onPointerEnter={(event) => {\n              if (event.pointerType === 'mouse') read(index);\n            }}\n            onPointerLeave={(event) => {\n              if (event.pointerType === 'mouse') read(-1);\n            }}\n            onClick={() => togglePin(index)}\n          >\n            <span className={slots.legendSwatch()} style={{ background: colors[index] }} />\n            <span className={slots.legendName()}>{datum.label}</span>\n            {showValue ? <span className={slots.legendValue()}>{format(datum.value, datum)}</span> : null}\n          </button>\n        )),\n      },\n      props\n    ),\n  });\n\n  return data.length ? element : null;\n}\nPolarAreaChartLegend.displayName = 'PolarAreaChart.Legend';\n\nexport interface PolarAreaChartHeaderProps extends Omit<ComponentProps<'div'>, 'title'> {\n  /** Small line above the value: what the chart is of. */\n  title?: ReactNode;\n  /** The readout. The largest thing on the card, and the first thing read. */\n  value?: ReactNode;\n  /** One muted line under the value: a period, a comparison, a caveat. */\n  caption?: ReactNode;\n  /** Prettier names for the wedges, keyed by their `label`. */\n  labels?: Record<string, string>;\n  /** Draw a swatch and a name per wedge along the trailing edge, for two or three short names. */\n  legend?: boolean;\n  /** Trailing slot: a control, a badge, a range picker. Wins over `legend`. */\n  children?: ReactNode;\n}\n\n/** The strip above the dial. The value is not derived here, because its formatting is the caller's to know. */\nfunction PolarAreaChartHeader({\n  title,\n  value,\n  caption,\n  labels,\n  legend = false,\n  className,\n  children,\n  render,\n  ...props\n}: PolarAreaChartHeaderProps & RenderProp<'div'>) {\n  const { data, colors } = useChart('PolarAreaChart.Header');\n  const slots = polarAreaChartVariants();\n  const trailing =\n    children ??\n    (legend && data.length\n      ? data.map((datum, index) => (\n          <span key={index} className={slots.legendItem()}>\n            <span className={slots.legendSwatch()} style={{ background: colors[index] }} />\n            {labels?.[datum.label] ?? datum.label}\n          </span>\n        ))\n      : null);\n\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'polar-area-chart-header',\n        className: slots.header({ className }),\n        children: (\n          <>\n            <div className={slots.headerText()}>\n              {title ? <div className={slots.headerMuted()}>{title}</div> : null}\n              {value || value === 0 ? <div className={slots.headerValue()}>{value}</div> : null}\n              {caption ? <div className={slots.headerMuted()}>{caption}</div> : null}\n            </div>\n            {trailing ? <div className={slots.headerTrailing()}>{trailing}</div> : null}\n          </>\n        ),\n      },\n      props\n    ),\n  });\n}\nPolarAreaChartHeader.displayName = 'PolarAreaChart.Header';\n\nexport const PolarAreaChart = Object.assign(PolarAreaChartRoot, {\n  Header: PolarAreaChartHeader,\n  Grid: PolarAreaChartGrid,\n  Wedges: PolarAreaChartWedges,\n  Labels: PolarAreaChartLabels,\n  Tooltip: PolarAreaChartTooltip,\n  Legend: PolarAreaChartLegend,\n  Skeleton: PolarAreaChartSkeleton,\n});\n\n/* By name as well, for a Server Component, which cannot dot into a client\n   module. */\nexport {\n  PolarAreaChartHeader,\n  PolarAreaChartGrid,\n  PolarAreaChartWedges,\n  PolarAreaChartLabels,\n  PolarAreaChartTooltip,\n  PolarAreaChartLegend,\n  PolarAreaChartSkeleton,\n};\n"
    },
    {
      "path": "components/panelui/polar-area-chart/polar-layout.ts",
      "type": "registry:component",
      "target": "@components/panelui/polar-area-chart/polar-layout.ts",
      "content": "/** A wedge's place on the dial, in turns clockwise from twelve o'clock. */\nexport interface PolarWedge {\n  from: number;\n  to: number;\n  /** Halfway along it, which is where its label sits. */\n  mid: number;\n  /** How far out it reaches, in pixels. */\n  radius: number;\n  /** Its value against the maximum, 0 to 1. */\n  fraction: number;\n}\n\n/** What a wedge's radius stands for. */\nexport type PolarAreaScale = 'radius' | 'area';\n\nexport interface PolarLayoutOptions {\n  /** The outermost ring, in pixels, standing for `maxValue`. */\n  radius: number;\n  maxValue: number;\n  scale: PolarAreaScale;\n  /** Where the first wedge begins, in degrees clockwise from twelve o'clock. */\n  startAngle: number;\n  /** Gap between one wedge and the next, in degrees. */\n  padAngle: number;\n}\n\nconst NICE_STEPS = [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10];\n\n/** The first round number at or above `value`, so the outer ring reads as a figure somebody would pick. */\nexport function polarNiceMax(value: number): number {\n  if (!Number.isFinite(value) || value <= 0) return 1;\n  const magnitude = 10 ** Math.floor(Math.log10(value));\n  const scaled = value / magnitude;\n  return (NICE_STEPS.find((step) => scaled <= step) ?? 10) * magnitude;\n}\n\n/**\n * A value's distance from the centre. One conversion for the wedges and the rings,\n * so a ring is always where its value falls. Under `area` it is the square root, so\n * the ink is proportional to the value and the rings are not evenly spaced.\n */\nexport function polarReach(value: number, { radius, maxValue, scale }: Pick<PolarLayoutOptions, 'radius' | 'maxValue' | 'scale'>): number {\n  const fraction = Math.min(Math.max(value, 0) / maxValue, 1);\n  return radius * (scale === 'area' ? Math.sqrt(fraction) : fraction);\n}\n\n/** Every wedge takes the same angle, and only the value decides how far it reaches. */\nexport function polarWedges(values: readonly number[], options: PolarLayoutOptions): PolarWedge[] {\n  if (!values.length) return [];\n  const each = 1 / values.length;\n  const origin = options.startAngle / 360;\n  const pad = Math.min(options.padAngle / 360, each / 2);\n  return values.map((value, index) => {\n    const from = origin + each * index + pad / 2;\n    const to = origin + each * (index + 1) - pad / 2;\n    return {\n      from,\n      to,\n      mid: (from + to) / 2,\n      radius: polarReach(value, options),\n      fraction: Math.min(Math.max(value, 0) / options.maxValue, 1),\n    };\n  });\n}\n\n/** The wedge under a point measured from the centre, or -1 for a gap or past its reach. */\nexport function polarWedgeAt(wedges: readonly PolarWedge[], x: number, y: number): number {\n  const distance = Math.hypot(x, y);\n  const turn = Math.atan2(x, -y) / (Math.PI * 2);\n  return wedges.findIndex((wedge) => {\n    if (distance > wedge.radius) return false;\n    const past = (((turn - wedge.from) % 1) + 1) % 1;\n    return past < wedge.to - wedge.from;\n  });\n}\n\n/** Radii part way through a change, `progress` running 0 to 1. A wedge with no earlier radius grows from the centre. */\nexport function polarRadiiBetween(from: readonly number[], to: readonly number[], progress: number): number[] {\n  return to.map((radius, index) => {\n    const start = from[index] ?? 0;\n    return start + (radius - start) * progress;\n  });\n}\n\n/** A point on the dial, from the top-left of a box with its centre at `center`. */\nexport function polarPoint(center: number, radius: number, turn: number): { x: number; y: number } {\n  const angle = turn * Math.PI * 2;\n  return { x: center + Math.sin(angle) * radius, y: center - Math.cos(angle) * radius };\n}\n\n/** Where a box goes over a point, pushed back inside the plot, because a readout half off the edge is half a readout. */\nexport function polarBoxInside(point: number, boxSize: number, plot: number): number {\n  return Math.max(0, Math.min(plot - boxSize, point - boxSize / 2));\n}\n\n/** The wedge a navigation key moves the reading to, or undefined for any other key. Stops at the ends. */\nexport function polarKeyWalk(current: number, count: number, key: string): number | undefined {\n  const last = count - 1;\n  if (last < 0) return undefined;\n  switch (key) {\n    case 'ArrowRight':\n    case 'ArrowDown':\n      return Math.min(current + 1, last);\n    case 'ArrowLeft':\n    case 'ArrowUp':\n      return Math.max(current - 1, 0);\n    case 'Home':\n      return 0;\n    case 'End':\n      return last;\n    default:\n      return undefined;\n  }\n}\n"
    }
  ]
}
