{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pyramid-chart",
  "type": "registry:component",
  "title": "Pyramid Chart",
  "description": "Two series mirrored about a centre line, one row per category, on one shared scale.",
  "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/pyramid-chart/index.tsx",
      "type": "registry:component",
      "target": "@components/panelui/pyramid-chart/index.tsx",
      "content": "'use client';\n\n/**\n * PyramidChart — two series mirrored about a centre line, one row per category.\n *\n * ```tsx\n * <PyramidChart data={penguins} xDataKey=\"species\">\n *   <PyramidChart.Grid />\n *   <PyramidChart.Bar dataKey=\"male\" side=\"start\" />\n *   <PyramidChart.Bar dataKey=\"female\" side=\"end\" />\n *   <PyramidChart.XAxis />\n *   <PyramidChart.YAxis />\n *   <PyramidChart.Tooltip />\n * </PyramidChart>\n * ```\n *\n * ## The same parts as the app\n *\n * The parts and their props are the app library's PyramidChart, so a chart\n * written for one reads the same in the other. What differs is what the web\n * changes: a colour is named by the theme's role, a row is read by hovering,\n * tapping or dragging, a click pins the reading, and the arrow keys walk the rows.\n *\n * ## The two wings share one scale\n *\n * The domain comes from the larger of the two series' extents and both use it, so\n * a bar twice as long as the one facing it means twice as much. The centre is\n * zero and stays there, because a wing cropped at its base misreports its value.\n *\n * ## Lengths, not signed values\n *\n * Which side a series is on comes from `side`, not from the sign of its numbers,\n * so a value is a distance outward. A negative one is drawn as nothing and still\n * appears in the readout, so a data error shows as a gap and not as a bar pointing\n * the wrong way.\n *\n * ## One mark for both wings\n *\n * Every bar is a row of one mark, with its two ends worked out in value units.\n * That is what lets the readout hold both of a row's bars at once: the chart only\n * groups the points of a single mark. The names and the value labels are HTML\n * placed from the same numbers, because neither has a place on a chart axis: a\n * name can sit over its bars, and the value axis repeats itself either side of zero.\n */\nimport {\n  barX,\n  defineChart,\n  ruleX,\n  type ChartInteractionController,\n  type ChartMotionContext,\n  type ChartPoint,\n  type SceneNode,\n} from '@tanstack/charts';\nimport { motion } from '@tanstack/charts/motion';\nimport { Chart } from '@tanstack/charts/react/core';\nimport { scaleBand } from '@tanstack/charts/scales/band';\nimport { scaleLinear } from '@tanstack/charts/scales/linear';\nimport { tooltip as chartTooltip } from '@tanstack/charts/tooltip';\nimport {\n  createContext,\n  forwardRef,\n  useCallback,\n  useContext,\n  useEffect,\n  useImperativeHandle,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type PointerEvent as ReactPointerEvent,\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 { barThickness, gutterUnits, sharedMax, wingSpan, wingTicks, type PyramidSide } from './pyramid-scale';\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\nexport type PyramidChartStatus = 'loading' | 'ready';\n\n/** Which wing a series grows into. */\nexport type PyramidChartSide = PyramidSide;\n\n/** Where the category names sit. */\nexport type PyramidChartLabelPlacement = 'above' | 'center' | 'start';\n\nexport type PyramidChartDatum = Record<string, string | number | null | undefined>;\n\n/** Which of the theme's roles a series is drawn in. */\nexport type PyramidChartColor =\n  | 'primary'\n  | 'info'\n  | 'success'\n  | 'warning'\n  | 'destructive'\n  | 'chart-1'\n  | 'chart-2'\n  | 'chart-3'\n  | 'chart-4'\n  | 'chart-5';\n\nconst COLOR_VAR: Record<PyramidChartColor, string> = {\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\nconst THEME = {\n  foreground: 'var(--foreground)',\n  muted: 'var(--muted-foreground)',\n  grid: 'var(--border)',\n  background: 'transparent',\n  palette: ['var(--chart-1)', 'var(--chart-2)', 'var(--chart-3)', 'var(--chart-4)', 'var(--chart-5)'],\n};\n\nconst pyramidChartVariants = tv({\n  slots: {\n    root: 'relative grid w-full grid-cols-1 text-foreground',\n    plot: 'relative col-start-1 row-start-2 w-full',\n    // `pan-y` hands a vertical drag to the page and a sideways one to the chart.\n    chart:\n      'absolute! inset-0 touch-pan-y rounded-lg text-xs [--ts-chart-tooltip-background:var(--popover)] [--ts-chart-tooltip-border-radius:var(--radius-xl)] [--ts-chart-tooltip-border:1px_solid_var(--border)] [--ts-chart-tooltip-color:var(--popover-foreground)] [--ts-chart-tooltip-shadow:var(--shadow-lg)] [&_svg]:rounded-lg [&_svg]:outline-none [&_svg:focus-visible]:ring-2 [&_svg:focus-visible]:ring-ring',\n    sweepClip: 'pointer-events-none absolute inset-0 overflow-hidden',\n    sweep:\n      'absolute inset-y-0 left-0 w-2/5 bg-[linear-gradient(90deg,transparent,color-mix(in_oklab,var(--chart-1)_55%,transparent),transparent)] motion-reduce:hidden',\n    overlay: 'pointer-events-none absolute inset-0 text-xs text-muted-foreground',\n    tick: 'absolute bottom-0 truncate text-center tabular-nums',\n    name: 'absolute flex items-center truncate',\n    legend:\n      'pointer-events-none absolute right-2 top-1 col-start-1 row-start-2 flex gap-3 text-xs text-muted-foreground',\n    legendItem: 'flex items-center gap-1.5',\n    legendSwatch: 'size-2 shrink-0 rounded-full',\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: 'flex shrink flex-wrap items-center justify-end gap-x-3 gap-y-1 pt-1 text-xs text-muted-foreground',\n  },\n});\n\n/** Room around the plot. The bottom holds the value labels. */\nconst PADDING = { top: 6, right: 10, bottom: 22, left: 10 };\n\n/** Left gutter held for the names when they sit at the start. */\nconst CATEGORY_GUTTER = 68;\n\n/** Middle gutter held for them between the wings. It comes off the bars, not the edges. */\nconst CENTRE_GUTTER = 72;\n\n/** Height taken off the top of every band for the name sitting over it. */\nconst LABEL_ROW = 20;\n\n/** The box a value label is centred in, narrow enough to stay inside the chart at the edge. */\nconst AXIS_LABEL_WIDTH = 56;\n\n/** How much of a wing a placeholder bar takes. */\nconst SKELETON_LENGTH = 0.35;\n\n/** Rows to draw when there is no data yet to count them from. */\nconst SKELETON_ROWS = 5;\n\nconst SKELETON_MARK = 'pyramid-chart-skeleton';\n\n/** How much of the entrance goes to staggering the rows. */\nconst STAGGER_SHARE = 0.45;\n\nconst KEYFRAMES = '@keyframes panelui-pyramid-sweep{from{transform:translateX(-100%)}to{transform:translateX(250%)}}';\n\nconst COMPACT = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 });\nconst COMPACT_SMALL = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 2 });\n\n/** Below one, a single decimal would round most values down to nothing. */\nconst compactNumber = (value: number) => (Math.abs(value) < 1 ? COMPACT_SMALL : COMPACT).format(value);\n\n/** One bar: a value of one series in one row, with its two ends on the shared scale. */\ninterface WingRow {\n  index: number;\n  series: string;\n  side: PyramidSide;\n  value: number;\n  x1: number;\n  x2: number;\n}\n\ninterface SeriesEntry {\n  key: string;\n  fill: string;\n  side: PyramidSide;\n  radius: number | undefined;\n}\n\n/**\n * What the parts have asked for. The readout's formatters are read through\n * `latest` when it opens, so a new one costs nothing.\n */\ninterface Slots {\n  grid?: { columns: number; dashArray: string; opacity: number; centreLine: boolean };\n  xAxis?: Pick<PyramidChartXAxisProps, 'ticks' | 'format' | 'className'>;\n  yAxis?: Pick<PyramidChartYAxisProps, 'format' | 'className'>;\n  tooltip?: {\n    className: string | undefined;\n    latest: { current: Pick<PyramidChartTooltipProps, 'formatValue' | 'formatX' | 'labels'> };\n  };\n  skeleton?: { rows: number | undefined; duration: number };\n}\n\ninterface PyramidChartContextValue {\n  data: readonly PyramidChartDatum[];\n  xDataKey: string;\n  series: readonly SeriesEntry[];\n  setSeries: (entry: SeriesEntry) => void;\n  removeSeries: (key: string) => void;\n  setSlot: <K extends keyof Slots>(slot: K, value: Slots[K]) => void;\n  activeIndex: number;\n}\n\nconst PyramidChartContext = createContext<PyramidChartContextValue | null>(null);\n\nfunction useChart(component: string): PyramidChartContextValue {\n  const context = useContext(PyramidChartContext);\n  if (!context) {\n    throw new Error(`${component} must be used within a <PyramidChart>`);\n  }\n  return context;\n}\n\n/**\n * The row being read, for something rendered inside the chart. A readout outside\n * it takes `onActiveIndexChange` instead.\n */\nexport function usePyramidChart() {\n  const { data, activeIndex, xDataKey } = useChart('usePyramidChart');\n  return {\n    activeIndex,\n    activePoint: activeIndex >= 0 ? (data[activeIndex] ?? null) : null,\n    xDataKey,\n  };\n}\n\n/** The stubs' outlines from the drawn scene, for the sweep to be clipped to. */\nfunction stubOutlines(nodes: readonly SceneNode[], x = 0, y = 0, inside = false): string {\n  return nodes\n    .map((node) => {\n      if (node.kind === 'group') {\n        return stubOutlines(\n          node.children,\n          x + (node.translateX ?? 0),\n          y + (node.translateY ?? 0),\n          inside || node.key.includes(SKELETON_MARK)\n        );\n      }\n      if (node.kind !== 'rect' || !(inside || node.key.includes(SKELETON_MARK))) return '';\n      const left = node.x + x;\n      const top = node.y + y;\n      return `M${left},${top}h${node.width}v${node.height}h${-node.width}Z`;\n    })\n    .join('');\n}\n\n/** Rounds the outward corners only, so the two wings meet square at the centre. */\nconst outwardCorners = (side: PyramidSide, radius: number): readonly [number, number, number, number] =>\n  side === 'start' ? [radius, 0, 0, radius] : [0, radius, radius, 0];\n\nexport interface PyramidChartProps extends Omit<ComponentProps<'div'>, 'ref'> {\n  /** The rows. Each one is a band across the chart, with a wing either side. */\n  data: readonly PyramidChartDatum[];\n  /** Key holding the category label. Used by the axis and the readout. */\n  xDataKey?: string;\n  /**\n   * `loading` holds the bars at the centre and grows them out when it turns\n   * `ready`. Add a `PyramidChart.Skeleton` for something to stand in the plot\n   * meanwhile.\n   */\n  status?: PyramidChartStatus;\n  /** The plot's width ÷ height. `1.2` suits three or four rows in a card. */\n  aspectRatio?: number;\n  /** Milliseconds for the bars to grow out. */\n  animationDuration?: number;\n  /** Milliseconds for the bars to settle after the data changes. */\n  domainDuration?: number;\n  /**\n   * Fix the far end of the shared scale instead of deriving it. The near end is\n   * zero either way.\n   */\n  maxValue?: number;\n  /**\n   * Where the category names sit. `above` gives each row a line of its own over\n   * its pair of bars. `center` puts them in a gutter between the wings, and\n   * `start` down the left edge.\n   */\n  labelPlacement?: PyramidChartLabelPlacement;\n  /** Fraction of each band left empty, `0` to `1`. */\n  barGap?: number;\n  /** Largest bar thickness in pixels. Derived from the band when omitted. */\n  barWidth?: number;\n  /** Corner radius on the outward end of a bar. */\n  cornerRadius?: number;\n  /** Smallest length a positive bar is drawn at, in pixels. */\n  minBarLength?: number;\n  /** Opacity of the rows that are not being read. */\n  fadedOpacity?: number;\n  /**\n   * The row being read, and `-1`/`null` when there is none. Fires when the index\n   * changes, not per frame.\n   */\n  onActiveIndexChange?: (index: number, datum: PyramidChartDatum | null) => void;\n  /** What a screen reader calls the chart. */\n  label?: string;\n  /** What a screen reader says for one row. Defaults to its keys and values. */\n  labelForDatum?: (datum: PyramidChartDatum, index: number) => string;\n}\n\n/** Imperative handle: re-run the grow-out, for a \"replay\" control. */\nexport interface PyramidChartHandle {\n  replay: () => void;\n}\n\nconst PyramidChartRoot = forwardRef<PyramidChartHandle, PyramidChartProps & RenderProp<'div'>>(function PyramidChartRoot(\n  {\n    data,\n    xDataKey = 'name',\n    status = 'ready',\n    aspectRatio = 1.2,\n    animationDuration = 700,\n    domainDuration = 500,\n    maxValue,\n    labelPlacement = 'above',\n    barGap = 0.25,\n    barWidth,\n    cornerRadius = 4,\n    minBarLength = 0,\n    fadedOpacity = 0.3,\n    onActiveIndexChange,\n    label,\n    labelForDatum,\n    className,\n    children,\n    render,\n    ...props\n  },\n  ref\n) {\n  const slotClasses = pyramidChartVariants();\n  const plotRef = useRef<HTMLDivElement>(null);\n  const [width, setWidth] = useState(0);\n  const [series, setSeriesState] = useState<readonly SeriesEntry[]>([]);\n  const [slots, setSlots] = useState<Slots>({});\n  const [activeIndex, setActiveIndex] = useState(-1);\n  const [revision, setRevision] = useState(0);\n  const [stubs, setStubs] = useState('');\n  const interactionRef = useRef<ChartInteractionController<WingRow, number, number> | null>(null);\n  const dragging = useRef(false);\n\n  /*\n   * The chart mounts once its width is known. Mounted at a guess, the first\n   * measurement is a resize, and a resize ends the entrance before it is seen.\n   */\n  useEffect(() => {\n    const node = plotRef.current;\n    if (!node) return;\n    const read = () => setWidth(node.clientWidth);\n    read();\n    const observer = new ResizeObserver(read);\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, []);\n\n  const setSeries = useCallback(\n    (entry: SeriesEntry) =>\n      setSeriesState((current) =>\n        current.some(({ key }) => key === entry.key)\n          ? current.map((existing) => (existing.key === entry.key ? entry : existing))\n          : [...current, entry]\n      ),\n    []\n  );\n  const removeSeries = useCallback(\n    (key: string) => setSeriesState((current) => current.filter((entry) => entry.key !== key)),\n    []\n  );\n  const setSlot = useCallback<PyramidChartContextValue['setSlot']>(\n    (slot, value) => setSlots((current) => ({ ...current, [slot]: value })),\n    []\n  );\n\n  useImperativeHandle(ref, () => ({ replay: () => setRevision((current) => current + 1) }), []);\n\n  const loading = status === 'loading';\n  const { grid, xAxis, yAxis, tooltip, skeleton } = slots;\n\n  /*\n   * Each place a name can go takes its room from somewhere different: `above`\n   * off the top of every band, `center` out of the middle of the plot, `start`\n   * off the left edge.\n   */\n  const gutter = yAxis && labelPlacement === 'center' ? CENTRE_GUTTER : 0;\n  const labelInset = yAxis && labelPlacement === 'above' ? LABEL_ROW : 0;\n  const left = yAxis && labelPlacement === 'start' ? CATEGORY_GUTTER : PADDING.left;\n  const plotWidth = Math.max(width - left - PADDING.right, 0);\n  const plotHeight = Math.max(width / aspectRatio - PADDING.top - PADDING.bottom, 0);\n  const rowCount = loading ? Math.max(1, skeleton?.rows ?? (data.length || SKELETON_ROWS)) : data.length;\n  const band = rowCount > 0 ? plotHeight / rowCount : 0;\n\n  const extentMax = useMemo(\n    () => sharedMax(data, series.map(({ key }) => key), maxValue),\n    [data, series, maxValue]\n  );\n  // While loading the stubs have a scale of their own: a stub's length is a share of a wing.\n  const domainMax = loading ? 1 : extentMax;\n  const base = gutterUnits(domainMax, plotWidth, gutter);\n  const wing = (plotWidth - gutter) / 2;\n  const floor = wing > 0 ? (minBarLength / wing) * domainMax : 0;\n  const thickness = barThickness(band, labelInset, barGap, barWidth);\n\n  const definition = useMemo(() => {\n    const bySeries = new Map(series.map((entry) => [entry.key, entry]));\n    const rows: WingRow[] = data.flatMap((datum, index) =>\n      series.flatMap(({ key, side }) => {\n        const value = datum[key];\n        if (typeof value !== 'number' || Number.isNaN(value)) return [];\n        const [x1, x2] = wingSpan(value, side, base, floor);\n        return [{ index, series: key, side, value, x1, x2 }];\n      })\n    );\n\n    const indexes = Array.from({ length: rowCount }, (_unused, index) => index);\n    const stubRows: WingRow[] =\n      loading && skeleton\n        ? indexes.flatMap((index) =>\n            (['start', 'end'] as const).map((side) => {\n              const [x1, x2] = wingSpan(SKELETON_LENGTH, side, base);\n              return { index, series: side, side, value: SKELETON_LENGTH, x1, x2 };\n            })\n          )\n        : [];\n\n    const bars = barX(rows, {\n      x1: 'x1',\n      x2: 'x2',\n      y: 'index',\n      z: 'series',\n      key: (row: WingRow) => `${row.index}:${row.series}`,\n      fill: (row: WingRow) => bySeries.get(row.series)?.fill ?? COLOR_VAR['chart-1'],\n      radius: (row: WingRow) => outwardCorners(row.side, bySeries.get(row.series)?.radius ?? cornerRadius),\n      maxThickness: thickness,\n      states: [\n        {\n          when: { focus: 'unmatched' as const },\n          style: { fillOpacity: fadedOpacity },\n          transition: { type: 'tween' as const, duration: 120, easing: 'ease-out' as const },\n        },\n      ],\n    });\n\n    const stubMark = barX(stubRows, {\n      id: SKELETON_MARK,\n      x1: 'x1',\n      x2: 'x2',\n      y: 'index',\n      z: 'series',\n      key: (row: WingRow) => `${row.index}:${row.series}`,\n      fill: 'var(--muted)',\n      radius: (row: WingRow) => outwardCorners(row.side, cornerRadius),\n      maxThickness: thickness,\n      motion: false as const,\n    });\n\n    const rules = grid\n      ? ruleX(\n          wingTicks(domainMax, grid.columns).flatMap((value) => [-(base + value), base + value]),\n          {\n            id: 'pyramid-chart-grid',\n            stroke: 'var(--border)',\n            strokeOpacity: grid.opacity,\n            strokeDasharray: grid.dashArray,\n            motion: false as const,\n          }\n        )\n      : null;\n    // The solid line both wings are measured from. A gutter has names standing where it would go.\n    const centre =\n      grid?.centreLine && gutter === 0\n        ? ruleX([0], { id: 'pyramid-chart-centre', stroke: 'var(--border)', strokeOpacity: grid.opacity, motion: false as const })\n        : null;\n\n    const interactive = tooltip !== undefined && !loading && rows.length > 0;\n    const readout = tooltip\n      ? {\n          use: chartTooltip,\n          className: tooltip.className,\n          content(points: readonly ChartPoint<WingRow, number, number>[]) {\n            const { formatValue, formatX, labels } = tooltip.latest.current;\n            const first = points[0]?.datum;\n            const datum = first ? data[first.index] : undefined;\n            return {\n              title: datum ? (formatX ? formatX(datum) : String(datum[xDataKey] ?? '')) : '',\n              rows: points.map(({ datum: row, color }) => ({\n                label: labels?.[row.series] ?? row.series,\n                value: formatValue ? formatValue(row.value, row.series) : compactNumber(row.value),\n                color,\n              })),\n            };\n          },\n        }\n      : undefined;\n\n    return defineChart({\n      theme: THEME,\n      marks: [...(rules ? [rules] : []), ...(centre ? [centre] : []), loading ? stubMark : bars],\n      scales: {\n        x: { scale: scaleLinear([-(domainMax + base), domainMax + base], [0, 1]), nice: false },\n        y: { scale: scaleBand(indexes, [0, 1]).paddingInner(0).paddingOuter(0) },\n      },\n      guides: false as const,\n      // A name's line comes off every band, so the bars move down by half of it, and\n      // moving the two margins by the same amount leaves the bands as tall as they were.\n      margin: {\n        top: PADDING.top + labelInset / 2,\n        bottom: PADDING.bottom - labelInset / 2,\n        left,\n        right: PADDING.right,\n      },\n      focusRing: false,\n      /*\n       * Rows grow out one after another and all finish inside the one duration:\n       * the window each gets is what is left after the last one's delay.\n       */\n      motion: (context: ChartMotionContext<WingRow>) => {\n        if (context.phase !== 'enter') {\n          return { transition: { type: 'tween' as const, duration: domainDuration, easing: 'ease-out' as const } };\n        }\n        if (context.role !== 'bar') return false as const;\n        const row = context.datum?.index ?? 0;\n        return {\n          delay: rowCount > 1 ? (row / rowCount) * animationDuration * STAGGER_SHARE : 0,\n          transition: {\n            type: 'tween' as const,\n            duration: animationDuration * (1 - (rowCount > 1 ? STAGGER_SHARE : 0)),\n            easing: 'ease-out' as const,\n          },\n        };\n      },\n      keyboard: interactive,\n      pointer: interactive,\n      ...(interactive && readout\n        ? { focus: 'group-y' as const, maxFocusDistance: Number.POSITIVE_INFINITY, tooltip: readout }\n        : {}),\n    });\n  }, [\n    data,\n    xDataKey,\n    series,\n    loading,\n    rowCount,\n    domainMax,\n    base,\n    floor,\n    thickness,\n    gutter,\n    labelInset,\n    left,\n    cornerRadius,\n    fadedOpacity,\n    animationDuration,\n    domainDuration,\n    grid,\n    tooltip,\n    skeleton,\n  ]);\n\n  // Marks take their timing from the definition. This one is what the readout\n  // moves with, and it should keep up with the pointer.\n  const renderer = useMemo(() => motion({ transition: { type: 'tween', duration: 160, easing: 'ease-out' } }), []);\n\n  const summary = label ?? `Pyramid chart, ${data.length} ${data.length === 1 ? 'row' : 'rows'}`;\n\n  const context = useMemo<PyramidChartContextValue>(\n    () => ({ data, xDataKey, series, setSeries, removeSeries, setSlot, activeIndex }),\n    [data, xDataKey, series, setSeries, removeSeries, setSlot, activeIndex]\n  );\n\n  const spokenRow = (datum: PyramidChartDatum, index: number) =>\n    labelForDatum?.(datum, index) ??\n    [xDataKey, ...series.map(({ key }) => key)]\n      .filter((key) => datum[key] !== null && datum[key] !== undefined)\n      .map((key) => `${key}, ${datum[key]}`)\n      .join('. ');\n\n  // The chart also reports a row again when the data is rebuilt under it. Only a\n  // change of row is news, and repeating it can loop a caller that keeps the datum.\n  const reportedIndex = useRef(-1);\n  const reportActive = (index: number) => {\n    if (reportedIndex.current === index) return;\n    reportedIndex.current = index;\n    setActiveIndex(index);\n    onActiveIndexChange?.(index, index >= 0 ? (data[index] ?? null) : null);\n  };\n  const onFocusChange = (point: ChartPoint<WingRow, number, number> | null) =>\n    reportActive(point ? point.datum.index : -1);\n\n  // A remounted chart says nothing about the focus it lost.\n  useEffect(() => reportActive(-1), [revision, status]);\n\n  // Without a readout nothing can read a row, and the chart keeps a keyboard or drag focus it holds.\n  const readable = tooltip !== undefined;\n  useEffect(() => {\n    if (readable) return;\n    interactionRef.current?.setControlledFocus(null);\n    reportActive(-1);\n  }, [readable]);\n\n  /*\n   * The chart follows a mouse on its own but not a finger, which it treats as a\n   * tap. A sideways drag reads the rows it crosses, and the last one stays until\n   * the next press, the same as a tap's. A vertical drag never gets here: `pan-y`\n   * gives it to the page, and the browser cancels the pointer.\n   */\n  const readDrag = (event: ReactPointerEvent<HTMLDivElement>) => {\n    if (event.pointerType !== 'touch' || !tooltip || loading) return;\n    const interaction = interactionRef.current;\n    const target = interaction?.resolvePointer(event.clientX, event.clientY);\n    if (!interaction || !target) return;\n    interaction.setControlledFocus(target);\n    if (dragging.current) return;\n    dragging.current = true;\n    document.addEventListener(\n      'pointerdown',\n      () => {\n        dragging.current = false;\n        interactionRef.current?.setControlledFocus(null);\n      },\n      { capture: true, once: true }\n    );\n  };\n\n  // Centred on its tick, then held inside the chart: the outermost tick is on the\n  // plot's edge, where a centred box would hang half its width off the side.\n  const tickLeft = (x: number) => Math.max(0, Math.min(x - AXIS_LABEL_WIDTH / 2, width - AXIS_LABEL_WIDTH));\n  const centre = left + plotWidth / 2;\n  const axisTicks =\n    xAxis && !loading && wing > 0\n      ? [\n          { key: 'centre', value: 0, x: centre },\n          ...wingTicks(extentMax, xAxis.ticks ?? 2).flatMap((value, index, all) => {\n            const reach = gutter / 2 + (wing * (index + 1)) / all.length;\n            return [\n              { key: `start-${index}`, value, x: centre - reach },\n              { key: `end-${index}`, value, x: centre + reach },\n            ];\n          }),\n        ]\n      : [];\n  const formatTick = xAxis?.format ?? compactNumber;\n\n  // A placeholder count that differs from the data has no names to line up with.\n  const names = yAxis && width > 0 && band > 0 && rowCount === data.length ? data : [];\n  const nameBox = (index: number): { left: number; width: number; top: number; height: number } => {\n    const top = PADDING.top + index * band;\n    if (labelPlacement === 'above') return { left: 0, width, top, height: LABEL_ROW };\n    if (labelPlacement === 'center') return { left: centre - CENTRE_GUTTER / 2, width: CENTRE_GUTTER, top, height: band };\n    return { left: 0, width: Math.max(left - 8, 0), top, height: band };\n  };\n  const nameAlign = labelPlacement === 'start' ? 'flex-end' : 'center';\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'pyramid-chart',\n        className: slotClasses.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}>{spokenRow(datum, index)}</li>\n                ))}\n              </ul>\n            )}\n            <div\n              ref={plotRef}\n              data-slot=\"pyramid-chart-plot\"\n              className={slotClasses.plot()}\n              style={{ aspectRatio }}\n              onKeyDown={(event) => {\n                if (event.key === 'Escape') interactionRef.current?.setControlledFocus(null);\n              }}\n              onPointerMove={readDrag}\n              onPointerCancel={() => interactionRef.current?.setControlledFocus(null)}\n            >\n              {width > 0 ? (\n                <Chart\n                  // An entrance only grows from the centre on a chart's first paint,\n                  // so the bars arriving after a load, or a replay, are a new chart.\n                  key={`${revision}:${status}`}\n                  definition={definition}\n                  renderer={renderer}\n                  ariaLabel={summary}\n                  aspectRatio={aspectRatio}\n                  initialWidth={width}\n                  className={slotClasses.chart()}\n                  onFocusChange={onFocusChange}\n                  onRender={({ scene, interaction }) => {\n                    interactionRef.current = interaction;\n                    setStubs(stubOutlines(scene.nodes));\n                  }}\n                />\n              ) : null}\n              {loading && skeleton && stubs ? (\n                <div\n                  data-slot=\"pyramid-chart-skeleton\"\n                  aria-hidden\n                  className={slotClasses.sweepClip()}\n                  style={{ clipPath: `path('${stubs}')` }}\n                >\n                  <style>{KEYFRAMES}</style>\n                  <div\n                    className={slotClasses.sweep()}\n                    style={{ animation: `panelui-pyramid-sweep ${skeleton.duration}ms linear infinite` }}\n                  />\n                </div>\n              ) : null}\n              {axisTicks.length ? (\n                <div data-slot=\"pyramid-chart-x-axis\" aria-hidden className={slotClasses.overlay({ className: xAxis?.className })}>\n                  {axisTicks.map(({ key, value, x }) => (\n                    <span key={key} className={slotClasses.tick()} style={{ left: tickLeft(x), width: AXIS_LABEL_WIDTH }}>\n                      {formatTick(value)}\n                    </span>\n                  ))}\n                </div>\n              ) : null}\n              {names.length ? (\n                <div data-slot=\"pyramid-chart-y-axis\" aria-hidden className={slotClasses.overlay({ className: yAxis?.className })}>\n                  {names.map((datum, index) => (\n                    <span key={index} className={slotClasses.name()} style={{ ...nameBox(index), justifyContent: nameAlign }}>\n                      {yAxis?.format ? yAxis.format(datum, index) : String(datum[xDataKey] ?? '')}\n                    </span>\n                  ))}\n                </div>\n              ) : null}\n            </div>\n            {children}\n          </>\n        ),\n      },\n      props\n    ),\n  });\n\n  return <PyramidChartContext.Provider value={context}>{element}</PyramidChartContext.Provider>;\n});\nPyramidChartRoot.displayName = 'PyramidChart';\n\n/** Hands a part's formatters to the root without a new function rebuilding the chart. */\nfunction useLatest<T>(value: T) {\n  const [latest] = useState(() => ({ current: value }));\n  useEffect(() => {\n    latest.current = value;\n  });\n  return latest;\n}\n\nexport interface PyramidChartGridProps {\n  /** How many lines to draw on each wing. */\n  columns?: number;\n  /** The stroke's dash pattern. */\n  dashArray?: string;\n  /** Opacity of the lines. */\n  opacity?: number;\n  /** Draw the solid line down the middle. A gutter between the wings leaves it out. */\n  centreLine?: boolean;\n}\n\n/** Mirrored reference lines, plus the solid line both wings are measured from. */\nfunction PyramidChartGrid({\n  columns = 2,\n  dashArray = '4 6',\n  opacity = 1,\n  centreLine = true,\n}: PyramidChartGridProps) {\n  const { setSlot } = useChart('PyramidChart.Grid');\n  useEffect(() => {\n    setSlot('grid', { columns, dashArray, opacity, centreLine });\n    return () => setSlot('grid', undefined);\n  }, [columns, dashArray, opacity, centreLine, setSlot]);\n  return null;\n}\nPyramidChartGrid.displayName = 'PyramidChart.Grid';\n\nexport interface PyramidChartBarProps {\n  /** Column in the data holding this series' values. */\n  dataKey: string;\n  /** Which wing it grows into. */\n  side?: PyramidChartSide;\n  /**\n   * Which of the theme's roles the series is drawn in. Defaults to a different\n   * one per side, so two bars with nothing but a key and a side are told apart.\n   */\n  color?: PyramidChartColor;\n  /** Corner radius, overriding the chart's. */\n  cornerRadius?: number;\n}\n\n/** One wing. */\nfunction PyramidChartBar({\n  dataKey,\n  side = 'end',\n  color,\n  cornerRadius,\n}: PyramidChartBarProps) {\n  const { setSeries, removeSeries } = useChart('PyramidChart.Bar');\n  const fill = COLOR_VAR[color ?? (side === 'start' ? 'chart-2' : 'chart-1')];\n  useEffect(() => {\n    setSeries({ key: dataKey, fill, side, radius: cornerRadius });\n  }, [dataKey, fill, side, cornerRadius, setSeries]);\n  // Apart from the update above, so a new colour keeps the series' place in the order.\n  useEffect(() => () => removeSeries(dataKey), [dataKey, removeSeries]);\n  return null;\n}\nPyramidChartBar.displayName = 'PyramidChart.Bar';\n\nexport interface PyramidChartSkeletonProps {\n  /**\n   * How many placeholder rows to draw. Defaults to one per row of data, and to\n   * five when the data has not arrived.\n   */\n  rows?: number;\n  /** Milliseconds for one pass of the sweep. */\n  duration?: number;\n}\n\n/**\n * The loading state: equal stubs either side of the centre, with a highlight\n * travelling across them. Equal, because wings of differing lengths cannot be\n * told from real data.\n *\n * The highlight is a child translated inside a clip of the stubs' outlines, so\n * the loop runs on the compositor and repaints nothing.\n */\nfunction PyramidChartSkeleton({\n  rows,\n  duration = 1400,\n}: PyramidChartSkeletonProps) {\n  const { setSlot } = useChart('PyramidChart.Skeleton');\n  useEffect(() => {\n    setSlot('skeleton', { rows, duration });\n    return () => setSlot('skeleton', undefined);\n  }, [rows, duration, setSlot]);\n  return null;\n}\nPyramidChartSkeleton.displayName = 'PyramidChart.Skeleton';\n\nexport interface PyramidChartXAxisProps {\n  /** How many labels per wing, not counting the zero in the middle. */\n  ticks?: number;\n  /** Format a value for its label. Defaults to a compact number. */\n  format?: (value: number) => string;\n  /** Added to the layer holding the labels. */\n  className?: string;\n}\n\n/**\n * The value labels along the bottom: the same magnitudes twice, either side of a\n * zero, because both wings are read outward from the centre.\n */\nfunction PyramidChartXAxis({\n  ticks = 2,\n  format,\n  className,\n}: PyramidChartXAxisProps) {\n  const { setSlot } = useChart('PyramidChart.XAxis');\n  useEffect(() => {\n    setSlot('xAxis', { ticks, format, className });\n    return () => setSlot('xAxis', undefined);\n  }, [ticks, format, className, setSlot]);\n  return null;\n}\nPyramidChartXAxis.displayName = 'PyramidChart.XAxis';\n\nexport interface PyramidChartYAxisProps {\n  /** Turn a row into its label. Defaults to the value at `xDataKey`. */\n  format?: (datum: PyramidChartDatum, index: number) => string;\n  /** Added to the layer holding the names. */\n  className?: string;\n}\n\n/** The category names, one per row. `labelPlacement` on the chart decides where they sit. */\nfunction PyramidChartYAxis({\n  format,\n  className,\n}: PyramidChartYAxisProps) {\n  const { setSlot } = useChart('PyramidChart.YAxis');\n  useEffect(() => {\n    setSlot('yAxis', { format, className });\n    return () => setSlot('yAxis', undefined);\n  }, [format, className, setSlot]);\n  return null;\n}\nPyramidChartYAxis.displayName = 'PyramidChart.YAxis';\n\nexport interface PyramidChartTooltipProps {\n  /** Format one series' value. Defaults to a compact number. */\n  formatValue?: (value: number, key: string) => string;\n  /** Format the readout's heading from the row. Defaults to the value at xDataKey. */\n  formatX?: (datum: PyramidChartDatum) => string;\n  /** Prettier names for the series keys, as the legend takes. */\n  labels?: Record<string, string>;\n  /** Added to the readout's surface. */\n  className?: string;\n}\n\n/**\n * The readout, and what drives it: hovering a row, pressing or dragging across\n * them, or the arrow keys. A click or a tap pins the reading until the next press\n * elsewhere or Escape. The whole plot is the hit area, and the other rows fade.\n */\nfunction PyramidChartTooltip({\n  formatValue,\n  formatX,\n  labels,\n  className,\n}: PyramidChartTooltipProps) {\n  const { setSlot } = useChart('PyramidChart.Tooltip');\n  const latest = useLatest({ formatValue, formatX, labels });\n  useEffect(() => {\n    setSlot('tooltip', { className, latest });\n    return () => setSlot('tooltip', undefined);\n  }, [className, latest, setSlot]);\n  return null;\n}\nPyramidChartTooltip.displayName = 'PyramidChart.Tooltip';\n\nexport interface PyramidChartLegendProps extends ComponentProps<'div'> {\n  /** Prettier names for the series keys. */\n  labels?: Record<string, string>;\n}\n\n/** A swatch and a name per series, in the order the series were declared. */\nfunction PyramidChartLegend({ labels, className, render, ...props }: PyramidChartLegendProps & RenderProp<'div'>) {\n  const { series } = useChart('PyramidChart.Legend');\n  const slots = pyramidChartVariants();\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'pyramid-chart-legend',\n        'aria-hidden': true,\n        className: slots.legend({ className }),\n        children: series.map(({ key, fill: color }) => (\n          <span key={key} className={slots.legendItem()}>\n            <span className={slots.legendSwatch()} style={{ background: color }} />\n            {labels?.[key] ?? key}\n          </span>\n        )),\n      },\n      props\n    ),\n  });\n\n  return series.length ? element : null;\n}\nPyramidChartLegend.displayName = 'PyramidChart.Legend';\n\nexport interface PyramidChartHeaderProps 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 total. */\n  caption?: ReactNode;\n  /** Prettier names for the series keys, as the legend takes. */\n  labels?: Record<string, string>;\n  /**\n   * Draw a swatch and a name per series along the trailing edge. Prefer this to\n   * `PyramidChart.Legend` on a chart that has a header: the legend sits over the\n   * plot, in the corner the bars also want.\n   */\n  legend?: boolean;\n  /** Trailing slot: a control, a badge, a range picker. Wins over `legend`. */\n  children?: ReactNode;\n}\n\n/**\n * The strip above the plot: what the chart is of, what it reads and what the\n * colours mean. The value is not derived here. A readout that follows the\n * pointer takes it from `onActiveIndexChange` and passes the string down, so one\n * header can show a total at rest and a row's figures while one is read.\n */\nfunction PyramidChartHeader({\n  title,\n  value,\n  caption,\n  labels,\n  legend = false,\n  className,\n  children,\n  render,\n  ...props\n}: PyramidChartHeaderProps & RenderProp<'div'>) {\n  const { series } = useChart('PyramidChart.Header');\n  const slots = pyramidChartVariants();\n  const trailing =\n    children ??\n    (legend && series.length\n      ? series.map(({ key, fill: color }) => (\n          <span key={key} className={slots.legendItem()}>\n            <span className={slots.legendSwatch()} style={{ background: color }} />\n            {labels?.[key] ?? key}\n          </span>\n        ))\n      : null);\n\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'pyramid-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 ? <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}\nPyramidChartHeader.displayName = 'PyramidChart.Header';\n\nexport const PyramidChart = Object.assign(PyramidChartRoot, {\n  Header: PyramidChartHeader,\n  Grid: PyramidChartGrid,\n  Bar: PyramidChartBar,\n  Skeleton: PyramidChartSkeleton,\n  XAxis: PyramidChartXAxis,\n  YAxis: PyramidChartYAxis,\n  Tooltip: PyramidChartTooltip,\n  Legend: PyramidChartLegend,\n});\n\n/* By name as well, for a Server Component, which cannot dot into a client\n   module. */\nexport {\n  PyramidChartHeader,\n  PyramidChartGrid,\n  PyramidChartBar,\n  PyramidChartSkeleton,\n  PyramidChartXAxis,\n  PyramidChartYAxis,\n  PyramidChartTooltip,\n  PyramidChartLegend,\n};\n"
    },
    {
      "path": "components/panelui/pyramid-chart/pyramid-scale.ts",
      "type": "registry:component",
      "target": "@components/panelui/pyramid-chart/pyramid-scale.ts",
      "content": "/**\n * The arithmetic of two wings on one scale, kept apart from the drawing so the\n * parts that are easy to get subtly wrong can be tested without a browser.\n *\n * Positions are in value units with the centre at zero, so a start wing runs\n * negative and an end wing positive. Pixels only come in where something is\n * fixed in pixels: the gutter between the wings and the floor under a small bar.\n */\n\nexport type PyramidSide = 'start' | 'end';\n\n/** Four steps, not two, so the halfway label the axis draws is round as well. */\nconst DOMAIN_STEPS = 4;\n\n/**\n * The far end of a scale that starts at zero, rounded out to a step of 1, 2 or 5\n * times a power of ten. A fraction of headroom would end the axis on 80.3.\n */\nexport function niceMax(max: number, steps = DOMAIN_STEPS): number {\n  if (!Number.isFinite(max) || max <= 0) return 1;\n  const rough = max / steps;\n  const magnitude = 10 ** Math.floor(Math.log10(rough));\n  const error = rough / magnitude;\n  // Geometric means, so each step wins over the span it is closest to.\n  const multiple = error >= Math.sqrt(50) ? 10 : error >= Math.sqrt(10) ? 5 : error >= Math.sqrt(2) ? 2 : 1;\n  const step = multiple * magnitude;\n  return Math.ceil(max / step) * step;\n}\n\n/**\n * The one maximum both wings are measured on, from every value in every series.\n * A maximum per side would give two halves that cannot be compared.\n */\nexport function sharedMax(\n  rows: readonly Readonly<Record<string, unknown>>[],\n  keys: readonly string[],\n  maxValue?: number\n): number {\n  if (maxValue !== undefined && maxValue > 0) return maxValue;\n  let largest = 0;\n  for (const row of rows) {\n    for (const key of keys) {\n      const value = row[key];\n      if (typeof value === 'number' && !Number.isNaN(value) && value > largest) largest = value;\n    }\n  }\n  return niceMax(largest);\n}\n\n/** Half the gutter in value units, so a wing's base sits at that distance from zero. */\nexport function gutterUnits(max: number, plotWidth: number, gutter: number): number {\n  const wing = (plotWidth - gutter) / 2;\n  return wing > 0 ? (max * (gutter / 2)) / wing : 0;\n}\n\n/**\n * A bar's two ends. A value is a distance outward, so a negative one has no\n * direction left to grow in and spans nothing. `floor` is the smallest length a\n * positive value is drawn at, in value units.\n */\nexport function wingSpan(value: number, side: PyramidSide, base: number, floor = 0): [number, number] {\n  const length = value > 0 ? Math.max(value, floor) : 0;\n  const sign = side === 'start' ? -1 : 1;\n  return [sign * base, sign * (base + length)];\n}\n\n/** The thickness of a bar, from what is left of a band once its name has taken a line. */\nexport function barThickness(band: number, labelInset: number, barGap: number, barWidth?: number): number {\n  const room = Math.max(band - labelInset, 0) * (1 - barGap);\n  return barWidth === undefined ? room : Math.min(barWidth, room);\n}\n\n/** The value at each mark along one wing, nearest the centre first, leaving zero out. */\nexport function wingTicks(max: number, count: number): number[] {\n  return Array.from({ length: Math.max(0, count) }, (_unused, index) => (max * (index + 1)) / count);\n}\n"
    }
  ]
}
