{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "line-chart",
  "title": "Line chart",
  "author": "superzero11 <https://github.com/superzero11/uiset>",
  "description": "Trends over time: one or more lines, a soft area for one series, or stacked areas, with a crosshair that lists every series and labels at line ends.",
  "dependencies": [
    "@ui-sdk/core@0.1.0-beta.5",
    "@ui-sdk/react@0.1.0-beta.5"
  ],
  "registryDependencies": [
    "https://uiset.dev/r/uiset.json",
    "https://uiset.dev/r/chart.json"
  ],
  "files": [
    {
      "path": "registry/uiset/ui/line-chart.tsx",
      "content": "\"use client\"\n\nimport type { ChartSelectChange } from \"./chart/points\"\nimport type { ReactNode } from \"react\"\nimport { ChartFrame, reactPlot } from \"./chart\"\nimport { lineFrame, linePlot, type LineOptions } from \"./chart/plots/line\"\n\ntype LineChartProps<Datum> = LineOptions<Datum> & {\n  title: string\n  description?: ReactNode\n  height?: number\n  selected?: string | null\n  onSelect?: (key: string | null, details: ChartSelectChange) => void\n  actions?: ReactNode\n  className?: string\n}\n\n/** Lines, areas or stacks over evenly spaced x positions. The geometry is chart/plots/line.ts. */\nfunction LineChart<Datum>({ title, description, height = 240, selected, onSelect, actions, className, ...options }: LineChartProps<Datum>) {\n  const frame = lineFrame(options)\n  return (\n    <ChartFrame\n      title={title}\n      description={description}\n      height={height}\n      className={[frame.className, className].filter(Boolean).join(\" \")}\n      series={frame.series}\n      table={frame.table}\n      rows={frame.rows}\n      selected={selected}\n      onSelect={onSelect}\n      actions={actions}\n      plot={(context) => reactPlot(linePlot(options, context))}\n    />\n  )\n}\n\nexport { LineChart }\nexport type { LineChartProps }\n",
      "type": "registry:ui",
      "target": "@ui/line-chart.tsx"
    },
    {
      "path": "registry/uiset/ui/chart/plots/line.ts",
      "content": "// The line chart's geometry: lines, areas or stacks over evenly spaced x positions.\nimport { seriesColor, focusKey, type ChartFrameData, type ChartGeometry, type ChartPlotContext, type ChartPoint, type ChartSeries } from \"../plot\"\nimport { formatValue, labelIndexes, linear, numberFormat, point, tickFormatter } from \"../scale\"\nimport { tooltipRow, v, type VChild } from \"../vnode\"\n\ntype LineOptions<Datum> = {\n  data: readonly Datum[]\n  /** The x label for a datum, like \"Mar 3\". Points are evenly spaced, in data order. */\n  x: (datum: Datum) => string\n  series: ChartSeries<Datum>[]\n  /** Formats values in tooltips, end labels and the table. */\n  format?: (value: number) => string\n  /** Reads numbers in this locale; pass it when rendering on a server. */\n  locale?: string\n  /** Lines; lines with a soft area under each; or areas stacked to a total. */\n  layout?: \"line\" | \"area\" | \"stacked\"\n  /** Keep zero on the axis. Defaults to true; turn off for values far from zero. */\n  zero?: boolean\n}\n\nconst TICK = 12\nconst charWidth = 6.6\n\nfunction path(points: readonly ([number, number] | null)[]) {\n  let d = \"\"\n  let open = false\n  for (const p of points) {\n    if (!p) {\n      open = false\n      continue\n    }\n    d += `${open ? \"L\" : \"M\"}${p[0].toFixed(1)},${p[1].toFixed(1)}`\n    open = true\n  }\n  return d\n}\n\n/** An area between two edges, one closed shape per unbroken run (gaps stay gaps). */\nfunction areaPath(upper: readonly ([number, number] | null)[], lower: readonly [number, number][]) {\n  let d = \"\"\n  let run: number[] = []\n  const close = () => {\n    if (run.length > 1) {\n      d += `M${run.map((i) => `${upper[i]![0].toFixed(1)},${upper[i]![1].toFixed(1)}`).join(\"L\")}`\n      d += `L${[...run]\n        .reverse()\n        .map((i) => `${lower[i]![0].toFixed(1)},${lower[i]![1].toFixed(1)}`)\n        .join(\"L\")}Z`\n    }\n    run = []\n  }\n  upper.forEach((p, i) => (p ? run.push(i) : close()))\n  close()\n  return d\n}\n\nfunction lineParts<Datum>({ data, x, series, format, locale, layout = \"line\" }: LineOptions<Datum>) {\n  const stacked = layout === \"stacked\"\n  const filled = layout !== \"line\"\n  const fmt = numberFormat(locale, format)\n  const labels = data.map(x)\n  const value = (s: ChartSeries<Datum>, d: Datum) => {\n    const n = s.value(d)\n    return n === null || n === undefined || !Number.isFinite(n) ? null : n\n  }\n  const total = (list: readonly ChartSeries<Datum>[], d: Datum) => list.reduce((sum, s) => sum + (value(s, d) ?? 0), 0)\n  return { stacked, filled, fmt, labels, value, total }\n}\n\nfunction lineFrame<Datum>(options: LineOptions<Datum>): ChartFrameData {\n  const { data, series } = options\n  const { stacked, filled, fmt, labels, value, total } = lineParts(options)\n  return {\n    className: [\"line-chart\", stacked && \"chart-stacked\"].filter(Boolean).join(\" \"),\n    series: series.map((s) => ({ key: s.key, label: s.label, shape: filled ? \"rect\" : \"line\" })),\n    table: {\n      head: [\"\", ...series.map((s) => s.label), ...(stacked ? [\"Total\"] : [])],\n      numeric: [false, ...series.map(() => true), ...(stacked ? [true] : [])],\n      rows: data.map((d, i) => ({\n        key: `${i}`,\n        cells: [labels[i]!, ...series.map((s) => formatValue(value(s, d), fmt)), ...(stacked ? [fmt(total(series, d))] : [])],\n      })),\n    },\n    rows: () =>\n      data.map((d, i) => {\n        const row: Record<string, string> = { x: labels[i]! }\n        for (const s of series) row[s.label] = formatValue(value(s, d), fmt)\n        return row\n      }),\n  }\n}\n\nfunction linePlot<Datum>(options: LineOptions<Datum>, { width, height: h, shown, active, selected: pinned }: ChartPlotContext): ChartGeometry {\n  const { data, series, locale, zero = true } = options\n  const { stacked, filled, fmt, labels, value, total } = lineParts(options)\n  const keyOf = (index: number) => `${index}`\n  const visible = series.filter((s) => shown(s.key))\n  const lastIndex = data.length - 1\n  // The axis covers every edge drawn: values for lines; each running total for stacks, so a\n  // negative layer never pushes another off the plot.\n  const extents: number[] = []\n  for (const d of data) {\n    let sum = 0\n    for (const s of visible) {\n      const n = value(s, d)\n      if (stacked) {\n        sum += n ?? 0\n        extents.push(sum)\n      } else if (n !== null) extents.push(n)\n    }\n  }\n  const top = 8\n  const bottom = 28\n  const y = linear(extents, [h - bottom, top], { zero: zero || filled })\n  const yLabel = tickFormatter(y.ticks, locale)\n  const left = Math.max(0, ...y.ticks.map((t) => yLabel(t).length)) * charWidth + TICK\n  // Direct labels at line ends for two to four series, when they don't collide.\n  const ends =\n    lastIndex >= 0\n      ? visible.map((s) => ({ s, n: value(s, data[lastIndex]!) })).filter((e): e is { s: ChartSeries<Datum>; n: number } => e.n !== null)\n      : []\n  const labelEnds = !stacked && visible.length > 1 && visible.length <= 4 && ends.length > 0\n  const right = labelEnds ? Math.min(140, Math.max(0, ...ends.map((e) => e.s.label.length)) * charWidth + 16) : 12\n  const px = point(data.length, [left, width - right])\n  const baseline = y(Math.max(y.domain[0], Math.min(0, y.domain[1])))\n\n  const base = data.map(() => 0)\n  const marks = visible.map((s) => {\n    const color = seriesColor(series, s.key)\n    const tops = data.map((d, i) => {\n      const n = value(s, d)\n      if (n === null) return null\n      return [px(i), y(stacked ? base[i]! + n : n)] as [number, number]\n    })\n    let fill: string | null = null\n    if (filled) {\n      const lower = data.map((_, i) => [px(i), stacked ? y(base[i]!) : baseline] as [number, number])\n      fill = areaPath(tops, lower)\n    }\n    if (stacked) data.forEach((d, i) => (base[i] = base[i]! + (value(s, d) ?? 0)))\n    return { s, color, line: path(tops), fill, tops }\n  })\n\n  const focusIndex = Number(focusKey(active, pinned, (key) => /^\\d+$/.test(key) && Number(key) < data.length) ?? NaN)\n  const xLabels = labelIndexes(data.length, Math.max(2, Math.floor((width - left - right) / 84)))\n\n  // Each position's target runs halfway to its neighbors, so the pointer only has to be\n  // nearest to an x, never on a 2px line.\n  const edge = (i: number) => (i <= 0 ? left : i > lastIndex ? width - right : (px(i - 1) + px(i)) / 2)\n  const points: ChartPoint[] = data.map((d, i) => {\n    const readings = visible.map((s) => `${s.label} ${formatValue(value(s, d), fmt)}`)\n    if (stacked && visible.length > 1) readings.push(`total ${fmt(total(visible, d))}`)\n    const tops = marks.map((m) => m.tops[i]?.[1]).filter((n): n is number => n !== undefined)\n    return {\n      key: keyOf(i),\n      label: `${labels[i]}: ${readings.join(\", \")}`,\n      x: edge(i),\n      y: top,\n      width: edge(i + 1) - edge(i),\n      height: h - top - bottom,\n      anchor: { x: px(i), y: Math.min(h - bottom, ...tops) },\n    }\n  })\n\n  let endLabels: VChild[] = []\n  if (labelEnds) {\n    const placed = marks\n      .map((m) => ({ m, end: m.tops[lastIndex] }))\n      .filter((e): e is { m: (typeof marks)[number]; end: [number, number] } => !!e.end)\n      .sort((a, b) => a.end[1] - b.end[1])\n    const collide = placed.some((p, i) => i > 0 && p.end[1] - placed[i - 1]!.end[1] < 14)\n    if (!collide)\n      endLabels = placed.map(({ m, end }) => v(\"text\", { key: `end-${m.s.key}`, className: \"chart-end-label\", x: end[0] + 10, y: end[1], dy: \"0.32em\" }, m.s.label))\n  }\n\n  const svg: VChild[] = [\n    v(\"g\", { key: \"grid\", className: \"chart-grid\" }, ...y.ticks.map((t) => v(\"line\", { key: t, x1: left, x2: width - right, y1: y(t), y2: y(t), \"data-zero\": t === 0 ? \"\" : undefined }))),\n    v(\"g\", { key: \"y\", className: \"chart-axis-labels\", \"data-axis\": \"y\" }, ...y.ticks.map((t) => v(\"text\", { key: t, x: left - 8, y: y(t), dy: \"0.32em\", textAnchor: \"end\" }, yLabel(t)))),\n    v(\n      \"g\",\n      { key: \"x\", className: \"chart-axis-labels\", \"data-axis\": \"x\" },\n      ...xLabels.map((i) =>\n        v(\n          \"text\",\n          { key: i, x: px(i), y: h - bottom + 18, textAnchor: data.length > 1 && i === 0 ? \"start\" : data.length > 1 && i === lastIndex ? \"end\" : \"middle\" },\n          labels[i],\n        ),\n      ),\n    ),\n    Number.isFinite(focusIndex) && v(\"line\", { key: \"crosshair\", className: \"chart-crosshair\", x1: px(focusIndex), x2: px(focusIndex), y1: top, y2: h - bottom }),\n    ...marks.map((m) => {\n      const end = lastIndex >= 0 ? m.tops[lastIndex] : null\n      const at = Number.isFinite(focusIndex) ? m.tops[focusIndex] : null\n      return v(\n        \"g\",\n        { key: m.s.key, className: \"chart-series\", style: { \"--series\": m.color } },\n        m.fill && v(\"path\", { className: \"chart-area\", d: m.fill }),\n        v(\"path\", { className: \"chart-line\", d: m.line }),\n        end && !Number.isFinite(focusIndex) && v(\"circle\", { className: \"chart-dot\", cx: end[0], cy: end[1], r: 4 }),\n        at && v(\"circle\", { className: \"chart-dot\", \"data-active\": \"\", cx: at[0], cy: at[1], r: 4.5 }),\n      )\n    }),\n    ...endLabels,\n  ]\n\n  return {\n    svg,\n    points,\n    tooltip: (key) => {\n      const i = Number(key)\n      const d = data[i]\n      if (d === undefined) return null\n      return [\n        v(\"span\", { key: \"title\", className: \"chart-tooltip-title\" }, labels[i]),\n        ...visible.map((s) => tooltipRow(seriesColor(series, s.key), formatValue(value(s, d), fmt), s.label, filled ? \"rect\" : \"line\", s.key)),\n        stacked && visible.length > 1 && v(\"span\", { key: \"total\", className: \"chart-tooltip-total\" }, v(\"strong\", {}, fmt(total(visible, d))), \" total\"),\n      ]\n    },\n  }\n}\n\nexport { lineFrame, linePlot }\nexport type { LineOptions }\n",
      "type": "registry:file",
      "target": "@ui/chart/plots/line.ts"
    }
  ],
  "type": "registry:ui"
}