{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "slope-chart",
  "type": "registry:component",
  "title": "Slope Chart",
  "description": "Each thing's value at two moments joined by a line, so what rose, what fell and how the ranking changed read at once: names and values at both ends, rises solid and falls dashed so direction never rests on colour.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-scale"
  ],
  "devDependencies": [
    "@types/d3-scale"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/slope-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/slope-chart.tsx",
      "content": "\"use client\";\n/**\n * @name slope-chart\n * @category viz\n * @description Each thing's value at two moments joined by a line, so what rose, what fell and how the ranking changed read at once: names and values at both ends, rises solid and falls dashed so direction never rests on colour.\n * @when Comparing many things between exactly two moments or conditions: this year and last, before and after a change. For many moments use line-chart or small-multiples; for one thing's change use a stat with its delta; for a few categories use dot-plot dumbbell.\n * @example\n * <SlopeChart\n *   label=\"Share of trips by mode\"\n *   data={[\n *     { mode: \"Car\", y2016: 52, y2026: 41 },\n *     { mode: \"Bike\", y2016: 9, y2026: 18 },\n *     { mode: \"Transit\", y2016: 24, y2026: 27 },\n *   ]}\n *   name=\"mode\"\n *   from=\"y2016\"\n *   to=\"y2026\"\n *   fromLabel=\"2016\"\n *   toLabel=\"2026\"\n * />\n */\nimport { scaleLinear } from \"d3-scale\";\nimport { useMemo } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { ChartContainer, ChartEmpty, ChartSvg, ChartTooltip, fitText, formatNumber, readNumber, useChartCursor, widestText, type ChartBaseProps } from \"@/components/viz/chart\";\n\nexport type SlopeChartLabels = { change: string; rose: string; fell: string; same: string };\n\nexport type SlopeChartProps<T extends object> = ChartBaseProps & {\n  data: readonly T[];\n  /** The field naming each thing. */\n  name: keyof T & string;\n  /** The fields holding the first and second values. */\n  from: keyof T & string;\n  to: keyof T & string;\n  /** The names of the two moments, above the two columns. */\n  fromLabel: string;\n  toLabel: string;\n  labels?: Partial<SlopeChartLabels>;\n};\n\nconst LABELS: SlopeChartLabels = { change: \"Change\", rose: \"Rose\", fell: \"Fell\", same: \"No change\" };\n\ntype Line = { name: string; a: number; b: number };\n\n/** Spreads label positions apart so none are nearer than `gap`, keeping their order. */\nfunction spread(ys: number[], gap: number, low: number, high: number): number[] {\n  const order = ys.map((y, i) => ({ y, i })).sort((p, q) => p.y - q.y);\n  for (let k = 1; k < order.length; k++) {\n    const prev = order[k - 1];\n    const item = order[k];\n    if (prev && item && item.y - prev.y < gap) item.y = prev.y + gap;\n  }\n  const last = order[order.length - 1];\n  if (last && last.y > high) {\n    const shift = last.y - high;\n    for (const item of order) item.y -= shift;\n  }\n  for (const item of order) item.y = Math.max(low, item.y);\n  const out = [...ys];\n  for (const item of order) out[item.i] = item.y;\n  return out;\n}\n\nexport function SlopeChart<T extends object>({\n  data,\n  name,\n  from,\n  to,\n  fromLabel,\n  toLabel,\n  labels: given,\n  label,\n  aspect = 1,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: SlopeChartProps<T>) {\n  const labels = { ...LABELS, ...given };\n  const lines = useMemo(\n    () =>\n      data.flatMap((row): Line[] => {\n        const a = readNumber(row, from);\n        const b = readNumber(row, to);\n        return a === null || b === null ? [] : [{ name: String((row as Record<string, unknown>)[name] ?? \"\"), a, b }];\n      }),\n    [data, name, from, to],\n  );\n  const cursor = useChartCursor(lines.length);\n  const number = formatValue ?? ((value: number) => formatNumber(value, locale));\n  const change = (line: Line): string => (formatValue ? formatValue(line.b - line.a) : formatNumber(line.b - line.a, locale, { signDisplay: \"exceptZero\", maximumFractionDigits: 2 }));\n  const direction = (line: Line): string => (line.b > line.a ? labels.rose : line.b < line.a ? labels.fell : labels.same);\n  const table = { caption: label, columns: [name, fromLabel, toLabel, labels.change], rows: lines.map((line) => [line.name, number(line.a), number(line.b), `${change(line)} (${direction(line)})`]) };\n  const current = cursor.active === null ? undefined : lines[cursor.active];\n\n  return (\n    <div data-slot=\"slope-chart\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      <ChartContainer\n        aspect={aspect}\n        height={height}\n        table={table}\n        announcement={cursor.keyboard && current ? `${current.name}: ${fromLabel} ${number(current.a)}, ${toLabel} ${number(current.b)}, ${direction(current)} ${change(current)}` : \"\"}\n      >\n        {({ width, height: plotHeight }) => {\n          if (lines.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const top = 28;\n          const bottom = 10;\n          const all = lines.flatMap((l) => [l.a, l.b]);\n          const sy = scaleLinear()\n            .domain([Math.min(...all), Math.max(...all) === Math.min(...all) ? Math.min(...all) + 1 : Math.max(...all)])\n            .range([plotHeight - bottom, top]);\n          const room = Math.min(width * 0.32, widestText(lines.map((l) => `${l.name} ${number(Math.max(l.a, l.b))}`)) + 12);\n          const x1 = room;\n          const x2 = width - room;\n          const leftYs = spread(\n            lines.map((l) => sy(l.a)),\n            14,\n            top,\n            plotHeight - bottom,\n          );\n          const rightYs = spread(\n            lines.map((l) => sy(l.b)),\n            14,\n            top,\n            plotHeight - bottom,\n          );\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps}>\n                <g aria-hidden=\"true\">\n                  <line x1={x1} x2={x1} y1={top - 6} y2={plotHeight - bottom} className=\"stroke-border-strong\" />\n                  <line x1={x2} x2={x2} y1={top - 6} y2={plotHeight - bottom} className=\"stroke-border-strong\" />\n                  <text x={x1} y={12} textAnchor=\"middle\" className=\"fill-foreground text-xs font-medium\">\n                    {fromLabel}\n                  </text>\n                  <text x={x2} y={12} textAnchor=\"middle\" className=\"fill-foreground text-xs font-medium\">\n                    {toLabel}\n                  </text>\n                  {lines.map((line, i) => {\n                    const rose = line.b >= line.a;\n                    const dim = cursor.active !== null && cursor.active !== i;\n                    return (\n                      <g key={i} onPointerEnter={() => cursor.point(i)} className={cn(\"transition-opacity duration-instant motion-reduce:transition-none\", dim && \"opacity-30\")}>\n                        <line x1={x1} x2={x2} y1={sy(line.a)} y2={sy(line.b)} stroke=\"transparent\" strokeWidth={12} />\n                        <line\n                          x1={x1}\n                          x2={x2}\n                          y1={sy(line.a)}\n                          y2={sy(line.b)}\n                          className={rose ? \"stroke-chart-1\" : \"stroke-chart-2\"}\n                          strokeWidth={cursor.active === i ? 3 : 2}\n                          strokeDasharray={rose ? undefined : \"6 4\"}\n                        />\n                        <circle cx={x1} cy={sy(line.a)} r={3.5} className={cn(rose ? \"fill-chart-1\" : \"fill-chart-2\", \"stroke-background\")} strokeWidth={1.5} />\n                        <circle cx={x2} cy={sy(line.b)} r={3.5} className={cn(rose ? \"fill-chart-1\" : \"fill-chart-2\", \"stroke-background\")} strokeWidth={1.5} />\n                        <text x={x1 - 8} y={leftYs[i]} dy=\"0.32em\" textAnchor=\"end\" className=\"fill-muted-foreground text-xs tabular-nums\">\n                          {fitText(line.name, room - 48)} <tspan className=\"fill-foreground\">{number(line.a)}</tspan>\n                        </text>\n                        <text x={x2 + 8} y={rightYs[i]} dy=\"0.32em\" className=\"fill-muted-foreground text-xs tabular-nums\">\n                          <tspan className=\"fill-foreground\">{number(line.b)}</tspan> {fitText(line.name, room - 48)}\n                        </text>\n                      </g>\n                    );\n                  })}\n                </g>\n              </ChartSvg>\n              {current ? (\n                <ChartTooltip\n                  x={(x1 + x2) / 2}\n                  y={(sy(current.a) + sy(current.b)) / 2}\n                  side=\"right\"\n                  title={current.name}\n                  rows={[\n                    { label: fromLabel, value: number(current.a) },\n                    { label: toLabel, value: number(current.b) },\n                    { label: direction(current), value: change(current) },\n                  ]}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Comparing many things between exactly two moments or conditions: this year and last, before and after a change. For many moments use line-chart or small-multiples; for one thing's change use a stat with its delta; for a few categories use dot-plot dumbbell.",
    "example": "<SlopeChart\n  label=\"Share of trips by mode\"\n  data={[\n    { mode: \"Car\", y2016: 52, y2026: 41 },\n    { mode: \"Bike\", y2016: 9, y2026: 18 },\n    { mode: \"Transit\", y2016: 24, y2026: 27 },\n  ]}\n  name=\"mode\"\n  from=\"y2016\"\n  to=\"y2026\"\n  fromLabel=\"2016\"\n  toLabel=\"2026\"\n/>",
    "client": true
  }
}
