{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "line-chart",
  "type": "registry:component",
  "title": "Line Chart",
  "description": "A line chart of one or more series over a numeric or time x, with a crosshair tooltip, arrow-key reading and labels at the line ends.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-scale",
    "d3-shape"
  ],
  "devDependencies": [
    "@types/d3-scale",
    "@types/d3-shape"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/line-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/line-chart.tsx",
      "content": "\"use client\";\n/**\n * @name line-chart\n * @category viz\n * @description A line chart of one or more series over a numeric or time x, with a crosshair tooltip, arrow-key reading and labels at the line ends.\n * @when Change over time or along a number, for up to about five series on one shared scale. For a single series whose volume matters use area-chart; for separate categories use bar-chart; never plot two different units against two y axes, use two charts.\n * @example\n * <LineChart\n *   label=\"Requests and errors per day\"\n *   data={[\n *     { day: new Date(\"2026-03-01\"), requests: 120, errors: 4 },\n *     { day: new Date(\"2026-03-02\"), requests: 180, errors: 9 },\n *     { day: new Date(\"2026-03-03\"), requests: 150, errors: 3 },\n *   ]}\n *   x=\"day\"\n *   series={[\n *     { key: \"requests\", label: \"Requests\" },\n *     { key: \"errors\", label: \"Errors\" },\n *   ]}\n * />\n */\nimport { scaleLinear, scaleUtc } from \"d3-scale\";\nimport { area as areaShape, curveLinear, curveMonotoneX, curveStep, line as lineShape } from \"d3-shape\";\nimport { useMemo, useState, type ComponentProps, type KeyboardEvent, type PointerEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  axisNumberFormatter,\n  ChartAxis,\n  ChartContainer,\n  ChartGrid,\n  ChartLegend,\n  ChartMark,\n  chartSeries,\n  ChartSvg,\n  ChartTooltip,\n  dateFormatter,\n  estimateTextWidth,\n  formatNumber,\n  readNumber,\n  type ChartFormat,\n  type ChartSeries,\n} from \"@/components/viz/chart\";\n\nexport type LineChartProps<T extends object> = Omit<ComponentProps<\"div\">, \"children\"> &\n  ChartFormat & {\n    /** One object per x position. */\n    data: readonly T[];\n    /** The field that holds x: a number or a Date. */\n    x: keyof T & string;\n    /** The lines, in a fixed order: the first takes the highlight colour. */\n    series: readonly ChartSeries<T>[];\n    /** What the chart shows, for assistive technology. */\n    label: string;\n    /** How points are joined. \"monotone\" smooths without overshooting the data. */\n    curve?: \"linear\" | \"monotone\" | \"step\";\n    showGrid?: boolean;\n    /** A marker on every point, when there is room for them. */\n    showDots?: boolean;\n    /** Default: shown for two or more series. One series is named by the chart's title. */\n    showLegend?: boolean;\n    /** Name each line at its end when there are at most four and there is room. */\n    endLabels?: boolean;\n    /** Start the y axis at zero. Default false for lines, always true for areas. */\n    zero?: boolean;\n    /** The name of the x column in the table alternative. Default: the `x` field name. */\n    xLabel?: string;\n    /** Replaces the x format on the axis, in the tooltip and in the table. */\n    formatX?: (value: number | Date) => string;\n    /** Width / height of the plot. */\n    aspect?: number;\n    /** A fixed plot height in pixels instead of a ratio. */\n    height?: number;\n  };\n\nexport type SeriesChartProps<T extends object> = LineChartProps<T> & {\n  /** Fill under each line with the series colour at low opacity. */\n  area?: boolean;\n  /** Stack the series on top of each other (areas only). */\n  stacked?: boolean;\n  /** The root's data-slot. */\n  slot?: string;\n};\n\nconst CURVES = { linear: curveLinear, monotone: curveMonotoneX, step: curveStep };\nconst TOP = 10;\nconst BOTTOM = 26;\n\n/** The engine behind line-chart and area-chart. Use those; this is exported so they can share it. */\nexport function SeriesChart<T extends object>({\n  data,\n  x,\n  series,\n  label,\n  curve = \"linear\",\n  showGrid = true,\n  showDots = false,\n  showLegend,\n  endLabels = true,\n  zero,\n  xLabel,\n  formatX,\n  aspect,\n  height,\n  locale,\n  timeZone,\n  formatValue,\n  area = false,\n  stacked = false,\n  slot = \"line-chart\",\n  className,\n  ...props\n}: SeriesChartProps<T>) {\n  const [active, setActive] = useState<number | null>(null);\n  const [keyboard, setKeyboard] = useState(false);\n  const stack = area && stacked;\n  const fromZero = area || zero === true;\n\n  const model = useMemo(() => {\n    const isTime = data.some((row) => (row as Record<string, unknown>)[x] instanceof Date);\n    const rows = data\n      .map((row) => {\n        const raw = (row as Record<string, unknown>)[x];\n        return { row, x: raw instanceof Date ? raw.getTime() : typeof raw === \"number\" ? raw : Number.NaN };\n      })\n      .filter((entry) => Number.isFinite(entry.x))\n      .sort((a, b) => a.x - b.x);\n    const xs = rows.map((entry) => entry.x);\n    const values = series.map((item) => rows.map((entry) => readNumber(entry.row, item.key)));\n    // Where each series is drawn: its own value, or its value on top of the series before it.\n    const base = values.map((list) => list.map(() => 0));\n    const tops = values.map((list) => list.map((value) => value ?? 0));\n    if (stack) {\n      for (let s = 1; s < values.length; s += 1) {\n        for (let i = 0; i < xs.length; i += 1) {\n          base[s]![i] = tops[s - 1]?.[i] ?? 0;\n          tops[s]![i] = (base[s]?.[i] ?? 0) + (values[s]?.[i] ?? 0);\n        }\n      }\n    }\n    let low = Infinity;\n    let high = -Infinity;\n    values.forEach((list, s) =>\n      list.forEach((value, i) => {\n        if (value === null && !stack) return;\n        const top = tops[s]?.[i] ?? 0;\n        low = Math.min(low, top);\n        high = Math.max(high, top);\n      }),\n    );\n    if (low === Infinity) {\n      low = 0;\n      high = 1;\n    }\n    return { isTime, rows, xs, values, base, tops, low, high };\n  }, [data, x, series, stack]);\n\n  const { isTime, xs, values, base, tops } = model;\n  const count = xs.length;\n  const span = count > 0 ? (xs[count - 1] ?? 0) - (xs[0] ?? 0) : 0;\n  const value = formatValue ?? ((number: number) => formatNumber(number, locale));\n  const plainX = (number: number): string => formatNumber(number, locale, { useGrouping: false, maximumFractionDigits: 2 });\n  const xText = (number: number, detail: \"axis\" | \"full\"): string =>\n    formatX ? formatX(isTime ? new Date(number) : number) : isTime ? dateFormatter(span, detail, locale, timeZone)(number) : plainX(number);\n\n  const table = {\n    caption: label,\n    columns: [xLabel ?? x, ...series.map((item) => item.label)],\n    rows: xs.map((position, i) => [xText(position, \"full\"), ...values.map((list) => (list[i] === null || list[i] === undefined ? \"\" : value(list[i] as number)))]),\n  };\n\n  const tooltipRows =\n    active === null\n      ? []\n      : series.flatMap((item, s) => {\n          const number = values[s]?.[active];\n          return number === null || number === undefined ? [] : [{ label: item.label, value: value(number), index: s, mark: area ? (\"rect\" as const) : (\"line\" as const) }];\n        });\n  const title = active === null ? \"\" : xText(xs[active] ?? 0, \"full\");\n  const announcement = keyboard && active !== null ? `${title}: ${tooltipRows.map((row) => `${row.label} ${row.value}`).join(\", \")}` : \"\";\n\n  const move = (step: number | \"first\" | \"last\"): void => {\n    if (count === 0) return;\n    setKeyboard(true);\n    setActive((current) => {\n      if (step === \"first\") return 0;\n      if (step === \"last\") return count - 1;\n      if (current === null) return step > 0 ? 0 : count - 1;\n      return Math.max(0, Math.min(count - 1, current + step));\n    });\n  };\n  const onKeyDown = (event: KeyboardEvent<SVGSVGElement>): void => {\n    if (event.key === \"ArrowRight\" || event.key === \"ArrowUp\") move(1);\n    else if (event.key === \"ArrowLeft\" || event.key === \"ArrowDown\") move(-1);\n    else if (event.key === \"Home\") move(\"first\");\n    else if (event.key === \"End\") move(\"last\");\n    else if (event.key === \"Escape\") setActive(null);\n    else return;\n    event.preventDefault();\n  };\n\n  const legend = showLegend ?? series.length > 1;\n\n  return (\n    <div data-slot={slot} className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      {legend ? <ChartLegend items={series.map((item, index) => ({ label: item.label, index }))} mark={area ? \"rect\" : \"line\"} /> : null}\n      <ChartContainer aspect={aspect} height={height} table={table} announcement={announcement}>\n        {(size) => {\n          if (count === 0) {\n            return <p className=\"absolute inset-0 flex items-center justify-center text-sm text-muted-foreground\">No data</p>;\n          }\n          const low = fromZero ? Math.min(0, model.low) : model.low;\n          const high = fromZero ? Math.max(0, model.high) : model.high;\n          const yScale = scaleLinear()\n            .domain(low === high ? [low - 1, high + 1] : [low, high])\n            .nice(Math.max(2, Math.floor(size.height / 56)))\n            .range([size.height - BOTTOM, TOP]);\n          const yTicks = yScale.ticks(Math.max(2, Math.floor(size.height / 56)));\n          const axisValue = formatValue ?? axisNumberFormatter(Math.max(Math.abs(yScale.domain()[0] ?? 0), Math.abs(yScale.domain()[1] ?? 0)), locale);\n          const left = Math.ceil(Math.max(...yTicks.map((tick) => estimateTextWidth(axisValue(tick))))) + 10;\n          const labelled = endLabels && series.length <= 4 && size.width >= 420;\n          const right = labelled ? Math.min(size.width * 0.3, Math.ceil(Math.max(...series.map((item) => estimateTextWidth(item.label)))) + 16) : 12;\n          const first = xs[0] ?? 0;\n          const last = xs[count - 1] ?? 0;\n          const xScale = scaleLinear()\n            .domain(first === last ? [first - 1, last + 1] : [first, last])\n            .range([left, size.width - right]);\n          const plotWidth = size.width - right - left;\n          const tickCount = Math.max(2, Math.floor(plotWidth / 90));\n          const xTicks = (\n            isTime\n              ? scaleUtc()\n                  .domain([new Date(first), new Date(last)])\n                  .ticks(tickCount)\n                  .map((date) => date.getTime())\n              : xScale.ticks(tickCount)\n          ).filter((tick) => tick >= first && tick <= last);\n          const px = (i: number): number => xScale(xs[i] ?? 0);\n          const py = (s: number, i: number): number => yScale(tops[s]?.[i] ?? 0);\n          const defined = (s: number) => (i: number): boolean => stack || (values[s]?.[i] ?? null) !== null;\n          const indices = xs.map((_, i) => i);\n          const factory = CURVES[curve];\n\n          // The last drawn point of each line: where its marker and its name go.\n          const ends = series.map((item, s) => {\n            let i = count - 1;\n            while (i >= 0 && !defined(s)(i)) i -= 1;\n            return i < 0 ? null : { s, x: px(i), y: py(s, i), label: item.label };\n          });\n          const placed = ends.filter((end) => end !== null).sort((a, b) => a.y - b.y);\n          // Names that would collide are not nudged apart (that detaches them from their lines): the legend carries them.\n          const roomForNames = labelled && placed.every((end, index) => index === 0 || end.y - (placed[index - 1]?.y ?? 0) >= 14);\n          const dots = showDots && plotWidth / count >= 12;\n          const zeroLine = (yScale.domain()[0] ?? 0) <= 0 && (yScale.domain()[1] ?? 0) >= 0 ? yScale(0) : null;\n          const activeX = active === null ? 0 : px(active);\n\n          const onPointerMove = (event: PointerEvent<SVGSVGElement>): void => {\n            const pointer = event.clientX - event.currentTarget.getBoundingClientRect().left;\n            // The crosshair finds the x: the nearest position, wherever the pointer is vertically.\n            let nearest = 0;\n            for (let i = 1; i < count; i += 1) {\n              if (Math.abs(px(i) - pointer) < Math.abs(px(nearest) - pointer)) nearest = i;\n            }\n            setKeyboard(false);\n            setActive(nearest);\n          };\n\n          return (\n            <>\n              <ChartSvg\n                label={label}\n                width={size.width}\n                height={size.height}\n                interactive\n                onKeyDown={onKeyDown}\n                onPointerMove={onPointerMove}\n                onPointerLeave={() => setActive(null)}\n                onFocus={(event) => {\n                  if (event.currentTarget.matches(\":focus-visible\")) move(\"last\");\n                }}\n                onBlur={() => setActive(null)}\n              >\n                {showGrid ? <ChartGrid offsets={yTicks.map((tick) => yScale(tick))} from={left} to={size.width - right} /> : null}\n                {zeroLine === null ? null : <line aria-hidden=\"true\" x1={left} x2={size.width - right} y1={zeroLine} y2={zeroLine} className=\"stroke-border-strong\" strokeWidth={1} shapeRendering=\"crispEdges\" />}\n                <ChartAxis side=\"left\" at={left - 8} ticks={yTicks.map((tick) => ({ offset: yScale(tick), label: axisValue(tick) }))} />\n                <ChartAxis side=\"bottom\" at={size.height - BOTTOM + 8} ticks={xTicks.map((tick) => ({ offset: xScale(tick), label: xText(tick, \"axis\") }))} />\n                <g aria-hidden=\"true\">\n                  {area\n                    ? series.map((item, s) => (\n                        <path\n                          key={item.key}\n                          d={\n                            areaShape<number>()\n                              .defined(defined(s))\n                              .x(px)\n                              .y0((i) => yScale(base[s]?.[i] ?? 0))\n                              .y1((i) => py(s, i))\n                              .curve(factory)(indices) ?? undefined\n                          }\n                          className={chartSeries(s).fill}\n                          // Flat: the series colour as a light wash, no gradient.\n                          fillOpacity={stack ? 0.28 : 0.12}\n                        />\n                      ))\n                    : null}\n                  {series.map((item, s) => (\n                    <path\n                      key={item.key}\n                      d={lineShape<number>().defined(defined(s)).x(px).y((i) => py(s, i)).curve(factory)(indices) ?? undefined}\n                      fill=\"none\"\n                      className={chartSeries(s).stroke}\n                      strokeWidth={2}\n                      strokeLinejoin=\"round\"\n                      strokeLinecap=\"round\"\n                      strokeDasharray={chartSeries(s).dash}\n                    />\n                  ))}\n                  {dots ? series.map((item, s) => indices.filter(defined(s)).map((i) => <ChartMark key={`${item.key}:${i}`} index={s} x={px(i)} y={py(s, i)} radius={3} />)) : null}\n                  {ends.map((end) => (end === null ? null : <ChartMark key={end.s} index={end.s} x={end.x} y={end.y} radius={4} />))}\n                  {roomForNames\n                    ? placed.map((end) => (\n                        <text key={end.s} x={end.x + 10} y={end.y} dy=\"0.32em\" className=\"fill-muted-foreground\">\n                          {end.label}\n                        </text>\n                      ))\n                    : null}\n                  {active === null ? null : (\n                    <>\n                      <line x1={activeX} x2={activeX} y1={TOP} y2={size.height - BOTTOM} className=\"stroke-border-strong\" strokeWidth={1} shapeRendering=\"crispEdges\" />\n                      {series.map((item, s) => (defined(s)(active) ? <ChartMark key={item.key} index={s} x={activeX} y={py(s, active)} radius={5} /> : null))}\n                    </>\n                  )}\n                </g>\n              </ChartSvg>\n              {active === null ? null : <ChartTooltip x={activeX} y={TOP} align=\"top\" side={activeX > size.width / 2 ? \"left\" : \"right\"} title={title} rows={tooltipRows} />}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n\nexport function LineChart<T extends object>(props: LineChartProps<T>) {\n  return <SeriesChart {...props} slot=\"line-chart\" />;\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Change over time or along a number, for up to about five series on one shared scale. For a single series whose volume matters use area-chart; for separate categories use bar-chart; never plot two different units against two y axes, use two charts.",
    "example": "<LineChart\n  label=\"Requests and errors per day\"\n  data={[\n    { day: new Date(\"2026-03-01\"), requests: 120, errors: 4 },\n    { day: new Date(\"2026-03-02\"), requests: 180, errors: 9 },\n    { day: new Date(\"2026-03-03\"), requests: 150, errors: 3 },\n  ]}\n  x=\"day\"\n  series={[\n    { key: \"requests\", label: \"Requests\" },\n    { key: \"errors\", label: \"Errors\" },\n  ]}\n/>",
    "client": true
  }
}
