{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "line-chart",
  "title": "Line Chart",
  "description": "One series as a line, with a cursor that snaps to points; a slider for keyboards and screen readers.",
  "registryDependencies": [
    "@corsair-ui/utils"
  ],
  "files": [
    {
      "path": "registry/default/ui/line-chart.tsx",
      "content": "\"use client\";\n\nimport {\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type CSSProperties,\n  type KeyboardEvent,\n  type PointerEvent,\n  type ReactNode,\n} from \"react\";\n\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)\";\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\ninterface LineChartProps extends Omit<ComponentProps<\"div\">, \"children\"> {\n  /** The values to plot, in order. The Y axis fits their range. */\n  data: number[];\n  /** A label per value, shown in the tooltip and along the X axis. */\n  labels?: string[];\n  /** Name of the series, shown in the tooltip and used as the accessible name. */\n  name?: string;\n  /** Line and dot colour; any CSS colour. Defaults to the primary colour. */\n  color?: string;\n  /** How the line runs 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 the value in the tooltip; overrides `locale` and `numberFormat`. */\n  formatValue?: (value: number, index: number) => ReactNode;\n  /** What screen readers hear for a point. Defaults to its label and value. */\n  formatValueText?: (value: number, index: number) => string;\n  /** The point selected at first. Defaults to the last one. */\n  defaultIndex?: number;\n  /** Called when the selected point 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  /** Colour the line only up to the selected point, grey after it. */\n  reveal?: boolean;\n  /** Shade the area under the line. */\n  showFill?: boolean;\n  /** Mark the selected point with a dot. */\n  showDot?: boolean;\n  /** Glide the cursor, dot and tooltip between points. */\n  animated?: boolean;\n}\n\n/**\n * A line chart for one series, with a cursor that snaps to the nearest\n * point and a tooltip beside it. It is a slider over the points for\n * keyboards and screen readers: arrow keys, Home and End move the cursor\n * and each point is announced with its label and value. On touch it follows\n * a horizontal drag and leaves vertical scrolling to the page. No chart\n * library: one SVG, scaled to its container.\n *\n * @example\n * <LineChart\n *   name=\"Knots\"\n *   data={[12, 18, 15, 24, 22, 30]}\n *   labels={[\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"]}\n * />\n */\nfunction LineChart({\n  data,\n  labels,\n  name,\n  color = \"var(--primary)\",\n  curve = \"smooth\",\n  locale = \"en-US\",\n  numberFormat,\n  formatValue,\n  formatValueText,\n  defaultIndex,\n  onIndexChange,\n  showXAxis = true,\n  tickCount = 6,\n  reveal = false,\n  showFill = true,\n  showDot = true,\n  animated = true,\n  className,\n  style,\n  \"aria-label\": ariaLabel,\n  ...props\n}: LineChartProps) {\n  const id = useId().replace(/[^\\w-]/g, \"\");\n  const plot = useRef<HTMLDivElement>(null);\n  const [width, setWidth] = useState(WIDTH);\n  const [active, setActive] = useState(() => defaultIndex ?? Math.max(0, data.length - 1));\n\n  useEffect(() => {\n    const node = plot.current;\n    if (!node || typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(([entry]) => {\n      if (entry?.contentRect.width) setWidth(entry.contentRect.width);\n    });\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, []);\n\n  const points = useMemo(() => {\n    if (data.length === 0) return [];\n    const min = Math.min(...data);\n    const range = Math.max(...data) - min || 1;\n    return data.map((value, index) => ({\n      value,\n      x: data.length === 1 ? WIDTH / 2 : (index / (data.length - 1)) * WIDTH,\n      y: TOP + (1 - (value - min) / range) * (HEIGHT - TOP - BOTTOM),\n    }));\n  }, [data]);\n\n  const numbers = useMemo(\n    () => new Intl.NumberFormat(locale, numberFormat),\n    [locale, numberFormat]\n  );\n\n  const { line, area } = useMemo(() => {\n    if (points.length === 0) return { line: \"\", area: \"\" };\n    const d = curve === \"smooth\" ? smoothPath(points) : linearPath(points);\n    const floor = HEIGHT - BOTTOM;\n    const last = points[points.length - 1]!;\n    return { line: d, area: `${d} L${n(last.x)} ${floor} L${n(points[0]!.x)} ${floor} Z` };\n  }, [points, curve]);\n\n  const ticks = useMemo(() => {\n    if (!showXAxis || !labels?.length || points.length === 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)), points.length);\n    if (most < 1) return [];\n    // Every step-th point, counted back from the latest so it always has a\n    // label, and the smallest step that keeps within `most` labels.\n    const last = points.length - 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, points.length, tickCount, width]);\n\n  if (points.length === 0) return null;\n\n  const index = Math.min(Math.max(active, 0), points.length - 1);\n  const point = points[index]!;\n  const select = (next: number) => {\n    const clamped = Math.min(Math.max(next, 0), points.length - 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 * (points.length - 1)));\n  };\n\n  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    const page = Math.max(1, Math.round(points.length / 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: points.length - 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 formatted = numbers.format(point.value);\n  const valueText =\n    formatValueText?.(point.value, index) ?? `${label ? `${label}: ` : \"\"}${formatted}`;\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 cursorX = cqw(point.x);\n  const cursorY = cqw(point.y);\n  const flip = point.x > WIDTH / 2;\n  const transition = animated ? `transform 220ms ${EASE}` : undefined;\n\n  return (\n    <div\n      data-slot=\"line-chart\"\n      className={cn(\"w-full select-none\", className)}\n      style={{ \"--line-chart-color\": color, ...style } as CSSProperties}\n      {...props}\n    >\n      <div\n        ref={plot}\n        role=\"slider\"\n        tabIndex={0}\n        aria-label={ariaLabel ?? name ?? \"Chart\"}\n        aria-valuemin={1}\n        aria-valuemax={points.length}\n        aria-valuenow={index + 1}\n        aria-valuetext={valueText}\n        aria-orientation=\"horizontal\"\n        data-slot=\"line-chart-plot\"\n        // A size container: the cursor, dot 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            <linearGradient id={`${id}-area`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n              <stop offset=\"0\" stopColor=\"var(--line-chart-color)\" stopOpacity=\"0.22\" />\n              <stop offset=\"1\" stopColor=\"var(--line-chart-color)\" stopOpacity=\"0\" />\n            </linearGradient>\n            <clipPath id={`${id}-reveal`} clipPathUnits=\"userSpaceOnUse\">\n              <rect\n                width={WIDTH}\n                height={HEIGHT}\n                style={{\n                  transform: `scaleX(${point.x / WIDTH})`,\n                  transformOrigin: \"left center\",\n                  transition,\n                }}\n                className=\"motion-reduce:!transition-none\"\n              />\n            </clipPath>\n          </defs>\n          {showFill ? (\n            <path\n              d={area}\n              fill={`url(#${id}-area)`}\n              clipPath={reveal ? `url(#${id}-reveal)` : undefined}\n            />\n          ) : null}\n          {reveal ? (\n            <path\n              d={line}\n              stroke=\"var(--border)\"\n              strokeWidth=\"2\"\n              vectorEffect=\"non-scaling-stroke\"\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n            />\n          ) : null}\n          <path\n            d={line}\n            stroke=\"var(--line-chart-color)\"\n            strokeWidth=\"2\"\n            vectorEffect=\"non-scaling-stroke\"\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            clipPath={reveal ? `url(#${id}-reveal)` : undefined}\n          />\n        </svg>\n\n        <div\n          aria-hidden=\"true\"\n          data-slot=\"line-chart-cursor\"\n          className=\"bg-border pointer-events-none absolute top-[11%] left-0 h-[86%] w-px motion-reduce:!transition-none\"\n          style={{ transform: `translate3d(${cursorX}, 0, 0)`, transition }}\n        />\n        {showDot ? (\n          <div\n            aria-hidden=\"true\"\n            data-slot=\"line-chart-dot\"\n            className=\"pointer-events-none absolute top-0 left-0 -mt-1.5 -ml-1.5 size-3 rounded-full bg-[color:var(--line-chart-color)] shadow-[0_0_0_2px_var(--background)] motion-reduce:!transition-none\"\n            style={{ transform: `translate3d(${cursorX}, ${cursorY}, 0)`, transition }}\n          />\n        ) : null}\n        {/* A zero-size anchor rides on the point; the card hangs off its side. */}\n        <div\n          aria-hidden=\"true\"\n          data-slot=\"line-chart-tooltip-anchor\"\n          className=\"pointer-events-none absolute top-0 left-0 z-10 size-0 motion-reduce:!transition-none\"\n          style={{ transform: `translate3d(${cursorX}, ${cursorY}, 0)`, transition }}\n        >\n          <div\n            data-slot=\"line-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            <div className=\"flex items-center gap-2\">\n              <span className=\"size-2.5 shrink-0 rounded-[3px] bg-[color:var(--line-chart-color)]\" />\n              {name ? <span className=\"text-muted-foreground\">{name}</span> : null}\n              <span className=\"ml-auto font-mono font-medium tabular-nums\">\n                {formatValue ? formatValue(point.value, index) : formatted}\n              </span>\n            </div>\n          </div>\n        </div>\n      </div>\n\n      {ticks.length > 0 ? (\n        <div aria-hidden=\"true\" data-slot=\"line-chart-axis\" className=\"relative mt-2 h-5\">\n          {ticks.map((tick) => {\n            const at = 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    </div>\n  );\n}\n\nexport { LineChart, type LineChartProps };\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}