{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "area-chart",
  "title": "Area Chart",
  "description": "One or more series as gradient-filled areas, stacked or overlapping, with a legend and a keyboard slider over the points.",
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/use-entrance"
  ],
  "files": [
    {
      "path": "registry/default/ui/area-chart.tsx",
      "content": "\"use client\";\n\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useMemo,\n  useState,\n  type ComponentProps,\n  type KeyboardEvent,\n  type PointerEvent,\n  type ReactNode,\n} from \"react\";\n\nimport { useEntrance } from \"@/registry/default/hooks/use-entrance\";\nimport { cn } from \"@/registry/default/lib/utils\";\n\n// The drawing is laid out in a fixed box and scaled to its container.\nconst WIDTH = 600;\nconst HEIGHT = 200;\nconst TOP = 22;\nconst BOTTOM = 10;\nconst EASE = \"cubic-bezier(0.22, 0.9, 0.3, 1)\";\nconst DRAW = \"cubic-bezier(0.65, 0, 0.35, 1)\";\n\ninterface Point {\n  x: number;\n  y: number;\n}\n\nconst n = (value: number) => Math.round(value * 100) / 100;\n/** A length in the drawing's units as a share of the plot's width. */\nconst cqw = (value: number) => `${n((value / WIDTH) * 100)}cqw`;\n\n/** Straight segments; the stroke's round joins soften the corners. */\nfunction linearPath(points: Point[]) {\n  return points.map((point, index) => `${index ? \"L\" : \"M\"}${n(point.x)} ${n(point.y)}`).join(\" \");\n}\n\n/**\n * A smooth curve through every point that never overshoots them\n * (monotone cubic interpolation), so peaks in the drawing are peaks in the data.\n */\nfunction smoothPath(points: Point[]) {\n  if (points.length < 3) return linearPath(points);\n  const slopes = points\n    .slice(1)\n    .map((point, index) => (point.y - points[index]!.y) / (point.x - points[index]!.x || 1));\n  const tangents = points.map((_, index) => {\n    if (index === 0) return slopes[0]!;\n    if (index === points.length - 1) return slopes[slopes.length - 1]!;\n    const before = slopes[index - 1]!;\n    const after = slopes[index]!;\n    return before * after <= 0 ? 0 : (before + after) / 2;\n  });\n  slopes.forEach((slope, index) => {\n    if (slope === 0) {\n      tangents[index] = 0;\n      tangents[index + 1] = 0;\n      return;\n    }\n    const a = tangents[index]! / slope;\n    const b = tangents[index + 1]! / slope;\n    const size = a * a + b * b;\n    if (size > 9) {\n      const scale = 3 / Math.sqrt(size);\n      tangents[index] = scale * a * slope;\n      tangents[index + 1] = scale * b * slope;\n    }\n  });\n  let d = `M${n(points[0]!.x)} ${n(points[0]!.y)}`;\n  for (let index = 0; index < points.length - 1; index++) {\n    const from = points[index]!;\n    const to = points[index + 1]!;\n    const third = (to.x - from.x) / 3;\n    d += ` C${n(from.x + third)} ${n(from.y + tangents[index]! * third)} ${n(to.x - third)} ${n(to.y - tangents[index + 1]! * third)} ${n(to.x)} ${n(to.y)}`;\n  }\n  return d;\n}\n\n/**\n * The default colour of series `index` out of `count`: the primary colour\n * for the first, then the primary colour mixed with the background, lighter\n * for each series down to 40%.\n */\nfunction defaultColor(index: number, count: number) {\n  if (index === 0) return \"var(--primary)\";\n  const share = Math.round(100 - (index / Math.max(count - 1, 1)) * 60);\n  return `color-mix(in oklab, var(--primary) ${share}%, var(--background))`;\n}\n\ninterface AreaChartSeries {\n  /** Shown in the legend and the tooltip, and read out by screen readers. */\n  name: string;\n  /** One value per label. Missing values count as 0. */\n  data: number[];\n  /** Line and fill colour; any CSS colour. See `AreaChart` for the defaults. */\n  color?: string;\n}\n\ninterface AreaChartProps extends Omit<ComponentProps<\"div\">, \"children\"> {\n  /** The series to plot, drawn in order: later series sit on top (or, stacked, above). */\n  series: AreaChartSeries[];\n  /** A label per position, shown in the tooltip and along the X axis. */\n  labels?: string[];\n  /** Accessible name of the chart. Defaults to the series names. */\n  name?: string;\n  /** Stack the series on top of each other instead of overlapping them. */\n  stacked?: boolean;\n  /** How the lines run between points. */\n  curve?: \"smooth\" | \"linear\";\n  /**\n   * Locale and options for the numbers, as in `Intl.NumberFormat`. Both can\n   * be passed from a server component; a fixed default keeps the server and\n   * the browser in agreement.\n   */\n  locale?: string;\n  numberFormat?: Intl.NumberFormatOptions;\n  /** Formats a value in the tooltip; overrides `locale` and `numberFormat`. */\n  formatValue?: (value: number, index: number, series: number) => ReactNode;\n  /**\n   * What screen readers hear for a position, given every series' value\n   * there. Defaults to the label, then each series' name and value.\n   */\n  formatValueText?: (values: number[], index: number) => string;\n  /** The position selected at first. Defaults to the last one. */\n  defaultIndex?: number;\n  /** Called when the selected position changes, by pointer or keyboard. */\n  onIndexChange?: (index: number) => void;\n  /** Show labels along the X axis. Needs `labels`. */\n  showXAxis?: boolean;\n  /**\n   * The most X axis labels to show, evenly spaced and ending on the latest\n   * point; narrow charts show fewer.\n   */\n  tickCount?: number;\n  /** Show a legend under the chart. Defaults to true when there is more than one series. */\n  showLegend?: boolean;\n  /** Mark each series at the selected position with a dot. */\n  showDot?: boolean;\n  /** Draw the areas in from the left the first time they come into view, and glide the cursor. */\n  animated?: boolean;\n}\n\n/**\n * An area chart for one or more series, overlapping or stacked, each filled\n * with a gradient from its colour to transparent. A cursor snaps to the\n * nearest position and a tooltip lists every series there. It is a slider\n * over the positions for keyboards and screen readers: arrow keys, Page Up /\n * Page Down, Home and End move the cursor and each position is announced\n * with its label and every series' value; the drawing itself is hidden from\n * assistive technology and the legend is a plain list. The areas draw in\n * from the left the first time they scroll into view; with\n * `prefers-reduced-motion` they are simply shown.\n *\n * Series without a `color` get the primary colour, then lighter mixes of\n * it with the background, so the chart follows the theme; pass colours to\n * tell many series apart.\n *\n * @example\n * <AreaChart\n *   labels={[\"Jan\", \"Feb\", \"Mar\", \"Apr\"]}\n *   series={[\n *     { name: \"Cargo\", data: [40, 52, 48, 61] },\n *     { name: \"Crew\", data: [20, 24, 22, 30] },\n *   ]}\n *   stacked\n * />\n */\nfunction AreaChart({\n  series,\n  labels,\n  name,\n  stacked = false,\n  curve = \"smooth\",\n  locale = \"en-US\",\n  numberFormat,\n  formatValue,\n  formatValueText,\n  defaultIndex,\n  onIndexChange,\n  showXAxis = true,\n  tickCount = 6,\n  showLegend = series.length > 1,\n  showDot = true,\n  animated = true,\n  className,\n  style,\n  \"aria-label\": ariaLabel,\n  ...props\n}: AreaChartProps) {\n  const id = useId().replace(/[^\\w-]/g, \"\");\n  const count = Math.max(0, ...series.map((item) => item.data.length));\n  const [plot, setPlot] = useState<HTMLDivElement | null>(null);\n  const [width, setWidth] = useState(WIDTH);\n  const [active, setActive] = useState(() => defaultIndex ?? Math.max(0, count - 1));\n  const [observe, phase] = useEntrance<HTMLDivElement>({ play: animated ? undefined : true });\n  const entrance = animated ? phase : \"static\";\n\n  const plotRef = useCallback(\n    (node: HTMLDivElement | null) => {\n      setPlot(node);\n      observe(node);\n    },\n    [observe]\n  );\n\n  useEffect(() => {\n    if (!plot || typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(([entry]) => {\n      if (entry?.contentRect.width) setWidth(entry.contentRect.width);\n    });\n    observer.observe(plot);\n    return () => observer.disconnect();\n  }, [plot]);\n\n  const layers = useMemo(() => {\n    if (count === 0) return [];\n    const xs = Array.from({ length: count }, (_, index) =>\n      count === 1 ? WIDTH / 2 : (index / (count - 1)) * WIDTH\n    );\n    const values = series.map((item) => xs.map((_, index) => item.data[index] ?? 0));\n    // Stacked series sit on the running total of the ones before them.\n    const tops = stacked\n      ? values.map((_, layer) =>\n          xs.map((_, index) =>\n            values.slice(0, layer + 1).reduce((sum, row) => sum + row[index]!, 0)\n          )\n        )\n      : values;\n    const all = tops.flat();\n    const min = Math.min(0, ...all);\n    const range = Math.max(0, ...all) - min || 1;\n    const y = (value: number) => TOP + (1 - (value - min) / range) * (HEIGHT - TOP - BOTTOM);\n    const path = curve === \"smooth\" ? smoothPath : linearPath;\n    const zero = y(0);\n    return series.map((item, layer) => {\n      const points = xs.map((x, index) => ({ x, y: y(tops[layer]![index]!) }));\n      const line = path(points);\n      const below =\n        stacked && layer > 0\n          ? path(xs.map((x, index) => ({ x, y: y(tops[layer - 1]![index]!) })).reverse()).replace(\n              /^M/,\n              \"L\"\n            )\n          : `L${n(points[points.length - 1]!.x)} ${n(zero)} L${n(points[0]!.x)} ${n(zero)}`;\n      return {\n        name: item.name,\n        color: item.color ?? defaultColor(layer, series.length),\n        values: values[layer]!,\n        points,\n        line,\n        area: `${line} ${below} Z`,\n      };\n    });\n  }, [series, count, stacked, curve]);\n\n  const numbers = useMemo(\n    () => new Intl.NumberFormat(locale, numberFormat),\n    [locale, numberFormat]\n  );\n\n  const ticks = useMemo(() => {\n    if (!showXAxis || !labels?.length || count === 0) return [];\n    // At most one label per 80px, so they never run into each other.\n    const most = Math.min(tickCount, Math.max(2, Math.floor(width / 80)), count);\n    if (most < 1) return [];\n    const last = count - 1;\n    const step = Math.floor(last / most) + 1;\n    return Array.from(\n      { length: Math.floor(last / step) + 1 },\n      (_, tick) => (last % step) + tick * step\n    );\n  }, [showXAxis, labels, count, tickCount, width]);\n\n  if (layers.length === 0) return null;\n\n  const index = Math.min(Math.max(active, 0), count - 1);\n  const select = (next: number) => {\n    const clamped = Math.min(Math.max(next, 0), count - 1);\n    if (clamped === index) return;\n    setActive(clamped);\n    onIndexChange?.(clamped);\n  };\n\n  const onPointer = (event: PointerEvent<HTMLDivElement>) => {\n    const box = event.currentTarget.getBoundingClientRect();\n    if (box.width === 0) return;\n    const at = (event.clientX - box.left) / box.width;\n    select(Math.round(at * (count - 1)));\n  };\n\n  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    const page = Math.max(1, Math.round(count / 10));\n    const moves: Record<string, number> = {\n      ArrowLeft: index - 1,\n      ArrowDown: index - 1,\n      ArrowRight: index + 1,\n      ArrowUp: index + 1,\n      PageDown: index - page,\n      PageUp: index + page,\n      Home: 0,\n      End: count - 1,\n    };\n    const next = moves[event.key];\n    if (next === undefined) return;\n    event.preventDefault();\n    select(next);\n  };\n\n  const label = labels?.[index];\n  const current = layers.map((layer) => layer.values[index]!);\n  const valueText =\n    formatValueText?.(current, index) ??\n    `${label ? `${label}: ` : \"\"}${layers\n      .map((layer, at) => `${layer.name} ${numbers.format(current[at]!)}`)\n      .join(\", \")}`;\n\n  // Positions for transforms, so they move on the compositor. In container\n  // units of the plot (its width is 100cqw, its height a third of that), so\n  // they are right before the plot is measured too: the server render and the\n  // first paint place nothing past the plot's edge, which on a phone would\n  // widen the page.\n  const x = layers[0]!.points[index]!.x;\n  const cursorX = cqw(x);\n  const highest = Math.min(...layers.map((layer) => layer.points[index]!.y));\n  const flip = x > WIDTH / 2;\n  const transition = animated ? `transform 220ms ${EASE}` : undefined;\n  const hidden = entrance === \"armed\" && \"opacity-0\";\n\n  return (\n    <div\n      data-slot=\"area-chart\"\n      data-stacked={stacked ? \"\" : undefined}\n      className={cn(\"w-full select-none\", className)}\n      style={style}\n      {...props}\n    >\n      <div\n        ref={plotRef}\n        role=\"slider\"\n        tabIndex={0}\n        aria-label={ariaLabel ?? name ?? layers.map((layer) => layer.name).join(\", \")}\n        aria-valuemin={1}\n        aria-valuemax={count}\n        aria-valuenow={index + 1}\n        aria-valuetext={valueText}\n        aria-orientation=\"horizontal\"\n        data-slot=\"area-chart-plot\"\n        data-state={entrance}\n        // A size container: the cursor, dots and tooltip are placed in its cqw.\n        className=\"focus-visible:ring-ring/50 [container-type:inline-size] relative aspect-[3/1] w-full touch-pan-y rounded-md outline-none focus-visible:ring-[3px]\"\n        onPointerMove={onPointer}\n        onPointerDown={onPointer}\n        onKeyDown={onKeyDown}\n      >\n        <svg\n          aria-hidden=\"true\"\n          viewBox={`0 0 ${WIDTH} ${HEIGHT}`}\n          preserveAspectRatio=\"none\"\n          className=\"absolute inset-0 size-full overflow-visible\"\n          fill=\"none\"\n        >\n          <defs>\n            {layers.map((layer, at) => (\n              <linearGradient key={at} id={`${id}-fill-${at}`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                <stop offset=\"0\" stopColor={layer.color} stopOpacity=\"0.3\" />\n                <stop offset=\"1\" stopColor={layer.color} stopOpacity=\"0\" />\n              </linearGradient>\n            ))}\n            <clipPath id={`${id}-draw`} clipPathUnits=\"userSpaceOnUse\">\n              {/* Wider than the box so round line caps at the edges are not cut. */}\n              <rect\n                x={-8}\n                y={-8}\n                width={WIDTH + 16}\n                height={HEIGHT + 16}\n                className=\"motion-reduce:![transform:none] motion-reduce:!transition-none\"\n                style={{\n                  transformBox: \"view-box\",\n                  transformOrigin: \"0 0\",\n                  transform: entrance === \"armed\" ? \"scaleX(0)\" : undefined,\n                  transition: entrance === \"play\" ? `transform 900ms ${DRAW}` : undefined,\n                }}\n              />\n            </clipPath>\n          </defs>\n          <g clipPath={`url(#${id}-draw)`}>\n            {layers.map((layer, at) => (\n              <path\n                key={`area-${at}`}\n                data-slot=\"area-chart-area\"\n                d={layer.area}\n                fill={`url(#${id}-fill-${at})`}\n              />\n            ))}\n            {layers.map((layer, at) => (\n              <path\n                key={`line-${at}`}\n                data-slot=\"area-chart-line\"\n                d={layer.line}\n                stroke={layer.color}\n                strokeWidth=\"2\"\n                vectorEffect=\"non-scaling-stroke\"\n                strokeLinecap=\"round\"\n                strokeLinejoin=\"round\"\n              />\n            ))}\n          </g>\n        </svg>\n\n        <div\n          aria-hidden=\"true\"\n          data-slot=\"area-chart-cursor\"\n          className={cn(\n            \"bg-border pointer-events-none absolute top-[11%] left-0 h-[86%] w-px motion-reduce:!transition-none\",\n            hidden\n          )}\n          style={{ transform: `translate3d(${cursorX}, 0, 0)`, transition }}\n        />\n        {showDot\n          ? layers.map((layer, at) => (\n              <div\n                key={at}\n                aria-hidden=\"true\"\n                data-slot=\"area-chart-dot\"\n                className={cn(\n                  \"pointer-events-none absolute top-0 left-0 -mt-1.5 -ml-1.5 size-3 rounded-full shadow-[0_0_0_2px_var(--background)] motion-reduce:!transition-none\",\n                  hidden\n                )}\n                style={{\n                  backgroundColor: layer.color,\n                  transform: `translate3d(${cursorX}, ${cqw(layer.points[index]!.y)}, 0)`,\n                  transition,\n                }}\n              />\n            ))\n          : null}\n        {/* A zero-size anchor rides on the highest point; the card hangs off its side. */}\n        <div\n          aria-hidden=\"true\"\n          data-slot=\"area-chart-tooltip-anchor\"\n          className={cn(\n            \"pointer-events-none absolute top-0 left-0 z-10 size-0 motion-reduce:!transition-none\",\n            hidden\n          )}\n          style={{\n            transform: `translate3d(${cursorX}, ${cqw(highest)}, 0)`,\n            transition,\n          }}\n        >\n          <div\n            data-slot=\"area-chart-tooltip\"\n            className={cn(\n              \"bg-popover text-popover-foreground absolute top-0 grid w-max min-w-32 -translate-y-1/2 gap-1.5 rounded-md border px-2.5 py-1.5 text-xs shadow-md\",\n              flip ? \"right-3\" : \"left-3\"\n            )}\n          >\n            {label ? <div className=\"font-medium\">{label}</div> : null}\n            {layers.map((layer, at) => (\n              <div key={at} className=\"flex items-center gap-2\">\n                <span\n                  className=\"size-2.5 shrink-0 rounded-[3px]\"\n                  style={{ backgroundColor: layer.color }}\n                />\n                <span className=\"text-muted-foreground\">{layer.name}</span>\n                <span className=\"ml-auto pl-2 font-mono font-medium tabular-nums\">\n                  {formatValue\n                    ? formatValue(current[at]!, index, at)\n                    : numbers.format(current[at]!)}\n                </span>\n              </div>\n            ))}\n          </div>\n        </div>\n      </div>\n\n      {ticks.length > 0 ? (\n        <div aria-hidden=\"true\" data-slot=\"area-chart-axis\" className=\"relative mt-2 h-5\">\n          {ticks.map((tick) => {\n            const at = layers[0]!.points[tick]!.x / WIDTH;\n            return (\n              <span\n                key={tick}\n                className={cn(\n                  \"text-muted-foreground absolute top-0 text-[11px] leading-none whitespace-nowrap tabular-nums\",\n                  // Labels near an edge line up with it instead of spilling past.\n                  at < 0.1 ? \"translate-x-0\" : at > 0.9 ? \"-translate-x-full\" : \"-translate-x-1/2\"\n                )}\n                style={{ left: `${at * 100}%` }}\n              >\n                {labels?.[tick]}\n              </span>\n            );\n          })}\n        </div>\n      ) : null}\n\n      {showLegend ? (\n        <ul\n          data-slot=\"area-chart-legend\"\n          className=\"mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs\"\n        >\n          {layers.map((layer, at) => (\n            <li key={at} data-slot=\"area-chart-legend-item\" className=\"flex items-center gap-1.5\">\n              <span\n                aria-hidden=\"true\"\n                className=\"size-2.5 shrink-0 rounded-[3px]\"\n                style={{ backgroundColor: layer.color }}\n              />\n              <span className=\"text-muted-foreground\">{layer.name}</span>\n            </li>\n          ))}\n        </ul>\n      ) : null}\n    </div>\n  );\n}\n\nexport { AreaChart, type AreaChartProps, type AreaChartSeries };\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}