{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "mirror-area-chart",
  "type": "registry:component",
  "title": "Mirror Area Chart",
  "description": "Two readings of one timeline, one above a baseline and one below it.",
  "dependencies": [
    "@base-ui/react",
    "@tanstack/charts",
    "d3-shape",
    "tailwind-variants"
  ],
  "devDependencies": [
    "@types/d3-shape"
  ],
  "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/mirror-area-chart/index.tsx",
      "type": "registry:component",
      "target": "@components/panelui/mirror-area-chart/index.tsx",
      "content": "'use client';\n\n/**\n * MirrorAreaChart — two readings of one timeline, one above a baseline and one\n * below it.\n *\n * ```tsx\n * <MirrorAreaChart data={load} xDataKey=\"time\">\n *   <MirrorAreaChart.Grid />\n *   <MirrorAreaChart.Area dataKey=\"jobs\" label=\"jobs\" muted />\n *   <MirrorAreaChart.Area dataKey=\"high\" label=\"high priority\" />\n *   <MirrorAreaChart.Area dataKey=\"share\" label=\"% high\" side=\"bottom\" />\n *   <MirrorAreaChart.Baseline />\n *   <MirrorAreaChart.Tooltip />\n * </MirrorAreaChart>\n * ```\n *\n * ## Two scales, one timeline\n *\n * Each half has its own scale, because the two readings are usually in different\n * units. Both grow away from the baseline, so a peak in one lines up with whatever\n * the other did at the same moment, and neither is squeezed into the other's range.\n * The chart draws on one axis, in shares of the plot, and works out each value's\n * position for its half.\n *\n * ## The parts describe, the root draws\n *\n * The parts draw nothing themselves. Each one tells the root what it wants, and the\n * root builds one chart definition from them, in a box its `aspectRatio` has\n * reserved. Areas on one side overlay in the order they are declared, so declare\n * the whole first and the part of it second.\n *\n * ## The same parts as the app\n *\n * The parts and their props are the app library's MirrorAreaChart. What differs is\n * what the web changes: a colour is named by the theme's role, a point is read by\n * hovering, tapping or dragging, a click pins the reading, and the arrow keys walk\n * the points.\n */\nimport { areaY, d3Curve, defineChart, dot, lineY, ruleY, type ChartInteractionController, type ChartMotionContext, type ChartPoint } from '@tanstack/charts';\nimport { crosshair } from '@tanstack/charts/crosshair';\nimport { whenFocused } from '@tanstack/charts/focus/mark';\nimport { decorative } from '@tanstack/charts/mark/decorative';\nimport { motion } from '@tanstack/charts/motion';\nimport { Chart } from '@tanstack/charts/react/core';\nimport { scaleLinear } from '@tanstack/charts/scales/linear';\nimport { tooltip as chartTooltip } from '@tanstack/charts/tooltip';\nimport { curveLinear, curveMonotoneX } from 'd3-shape';\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 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 { mirrorPosition, mirrorShare, outerValue, readValue, sideExtent, tickIndexes, type MirrorAreaChartSide } from './mirror-scale';\n\nexport type { MirrorAreaChartSide };\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 MirrorAreaChartStatus = 'loading' | 'ready';\nexport type MirrorAreaChartCurve = 'monotone' | 'linear';\nexport type MirrorAreaChartDatum = Record<string, string | number | null | undefined>;\n\n/** Which of the theme's roles something is drawn in. */\nexport type MirrorAreaChartColor =\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  | 'foreground'\n  | 'muted-foreground';\n\nconst COLOR_VAR: Record<MirrorAreaChartColor, 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  foreground: 'var(--foreground)',\n  'muted-foreground': 'var(--muted-foreground)',\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 CURVES = { monotone: d3Curve(curveMonotoneX), linear: d3Curve(curveLinear) };\n\nconst mirrorAreaChartVariants = 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    dots: 'pointer-events-none absolute inset-0 size-full',\n    skeleton: 'pointer-events-none absolute overflow-hidden rounded-sm bg-muted',\n    sweep:\n      'absolute inset-y-0 left-0 w-2/5 bg-[linear-gradient(90deg,transparent,color-mix(in_oklab,var(--chart-1)_30%,transparent),transparent)] motion-reduce:hidden',\n    legend:\n      'pointer-events-none absolute right-2 top-0 col-start-1 row-start-2 flex flex-wrap justify-end gap-x-3 gap-y-1 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 left around the plot for the axis labels. */\nconst MARGIN = { top: 12, right: 10, bottom: 30, left: 10 };\n\n/** The left margin when a `YAxis` needs somewhere to write. */\nconst Y_AXIS_WIDTH = 40;\n\n/** Keeps a compact band's stroke from being cut at the edges of its box. */\nconst COMPACT_MARGIN = { top: 2, right: 1, bottom: 2, left: 1 };\n\n/** How far the skeleton's band reaches into each half. */\nconst SKELETON_REACH = 0.18;\n\n/** Both halves grow out of the baseline at once, while the grid and axes are already there. */\nconst STYLES = `@keyframes panelui-mirror-sweep{from{transform:translateX(-100%)}to{transform:translateX(250%)}}\n@keyframes panelui-mirror-reveal{from{transform:scaleY(0)}to{transform:scaleY(1)}}\n@media (prefers-reduced-motion:no-preference){[data-slot=mirror-area-chart-plot][data-revealing] :is(.ts-chart__line,.ts-chart__area){transform-origin:0 var(--mirror-baseline);animation:panelui-mirror-reveal var(--mirror-reveal) cubic-bezier(.33,1,.68,1) both}}`;\n\nconst COMPACT = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 });\nconst COMPACT_SMALL = new Intl.NumberFormat('en', { notation: 'compact', maximumSignificantDigits: 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 point of one band. `position` is null across a gap. */\ninterface BandRow {\n  index: number;\n  position: number | null;\n}\n\ninterface SeriesEntry {\n  key: string;\n  label: string;\n  side: MirrorAreaChartSide;\n  stroke: string;\n  outer: number;\n  inner: number;\n  showLine: boolean;\n  strokeWidth: number;\n}\n\n/** Where the drawing put the plot, in pixels inside the chart's box. */\ninterface PlotBox {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n}\n\n/**\n * What the parts have asked for. An axis formatter is part of the drawing, so a new\n * one redraws it. The readout's are read through `latest` when it opens.\n */\ninterface Slots {\n  grid?: { variant: 'dots' | 'lines'; spacing: number | undefined; opacity: number; stroke: string };\n  baseline?: { stroke: string; strokeWidth: number; opacity: number };\n  xAxis?: { ticks: number; format: MirrorAreaChartXAxisProps['format'] };\n  yAxis?: { formatTop: MirrorAreaChartYAxisProps['formatTop']; formatBottom: MirrorAreaChartYAxisProps['formatBottom'] };\n  tooltip?: {\n    stroke: string;\n    className: string | undefined;\n    latest: { current: Pick<MirrorAreaChartTooltipProps, 'formatValue' | 'formatX' | 'formatSummary'> };\n  };\n  skeleton?: { duration: number; base: string | undefined };\n}\n\ninterface MirrorAreaChartContextValue {\n  data: readonly MirrorAreaChartDatum[];\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 MirrorAreaChartContext = createContext<MirrorAreaChartContextValue | null>(null);\n\nfunction useChart(component: string): MirrorAreaChartContextValue {\n  const context = useContext(MirrorAreaChartContext);\n  if (!context) {\n    throw new Error(`${component} must be used within a <MirrorAreaChart>`);\n  }\n  return context;\n}\n\n/** The row being read, for something rendered inside the chart. */\nexport function useMirrorAreaChart() {\n  const { data, activeIndex, xDataKey } = useChart('useMirrorAreaChart');\n  return {\n    activeIndex,\n    activePoint: activeIndex >= 0 ? (data[activeIndex] ?? null) : null,\n    xDataKey,\n  };\n}\n\n/** Top-half areas first, then the bottom half's, each in declaration order. */\nfunction sidesInOrder(series: readonly SeriesEntry[]) {\n  return [...series.filter(({ side }) => side === 'top'), ...series.filter(({ side }) => side === 'bottom')];\n}\n\nexport interface MirrorAreaChartProps extends Omit<ComponentProps<'div'>, 'ref'> {\n  /** The rows. Each one is a point along the x-axis. */\n  data: readonly MirrorAreaChartDatum[];\n  /** Key holding the x label. Used by the axis and the readout. */\n  xDataKey?: string;\n  /** How much of the plot's height sits above the baseline, from `0` to `1`. Give the half you want read first the larger share. */\n  split?: number;\n  /** Fix the top half's scale instead of deriving it from the data. Only the upper end is used: the baseline is always zero. */\n  topDomain?: [number, number];\n  /** Fix the bottom half's scale. Only the upper end is used. */\n  bottomDomain?: [number, number];\n  /** `monotone` never overshoots between points; `linear` joins them straight. */\n  curve?: MirrorAreaChartCurve;\n  /** `loading` holds the bands back and grows them out when it turns `ready`. Add a `MirrorAreaChart.Skeleton` to show something meanwhile. */\n  status?: MirrorAreaChartStatus;\n  /** The plot's width ÷ height. */\n  aspectRatio?: number;\n  /** Milliseconds for the bands to grow out. */\n  animationDuration?: number;\n  /** Milliseconds for the bands to settle after the data changes. */\n  domainDuration?: number;\n  /** The row being read, and `-1`/`null` when there is none. Fires when the index changes, not per frame. */\n  onActiveIndexChange?: (index: number, datum: MirrorAreaChartDatum | null) => void;\n  /** Drop the axis padding so the bands reach the edges, for a sparkline. */\n  compact?: boolean;\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: MirrorAreaChartDatum, index: number) => string;\n}\n\n/** Imperative handle: re-run the reveal, for a \"replay\" control. */\nexport interface MirrorAreaChartHandle {\n  replay: () => void;\n}\n\nconst MirrorAreaChartRoot = forwardRef<MirrorAreaChartHandle, MirrorAreaChartProps & RenderProp<'div'>>(function MirrorAreaChartRoot(\n  {\n    data,\n    xDataKey = 'date',\n    split = 0.55,\n    topDomain,\n    bottomDomain,\n    curve = 'monotone',\n    status = 'ready',\n    aspectRatio = 1.6,\n    animationDuration = 700,\n    domainDuration = 500,\n    onActiveIndexChange,\n    compact = false,\n    label,\n    labelForDatum,\n    className,\n    children,\n    render,\n    ...props\n  },\n  ref\n) {\n  const slotClasses = mirrorAreaChartVariants();\n  const plotRef = useRef<HTMLDivElement>(null);\n  const [width, setWidth] = useState(0);\n  const [series, setSeriesList] = useState<readonly SeriesEntry[]>([]);\n  const [slots, setSlots] = useState<Slots>({});\n  const [activeIndex, setActiveIndex] = useState(-1);\n  const [revision, setRevision] = useState(0);\n  const [revealedKey, setRevealedKey] = useState('');\n  const [box, setBox] = useState<PlotBox | null>(null);\n  const interactionRef = useRef<ChartInteractionController<BandRow, number, number> | null>(null);\n  const dragging = useRef(false);\n  // Unique per chart: gradients are found by id across the whole page.\n  const idPrefix = `panelui-mirror-${useId().replace(/[^a-zA-Z0-9]/g, '')}`;\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  // Puts an entry in its place, or at the end if it is new, so a change keeps the order.\n  const setSeries = useCallback(\n    (entry: SeriesEntry) =>\n      setSeriesList((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((key: string) => setSeriesList((current) => current.filter((entry) => entry.key !== key)), []);\n  const setSlot = useCallback<MirrorAreaChartContextValue['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 chartKey = `${revision}:${status}`;\n  // A finished reveal counts for this load only, so the next one plays again.\n  useEffect(() => {\n    if (loading) setRevealedKey('');\n  }, [loading]);\n  const { grid, baseline, xAxis, yAxis, tooltip, skeleton } = slots;\n  const share = mirrorShare(split);\n\n  const definition = useMemo(() => {\n    const curveFactory = CURVES[curve];\n    const span = Math.max(1, data.length - 1);\n    const keysOf = (side: MirrorAreaChartSide) => series.filter((entry) => entry.side === side).map(({ key }) => key);\n    const extents = {\n      top: sideExtent(data, keysOf('top'), topDomain),\n      bottom: sideExtent(data, keysOf('bottom'), bottomDomain),\n    };\n    const position = (value: number | null, side: MirrorAreaChartSide) =>\n      value === null ? null : mirrorPosition(value, side, extents[side], share);\n    const rowsOf = ({ key, side }: SeriesEntry): BandRow[] =>\n      data.map((datum, index) => ({ index, position: position(readValue(datum[key]), side) }));\n\n    const gradientId = (key: string) => `${idPrefix}-${series.findIndex((entry) => entry.key === key)}`;\n    const bands = series.map((entry) =>\n      decorative(\n        areaY(rowsOf(entry), {\n          id: `mirror-area-${entry.key}`,\n          x: 'index',\n          y1: () => 0,\n          y2: 'position',\n          key: 'index',\n          fill: `url(#${gradientId(entry.key)})`,\n          fillOpacity: 1,\n          curve: curveFactory,\n        })\n      )\n    );\n    const edges = series\n      .filter(({ showLine }) => showLine)\n      .map((entry) =>\n        decorative(\n          lineY(rowsOf(entry), {\n            id: `mirror-edge-${entry.key}`,\n            x: 'index',\n            y: 'position',\n            key: 'index',\n            stroke: entry.stroke,\n            strokeWidth: entry.strokeWidth,\n            lineCap: 'round',\n            lineJoin: 'round',\n            curve: curveFactory,\n          })\n        )\n      );\n    // The dot rides the outermost edge of the top half, or of the bottom when there is no top.\n    const dotSide: MirrorAreaChartSide = keysOf('top').length ? 'top' : 'bottom';\n    const dotKeys = keysOf(dotSide);\n    const dotRows = data.flatMap((datum, index) => {\n      const value = outerValue(datum, dotKeys);\n      return value === null ? [] : [{ index, position: position(value, dotSide) }];\n    });\n\n    const labelOf = (index: number) => {\n      const datum = data[index];\n      if (!datum) return '';\n      return xAxis?.format ? xAxis.format(datum, index) : String(datum[xDataKey] ?? '');\n    };\n\n    const valueTicks = [share, 0, share - 1];\n    const valueLabel = (value: number) => {\n      if (value === 0) return '0';\n      return value > 0\n        ? (yAxis?.formatTop ?? compactNumber)(extents.top)\n        : (yAxis?.formatBottom ?? compactNumber)(extents.bottom);\n    };\n    const rules = Math.max(Math.round(grid?.spacing ?? 2), 1);\n    const ruleTicks = Array.from({ length: rules }, (_, index) => index + 1).flatMap((step) => [\n      (share * step) / rules,\n      ((share - 1) * step) / rules,\n    ]);\n    const lined = grid?.variant === 'lines';\n\n    const interactive = tooltip !== undefined && !loading && data.length > 0 && series.length > 0;\n    const marks = loading\n      ? []\n      : [\n          ...bands,\n          ...edges,\n          ...(baseline\n            ? [\n                decorative(\n                  ruleY([0], {\n                    id: 'mirror-baseline',\n                    stroke: baseline.stroke,\n                    strokeWidth: baseline.strokeWidth,\n                    strokeOpacity: baseline.opacity,\n                  })\n                ),\n              ]\n            : []),\n          ...(interactive\n            ? [\n                // What the pointer and the keys land on: one point for every row, gap or not.\n                lineY(\n                  data.map((_, index) => ({ index, position: 0 })),\n                  { id: 'mirror-focus', x: 'index', y: 'position', key: 'index', stroke: 'transparent' }\n                ),\n                crosshair<number, number>({ y: false, stroke: tooltip.stroke, strokeOpacity: 0.6, strokeWidth: 1, strokeDasharray: '3 4' }),\n                whenFocused(\n                  dot(dotRows, {\n                    id: 'mirror-dot',\n                    x: 'index',\n                    y: 'position',\n                    key: 'index',\n                    r: 4.5,\n                    fill: tooltip.stroke,\n                    stroke: 'var(--background)',\n                    strokeWidth: 2,\n                  }),\n                  { match: 'x' }\n                ),\n              ]\n            : []),\n        ];\n\n    return defineChart({\n      theme: THEME,\n      marks,\n      margin: compact ? COMPACT_MARGIN : { ...MARGIN, left: yAxis ? Y_AXIS_WIDTH : MARGIN.left },\n      scales: {\n        x: {\n          scale: scaleLinear([0, span], [0, 1]),\n          axis:\n            xAxis && !compact\n              ? {\n                  line: false as const,\n                  // The two ends lean inward, clear of the plot's edge.\n                  tickLabels: {\n                    opacity: 1,\n                    anchor: ({ value }: { value: number }) =>\n                      value === 0 ? ('start' as const) : value === data.length - 1 ? ('end' as const) : undefined,\n                  },\n                  ticks: { size: 0, format: labelOf, values: tickIndexes(data.length, xAxis.ticks) },\n                }\n              : (false as const),\n        },\n        y: {\n          scale: scaleLinear([share - 1, share], [0, 1]),\n          grid: lined ? { stroke: grid.stroke, strokeOpacity: grid.opacity, strokeDasharray: '4 6' } : false,\n          axis:\n            yAxis && !compact && !loading\n              ? {\n                  line: false as const,\n                  tickLabels: { opacity: 1 },\n                  // Two scales, so three labels: a column of even numbers would suggest one.\n                  ticks: { size: 0, values: lined ? [...valueTicks, ...ruleTicks] : valueTicks, format: (value: number) => (valueTicks.includes(value) ? valueLabel(value) : '') },\n                }\n              : lined\n                ? { line: false as const, ticks: { size: 0, values: ruleTicks, format: () => '' } }\n                : (false as const),\n        },\n      },\n      gradients: series.map(({ key, side, stroke, outer, inner }) => ({\n        id: gradientId(key),\n        x1: 0,\n        y1: 0,\n        x2: 0,\n        y2: 1,\n        // Top to bottom in the band's own box: the outer edge is at the top of a top band.\n        stops: [\n          { offset: 0, color: stroke, opacity: side === 'top' ? outer : inner },\n          { offset: 1, color: stroke, opacity: side === 'top' ? inner : outer },\n        ],\n      })),\n      focusRing: false,\n      // The bands arrive by the animation in `STYLES`, and everything else is simply there.\n      motion: (context: ChartMotionContext<BandRow>) =>\n        context.phase === 'enter'\n          ? (false as const)\n          : { transition: { type: 'tween' as const, duration: domainDuration, easing: 'ease-out' as const } },\n      keyboard: interactive,\n      pointer: interactive,\n      ...(interactive\n        ? {\n            focus: 'group-x' as const,\n            maxFocusDistance: Number.POSITIVE_INFINITY,\n            tooltip: {\n              use: chartTooltip,\n              className: tooltip.className,\n              // Beside the crosshair and along the top, on whichever side has room.\n              anchor: { x: 'value', y: 'plot-top' } as const,\n              placement: ['bottom-left', 'bottom-right'] as const,\n              offset: 14,\n              content(points: readonly ChartPoint<BandRow, number, number>[]) {\n                const { formatValue, formatX, formatSummary } = tooltip.latest.current;\n                const index = points[0]?.datum.index ?? -1;\n                const datum = data[index];\n                if (!datum) return { title: '', rows: [] };\n                const title = formatX ? formatX(datum) : String(datum[xDataKey] ?? '');\n                if (formatSummary) return { title, rows: [{ label: formatSummary(datum), value: '' }] };\n                return {\n                  title,\n                  rows: series.flatMap(({ key, label: name, stroke }) => {\n                    const value = readValue(datum[key]);\n                    if (value === null) return [];\n                    return [{ label: name, value: formatValue ? formatValue(value, key) : compactNumber(value), color: stroke }];\n                  }),\n                };\n              },\n            },\n          }\n        : {}),\n    });\n  }, [\n    data,\n    xDataKey,\n    series,\n    loading,\n    curve,\n    share,\n    topDomain?.[0],\n    topDomain?.[1],\n    bottomDomain?.[0],\n    bottomDomain?.[1],\n    compact,\n    domainDuration,\n    idPrefix,\n    grid,\n    baseline,\n    xAxis,\n    yAxis,\n    tooltip,\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 ?? `Mirror area chart, ${data.length} ${data.length === 1 ? 'row' : 'rows'}`;\n\n  const context = useMemo<MirrorAreaChartContextValue>(\n    () => ({ data, xDataKey, series, setSeries, removeSeries, setSlot, activeIndex }),\n    [data, xDataKey, series, setSeries, removeSeries, setSlot, activeIndex]\n  );\n\n  const spokenRow = (datum: MirrorAreaChartDatum, index: number) =>\n    labelForDatum?.(datum, index) ??\n    [\n      `${xDataKey}, ${datum[xDataKey] ?? ''}`,\n      ...series.filter(({ key }) => readValue(datum[key]) !== null).map(({ key, label: name }) => `${name}, ${datum[key]}`),\n    ].join('. ');\n\n  // The chart also reports a point again when the data is rebuilt under it. Only a\n  // change of point 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<BandRow, number, number> | null) => 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  /*\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 points 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  const baselineY = box ? box.y + box.height * share : 0;\n  const dotGap = Math.max(grid?.spacing ?? 12, 4);\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'mirror-area-chart',\n        className: slotClasses.root({ className }),\n        children: (\n          <>\n            <style>{STYLES}</style>\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=\"mirror-area-chart-plot\"\n              data-revealing={!loading && revealedKey !== chartKey ? '' : undefined}\n              className={slotClasses.plot()}\n              style={{ aspectRatio, ['--mirror-reveal' as string]: `${animationDuration}ms`, ['--mirror-baseline' as string]: `${baselineY}px` }}\n              onAnimationEnd={(event) => {\n                if (event.animationName === 'panelui-mirror-reveal') setRevealedKey(chartKey);\n              }}\n              onKeyDown={(event) => {\n                if (event.key === 'Escape') interactionRef.current?.setControlledFocus(null);\n              }}\n              onPointerMove={readDrag}\n              onPointerCancel={() => interactionRef.current?.setControlledFocus(null)}\n            >\n              {/* Dots are a tile from the baseline, so one row always lies on it. */}\n              {box && grid && grid.variant === 'dots' && !compact ? (\n                <svg data-slot=\"mirror-area-chart-grid\" aria-hidden className={slotClasses.dots()} style={{ opacity: grid.opacity }}>\n                  <defs>\n                    <pattern\n                      id={`${idPrefix}-dots`}\n                      x={box.x}\n                      y={baselineY - dotGap / 2}\n                      width={dotGap}\n                      height={dotGap}\n                      patternUnits=\"userSpaceOnUse\"\n                    >\n                      <circle cx={dotGap / 2} cy={dotGap / 2} r={0.9} style={{ fill: grid.stroke }} />\n                    </pattern>\n                  </defs>\n                  <rect x={box.x} y={box.y} width={box.width} height={box.height} fill={`url(#${idPrefix}-dots)`} />\n                </svg>\n              ) : null}\n              {width > 0 ? (\n                <Chart\n                  // The reveal belongs to a new chart: a load finishing, or a replay.\n                  key={chartKey}\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                    const { x, y, width: plotWidth, height } = scene.chart;\n                    setBox((current) =>\n                      current && current.x === x && current.y === y && current.width === plotWidth && current.height === height\n                        ? current\n                        : { x, y, width: plotWidth, height }\n                    );\n                  }}\n                />\n              ) : null}\n              {loading && skeleton && box ? (\n                <div\n                  data-slot=\"mirror-area-chart-skeleton\"\n                  aria-hidden\n                  className={slotClasses.skeleton()}\n                  style={{\n                    left: box.x,\n                    width: box.width,\n                    top: baselineY - box.height * share * SKELETON_REACH,\n                    height: box.height * SKELETON_REACH,\n                    background: skeleton.base,\n                  }}\n                >\n                  <div className={slotClasses.sweep()} style={{ animation: `panelui-mirror-sweep ${skeleton.duration}ms linear infinite` }} />\n                </div>\n              ) : null}\n            </div>\n            {children}\n          </>\n        ),\n      },\n      props\n    ),\n  });\n\n  return <MirrorAreaChartContext.Provider value={context}>{element}</MirrorAreaChartContext.Provider>;\n});\nMirrorAreaChartRoot.displayName = 'MirrorAreaChart';\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 MirrorAreaChartGridProps {\n  /** `dots` is a field of points; `lines` is dashed rules across each half. */\n  variant?: 'dots' | 'lines';\n  /** Distance between dots in pixels, or how many rules each half gets. */\n  spacing?: number;\n  /** Opacity of the dots or the rules. */\n  opacity?: number;\n  /** Which of the theme's roles they are drawn in. Defaults to the border colour. */\n  color?: MirrorAreaChartColor;\n}\n\n/** The texture behind the bands. Dots by default, which mark the plot's extent without competing with the baseline. */\nfunction MirrorAreaChartGrid({\n  variant = 'dots',\n  spacing,\n  opacity = 1,\n  color,\n}: MirrorAreaChartGridProps) {\n  const { setSlot } = useChart('MirrorAreaChart.Grid');\n  const stroke = color ? COLOR_VAR[color] : 'var(--border)';\n  useEffect(() => {\n    setSlot('grid', { variant, spacing, opacity, stroke });\n    return () => setSlot('grid', undefined);\n  }, [variant, spacing, opacity, stroke, setSlot]);\n  return null;\n}\nMirrorAreaChartGrid.displayName = 'MirrorAreaChart.Grid';\n\nexport interface MirrorAreaChartBaselineProps {\n  /** Which of the theme's roles the line is drawn in. */\n  color?: MirrorAreaChartColor;\n  /** The line's width. */\n  strokeWidth?: number;\n  /** The line's opacity. */\n  opacity?: number;\n}\n\n/** The line both halves grow away from, drawn over the bands. */\nfunction MirrorAreaChartBaseline({\n  color = 'muted-foreground',\n  strokeWidth = 1,\n  opacity = 0.5,\n}: MirrorAreaChartBaselineProps) {\n  const { setSlot } = useChart('MirrorAreaChart.Baseline');\n  const stroke = COLOR_VAR[color];\n  useEffect(() => {\n    setSlot('baseline', { stroke, strokeWidth, opacity });\n    return () => setSlot('baseline', undefined);\n  }, [stroke, strokeWidth, opacity, setSlot]);\n  return null;\n}\nMirrorAreaChartBaseline.displayName = 'MirrorAreaChart.Baseline';\n\nexport interface MirrorAreaChartAreaProps {\n  /** Column in the data holding this series' values. A missing value leaves a gap. */\n  dataKey: string;\n  /** Which half it is drawn in. */\n  side?: MirrorAreaChartSide;\n  /** The name shown by the readout and the legend. Defaults to `dataKey`. */\n  label?: string;\n  /** Which of the theme's roles it is drawn in. */\n  color?: MirrorAreaChartColor;\n  /** Draw it in the muted foreground colour instead, for a total that the coloured areas are parts of. */\n  muted?: boolean;\n  /** Opacity of the fill at the band's outer edge. */\n  fillOpacity?: number;\n  /** Opacity of the fill at the baseline. Defaults to `fillOpacity`, a flat fill. */\n  gradientToOpacity?: number;\n  /** Draw the line along the band's outer edge. */\n  showLine?: boolean;\n  /** Thickness of that line. */\n  strokeWidth?: number;\n}\n\n/**\n * One band, growing away from the baseline on its side. Areas on one side overlay\n * in declaration order, so a whole declared first is drawn behind a part of it\n * declared second.\n */\nfunction MirrorAreaChartArea({\n  dataKey,\n  side = 'top',\n  label,\n  color = 'chart-1',\n  muted = false,\n  fillOpacity,\n  gradientToOpacity,\n  showLine = true,\n  strokeWidth = 1.5,\n}: MirrorAreaChartAreaProps) {\n  const { setSeries, removeSeries } = useChart('MirrorAreaChart.Area');\n  const stroke = COLOR_VAR[muted ? 'muted-foreground' : color];\n  const outer = fillOpacity ?? (muted ? 0.22 : 0.3);\n  const inner = gradientToOpacity ?? outer;\n  const name = label ?? dataKey;\n  useEffect(() => {\n    setSeries({ key: dataKey, label: name, side, stroke, outer, inner, showLine, strokeWidth });\n  }, [dataKey, name, side, stroke, outer, inner, showLine, strokeWidth, setSeries]);\n  // Apart from the update above, so a new colour keeps the band's place in the order.\n  useEffect(() => () => removeSeries(dataKey), [dataKey, removeSeries]);\n  return null;\n}\nMirrorAreaChartArea.displayName = 'MirrorAreaChart.Area';\n\nexport interface MirrorAreaChartSkeletonProps {\n  /** Milliseconds for one pass of the sweep. */\n  duration?: number;\n  /** Which of the theme's roles the band is drawn in, under the highlight. Defaults to the muted colour. */\n  color?: MirrorAreaChartColor;\n}\n\n/**\n * The loading state: a low band either side of the baseline with a highlight\n * travelling across it. It is a translated child inside the band's clip, so the\n * loop runs on the compositor and repaints nothing.\n */\nfunction MirrorAreaChartSkeleton({\n  duration = 1400,\n  color,\n}: MirrorAreaChartSkeletonProps) {\n  const { setSlot } = useChart('MirrorAreaChart.Skeleton');\n  const base = color && COLOR_VAR[color];\n  useEffect(() => {\n    setSlot('skeleton', { duration, base });\n    return () => setSlot('skeleton', undefined);\n  }, [duration, base, setSlot]);\n  return null;\n}\nMirrorAreaChartSkeleton.displayName = 'MirrorAreaChart.Skeleton';\n\nexport interface MirrorAreaChartXAxisProps {\n  /** How many labels to show, evenly spaced with both ends kept. */\n  ticks?: number;\n  /** Turn a row into its label. Defaults to the value at `xDataKey`. */\n  format?: (datum: MirrorAreaChartDatum, index: number) => string;\n}\n\n/** The x labels, each on its own point. */\nfunction MirrorAreaChartXAxis({\n  ticks = 4,\n  format,\n}: MirrorAreaChartXAxisProps) {\n  const { setSlot } = useChart('MirrorAreaChart.XAxis');\n  useEffect(() => {\n    setSlot('xAxis', { ticks, format });\n    return () => setSlot('xAxis', undefined);\n  }, [ticks, format, setSlot]);\n  return null;\n}\nMirrorAreaChartXAxis.displayName = 'MirrorAreaChart.XAxis';\n\nexport interface MirrorAreaChartYAxisProps {\n  /** Format a value in the top half. */\n  formatTop?: (value: number) => string;\n  /** Format a value in the bottom half. */\n  formatBottom?: (value: number) => string;\n}\n\n/** Three labels down the side: the top half's maximum, zero on the baseline, and the bottom half's maximum. */\nfunction MirrorAreaChartYAxis({\n  formatTop,\n  formatBottom,\n}: MirrorAreaChartYAxisProps) {\n  const { setSlot } = useChart('MirrorAreaChart.YAxis');\n  useEffect(() => {\n    setSlot('yAxis', { formatTop, formatBottom });\n    return () => setSlot('yAxis', undefined);\n  }, [formatTop, formatBottom, setSlot]);\n  return null;\n}\nMirrorAreaChartYAxis.displayName = 'MirrorAreaChart.YAxis';\n\nexport interface MirrorAreaChartTooltipProps {\n  /** The crosshair's and the dot's colour, as one of the theme's roles. */\n  color?: MirrorAreaChartColor;\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: MirrorAreaChartDatum) => string;\n  /** One line to show instead of a row per series. Use it when the series only make sense read together. */\n  formatSummary?: (datum: MirrorAreaChartDatum) => string;\n  /** Added to the readout's surface. */\n  className?: string;\n}\n\n/**\n * A dashed crosshair, a dot on the outer edge of the top half, and a readout beside\n * them, driven by hovering, pressing or dragging across the plot, or the arrow keys.\n * A click or a tap pins the reading until the next press elsewhere or Escape.\n */\nfunction MirrorAreaChartTooltip({\n  color = 'foreground',\n  formatValue,\n  formatX,\n  formatSummary,\n  className,\n}: MirrorAreaChartTooltipProps) {\n  const { setSlot } = useChart('MirrorAreaChart.Tooltip');\n  const latest = useLatest({ formatValue, formatX, formatSummary });\n  const stroke = COLOR_VAR[color];\n  useEffect(() => {\n    setSlot('tooltip', { stroke, className, latest });\n    return () => setSlot('tooltip', undefined);\n  }, [stroke, className, latest, setSlot]);\n  return null;\n}\nMirrorAreaChartTooltip.displayName = 'MirrorAreaChart.Tooltip';\n\n/** A swatch and a name per area, top half first. */\nfunction seriesKey(series: readonly SeriesEntry[], slots: ReturnType<typeof mirrorAreaChartVariants>) {\n  return sidesInOrder(series).map(({ key, label, stroke }) => (\n    <span key={key} className={slots.legendItem()}>\n      <span className={slots.legendSwatch()} style={{ background: stroke }} />\n      {label}\n    </span>\n  ));\n}\n\nexport type MirrorAreaChartLegendProps = ComponentProps<'div'>;\n\n/** A swatch and a name per area, over the top corner of the plot. On a chart with a header, use its `legend` prop. */\nfunction MirrorAreaChartLegend({\n  className,\n  render,\n  ...props\n}: MirrorAreaChartLegendProps & RenderProp<'div'>) {\n  const { series } = useChart('MirrorAreaChart.Legend');\n  const slots = mirrorAreaChartVariants();\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'mirror-area-chart-legend',\n        'aria-hidden': true,\n        className: slots.legend({ className }),\n        children: seriesKey(series, slots),\n      },\n      props\n    ),\n  });\n\n  return series.length ? element : null;\n}\nMirrorAreaChartLegend.displayName = 'MirrorAreaChart.Legend';\n\nexport interface MirrorAreaChartHeaderProps 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  /** Draw a swatch and a name per area along the trailing edge. */\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. The value is not derived here: pass the formatted\n * string, from `onActiveIndexChange` if it follows the pointer.\n */\nfunction MirrorAreaChartHeader({\n  title,\n  value,\n  caption,\n  legend = false,\n  className,\n  children,\n  render,\n  ...props\n}: MirrorAreaChartHeaderProps & RenderProp<'div'>) {\n  const { series } = useChart('MirrorAreaChart.Header');\n  const slots = mirrorAreaChartVariants();\n  const trailing = children ?? (legend && series.length ? seriesKey(series, slots) : null);\n\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'mirror-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 ? <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}\nMirrorAreaChartHeader.displayName = 'MirrorAreaChart.Header';\n\nexport const MirrorAreaChart = Object.assign(MirrorAreaChartRoot, {\n  Header: MirrorAreaChartHeader,\n  Grid: MirrorAreaChartGrid,\n  Area: MirrorAreaChartArea,\n  Baseline: MirrorAreaChartBaseline,\n  Skeleton: MirrorAreaChartSkeleton,\n  XAxis: MirrorAreaChartXAxis,\n  YAxis: MirrorAreaChartYAxis,\n  Tooltip: MirrorAreaChartTooltip,\n  Legend: MirrorAreaChartLegend,\n});\n\n/* By name as well, for a Server Component, which cannot dot into a client\n   module. */\nexport {\n  MirrorAreaChartHeader,\n  MirrorAreaChartGrid,\n  MirrorAreaChartArea,\n  MirrorAreaChartBaseline,\n  MirrorAreaChartSkeleton,\n  MirrorAreaChartXAxis,\n  MirrorAreaChartYAxis,\n  MirrorAreaChartTooltip,\n  MirrorAreaChartLegend,\n};\n"
    },
    {
      "path": "components/panelui/mirror-area-chart/mirror-scale.ts",
      "type": "registry:component",
      "target": "@components/panelui/mirror-area-chart/mirror-scale.ts",
      "content": "export type MirrorAreaChartSide = 'top' | 'bottom';\n\n/** A finite number, or null for a gap: a missing or non-numeric value leaves one in the band. */\nexport function readValue(value: unknown): number | null {\n  return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\n/** How much of the plot sits above the baseline, kept to where both halves can still be read. */\nexport function mirrorShare(split: number): number {\n  return Math.min(Math.max(Number.isFinite(split) ? split : 0.55, 0.1), 0.9);\n}\n\n/**\n * The value at one half's outer edge: the largest on that side plus 8%, so a peak\n * does not touch the edge of the plot. A fixed domain gives only its upper end,\n * because the baseline is always zero, and counts only when both ends are finite.\n */\nexport function sideExtent(\n  data: readonly Record<string, unknown>[],\n  keys: readonly string[],\n  explicit: readonly [number, number] | undefined\n): number {\n  if (explicit && Number.isFinite(explicit[0]) && Number.isFinite(explicit[1])) return Math.max(explicit[1], 0) || 1;\n  let max = 0;\n  for (const row of data) {\n    for (const key of keys) {\n      const value = readValue(row[key]);\n      if (value !== null && value > max) max = value;\n    }\n  }\n  return max > 0 ? max * 1.08 : 1;\n}\n\n/**\n * Both halves on one axis, in shares of the plot. The baseline is zero, the top\n * edge is `share` and the bottom edge is `share - 1`, so a value's height is a\n * fraction of its own half. A negative value is drawn on the baseline, because\n * each half only grows away from it.\n */\nexport function mirrorPosition(value: number, side: MirrorAreaChartSide, extent: number, share: number): number {\n  const reach = Math.max(value, 0) / extent;\n  return side === 'top' ? reach * share : -reach * (1 - share);\n}\n\n/** The largest value in a row among some keys, or null if it has none. */\nexport function outerValue(row: Record<string, unknown>, keys: readonly string[]): number | null {\n  let most: number | null = null;\n  for (const key of keys) {\n    const value = readValue(row[key]);\n    if (value !== null && (most === null || value > most)) most = value;\n  }\n  return most;\n}\n\n/** Which rows get an x label: `ticks` of them, evenly spaced, with both ends kept. */\nexport function tickIndexes(rows: number, ticks: number): number[] {\n  if (rows < 1) return [];\n  const count = Math.max(1, Math.min(Math.floor(ticks), rows));\n  const step = count > 1 ? (rows - 1) / (count - 1) : 0;\n  return Array.from({ length: count }, (_, index) => Math.round(index * step));\n}\n"
    }
  ]
}
