{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "stream-chart",
  "type": "registry:component",
  "title": "Stream Chart",
  "description": "Several series stacked as flowing layers around a centre line instead of a baseline (a streamgraph), so the rise and fall of each layer and of the whole read as a shape over time; arrow keys read every moment.",
  "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/stream-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/stream-chart.tsx",
      "content": "\"use client\";\n/**\n * @name stream-chart\n * @category viz\n * @description Several series stacked as flowing layers around a centre line instead of a baseline (a streamgraph), so the rise and fall of each layer and of the whole read as a shape over time; arrow keys read every moment.\n * @when Showing how the mix of up to five categories shifts over a long time, where the overall shape matters more than exact values: listening by genre, topics over years. For exact totals use area-chart stacked (with a baseline); for exact values per series use line-chart.\n * @example\n * <StreamChart\n *   label=\"Plays by genre\"\n *   data={[\n *     { year: 2020, jazz: 20, folk: 30, rock: 50 },\n *     { year: 2021, jazz: 28, folk: 34, rock: 44 },\n *     { year: 2022, jazz: 40, folk: 30, rock: 38 },\n *   ]}\n *   x=\"year\"\n *   series={[{ key: \"jazz\", label: \"Jazz\" }, { key: \"folk\", label: \"Folk\" }, { key: \"rock\", label: \"Rock\" }]}\n * />\n */\nimport { scaleLinear, scaleUtc } from \"d3-scale\";\nimport { area, curveBasis, stack, type SeriesPoint, stackOffsetSilhouette, stackOffsetWiggle, stackOrderInsideOut } from \"d3-shape\";\nimport { useMemo, type PointerEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  ChartContainer,\n  ChartEmpty,\n  ChartLegend,\n  chartSeries,\n  ChartSvg,\n  ChartTooltip,\n  dateFormatter,\n  formatNumber,\n  readNumber,\n  useChartCursor,\n  type ChartBaseProps,\n  type ChartSeries,\n} from \"@/components/viz/chart\";\n\nexport type StreamChartProps<T extends object> = ChartBaseProps & {\n  data: readonly T[];\n  /** The field holding x: a number or a Date. */\n  x: keyof T & string;\n  series: readonly ChartSeries<T>[];\n  /** \"wiggle\" keeps the layers as still as it can; \"silhouette\" centres the whole on the middle line. */\n  offset?: \"wiggle\" | \"silhouette\";\n  xLabel?: string;\n  formatX?: (value: number | Date) => string;\n  timeZone?: string;\n  showLegend?: boolean;\n};\n\ntype Row = Record<string, number>;\n\nexport function StreamChart<T extends object>({\n  data,\n  x,\n  series,\n  offset = \"wiggle\",\n  xLabel,\n  formatX,\n  timeZone,\n  showLegend = true,\n  label,\n  aspect,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: StreamChartProps<T>) {\n  const model = useMemo(() => {\n    const isTime = data.some((row) => (row as Record<string, unknown>)[x] instanceof Date);\n    const rows: Row[] = data\n      .flatMap((row) => {\n        const raw = (row as Record<string, unknown>)[x];\n        const at = raw instanceof Date ? raw.getTime() : typeof raw === \"number\" ? raw : NaN;\n        if (!Number.isFinite(at)) return [];\n        const out: Row = { __x: at };\n        for (const s of series) out[s.key] = Math.max(0, readNumber(row, s.key) ?? 0);\n        return [out];\n      })\n      .sort((a, b) => (a[\"__x\"] ?? 0) - (b[\"__x\"] ?? 0));\n    const layers = stack<Row>()\n      .keys(series.map((s) => s.key))\n      .order(stackOrderInsideOut)\n      .offset(offset === \"wiggle\" ? stackOffsetWiggle : stackOffsetSilhouette)(rows);\n    return { rows, layers, isTime };\n  }, [data, x, series, offset]);\n  const { rows, layers, isTime } = model;\n  const cursor = useChartCursor(rows.length);\n  const number = formatValue ?? ((value: number) => formatNumber(value, locale));\n  const xs = rows.map((row) => row[\"__x\"] ?? 0);\n  const span = xs.length > 1 ? (xs[xs.length - 1] ?? 0) - (xs[0] ?? 0) : 0;\n  const fullX = formatX ?? (isTime ? dateFormatter(span, \"full\", locale, timeZone) : (v: number | Date) => formatNumber(Number(v), locale));\n  const axisX = formatX ?? (isTime ? dateFormatter(span, \"axis\", locale, timeZone) : (v: number | Date) => formatNumber(Number(v), locale));\n  const xOf = (v: number): number | Date => (isTime ? new Date(v) : v);\n  const table = { caption: label, columns: [xLabel ?? x, ...series.map((s) => s.label)], rows: rows.map((row) => [fullX(xOf(row[\"__x\"] ?? 0)), ...series.map((s) => number(row[s.key] ?? 0))]) };\n  const current = cursor.active === null ? undefined : rows[cursor.active];\n  const rowsOf = (row: Row): { label: string; value: string; index: number; mark: \"rect\" }[] => series.map((s, i) => ({ label: s.label, value: number(row[s.key] ?? 0), index: i, mark: \"rect\" }));\n\n  return (\n    <div data-slot=\"stream-chart\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      {showLegend ? <ChartLegend items={series.map((s, i) => ({ label: s.label, index: i }))} mark=\"rect\" /> : null}\n      <ChartContainer\n        aspect={aspect}\n        height={height}\n        table={table}\n        announcement={\n          cursor.keyboard && current\n            ? `${fullX(xOf(current[\"__x\"] ?? 0))}: ${rowsOf(current)\n                .map((r) => `${r.label} ${r.value}`)\n                .join(\", \")}`\n            : \"\"\n        }\n      >\n        {({ width, height: plotHeight }) => {\n          if (rows.length < 2) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const bottom = 26;\n          const low = Math.min(...layers.flatMap((layer) => layer.map((p) => p[0])));\n          const high = Math.max(...layers.flatMap((layer) => layer.map((p) => p[1])));\n          const sy = scaleLinear()\n            .domain([low, high === low ? low + 1 : high])\n            .range([plotHeight - bottom, 6]);\n          const domain: [number, number] = [xs[0] ?? 0, xs[xs.length - 1] ?? 1];\n          const time = scaleUtc()\n            .domain(domain)\n            .range([4, width - 4]);\n          const linear = scaleLinear()\n            .domain(domain)\n            .range([4, width - 4]);\n          const sx = (v: number): number => (isTime ? time(v) : linear(v));\n          const ticks = isTime ? time.ticks(Math.max(2, Math.floor(width / 100))).map((d) => d.getTime()) : linear.ticks(Math.max(2, Math.floor(width / 100)));\n          const shape = area<SeriesPoint<Row>>()\n            .curve(curveBasis)\n            .x((p) => sx(p.data[\"__x\"] ?? 0))\n            .y0((p) => sy(p[0]))\n            .y1((p) => sy(p[1]));\n          const onPointerMove = (event: PointerEvent<SVGSVGElement>): void => {\n            const px = event.clientX - event.currentTarget.getBoundingClientRect().left;\n            let best = 0;\n            xs.forEach((v, i) => {\n              if (Math.abs(sx(v) - px) < Math.abs(sx(xs[best] ?? 0) - px)) best = i;\n            });\n            cursor.point(best);\n          };\n          const shownX = current ? sx(current[\"__x\"] ?? 0) : 0;\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps} onPointerMove={onPointerMove}>\n                <g aria-hidden=\"true\" className=\"fill-muted-foreground tabular-nums\">\n                  {ticks.map((t) => (\n                    <text key={t} x={sx(t)} y={plotHeight - bottom + 6} dy=\"1em\" textAnchor=\"middle\">\n                      {axisX(xOf(t))}\n                    </text>\n                  ))}\n                </g>\n                <g aria-hidden=\"true\">\n                  {layers.map((layer) => (\n                    <path key={layer.key} d={shape(layer) ?? \"\"} className={cn(chartSeries(layer.index).fill, \"stroke-background\")} strokeWidth={1.5} fillOpacity={0.85} />\n                  ))}\n                  {current ? <line x1={shownX} x2={shownX} y1={6} y2={plotHeight - bottom} className=\"stroke-foreground\" strokeWidth={1.5} /> : null}\n                </g>\n              </ChartSvg>\n              {current ? <ChartTooltip x={shownX} y={plotHeight / 2} side={shownX > width / 2 ? \"left\" : \"right\"} title={fullX(xOf(current[\"__x\"] ?? 0))} rows={rowsOf(current)} /> : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Showing how the mix of up to five categories shifts over a long time, where the overall shape matters more than exact values: listening by genre, topics over years. For exact totals use area-chart stacked (with a baseline); for exact values per series use line-chart.",
    "example": "<StreamChart\n  label=\"Plays by genre\"\n  data={[\n    { year: 2020, jazz: 20, folk: 30, rock: 50 },\n    { year: 2021, jazz: 28, folk: 34, rock: 44 },\n    { year: 2022, jazz: 40, folk: 30, rock: 38 },\n  ]}\n  x=\"year\"\n  series={[{ key: \"jazz\", label: \"Jazz\" }, { key: \"folk\", label: \"Folk\" }, { key: \"rock\", label: \"Rock\" }]}\n/>",
    "client": true
  }
}
