{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "scatter-chart",
  "type": "registry:component",
  "title": "Scatter Chart",
  "description": "Points placed by two numbers, optionally sized by a third (a bubble chart) and grouped by a category, with the nearest point read under the pointer and every point reachable by arrow keys.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-delaunay",
    "d3-scale"
  ],
  "devDependencies": [
    "@types/d3-delaunay",
    "@types/d3-scale"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/scatter-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/scatter-chart.tsx",
      "content": "\"use client\";\n/**\n * @name scatter-chart\n * @category viz\n * @description Points placed by two numbers, optionally sized by a third (a bubble chart) and grouped by a category, with the nearest point read under the pointer and every point reachable by arrow keys.\n * @when Showing how two measures relate across many things: does one rise with the other, which stand apart. Give `size` for a third measure as bubble area. For change over time use line-chart; for one measure across categories use bar-chart or dot-plot; for thousands of overlapping points use density-chart.\n * @example\n * <ScatterChart\n *   label=\"Price against rating\"\n *   data={[\n *     { name: \"Alder\", price: 12, rating: 4.1, sold: 320, kind: \"Tea\" },\n *     { name: \"Birch\", price: 18, rating: 4.6, sold: 120, kind: \"Tea\" },\n *     { name: \"Cedar\", price: 9, rating: 3.8, sold: 540, kind: \"Coffee\" },\n *   ]}\n *   x=\"price\"\n *   y=\"rating\"\n *   size=\"sold\"\n *   group=\"kind\"\n *   name=\"name\"\n *   xLabel=\"Price\"\n *   yLabel=\"Rating\"\n * />\n */\nimport { Delaunay } from \"d3-delaunay\";\nimport { scaleSqrt } from \"d3-scale\";\nimport { useMemo, type PointerEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  axisNumberFormatter,\n  ChartAxis,\n  ChartContainer,\n  ChartEmpty,\n  ChartGrid,\n  ChartLegend,\n  ChartMark,\n  chartLinear,\n  chartSeries,\n  ChartSvg,\n  ChartTooltip,\n  formatNumber,\n  readNumber,\n  useChartCursor,\n  widestText,\n  type ChartBaseProps,\n} from \"@/components/viz/chart\";\n\nexport type ScatterChartProps<T extends object> = ChartBaseProps & {\n  /** One object per point. Rows without a number for x or y are left out. */\n  data: readonly T[];\n  /** The field for the horizontal position. */\n  x: keyof T & string;\n  /** The field for the vertical position. */\n  y: keyof T & string;\n  /** A field whose number sets each point's area: a bubble chart. */\n  size?: keyof T & string;\n  /** A field naming each point's group: one colour and shape per group, in order of first appearance. */\n  group?: keyof T & string;\n  /** The groups in a fixed order, so a group keeps its colour when another is filtered out. */\n  groups?: readonly string[];\n  /** A field naming each point, for the tooltip and the table. */\n  name?: keyof T & string;\n  /** The names of the measures, on the axes, in the tooltip and in the table. Default: the field names. */\n  xLabel?: string;\n  yLabel?: string;\n  sizeLabel?: string;\n  /** Start an axis at zero. Default false: a scatter is read by position, not length. */\n  zeroX?: boolean;\n  zeroY?: boolean;\n  showGrid?: boolean;\n  /** Default: shown when there are two or more groups. */\n  showLegend?: boolean;\n  /** The largest bubble's radius in pixels. Default: a twelfth of the shorter side, at most 28. */\n  maxRadius?: number;\n};\n\ntype Point = {\n  row: number;\n  x: number;\n  y: number;\n  size: number | null;\n  group: number;\n  name: string;\n};\n\nexport function ScatterChart<T extends object>({\n  data,\n  x,\n  y,\n  size,\n  group,\n  groups,\n  name,\n  xLabel,\n  yLabel,\n  sizeLabel,\n  zeroX = false,\n  zeroY = false,\n  showGrid = true,\n  showLegend,\n  maxRadius,\n  label,\n  aspect,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: ScatterChartProps<T>) {\n  const model = useMemo(() => {\n    const read = (row: T, key: string | undefined): string => (key ? String((row as Record<string, unknown>)[key] ?? \"\") : \"\");\n    const order = groups ? [...groups] : [...new Set(data.map((row) => read(row, group)))];\n    const points: Point[] = [];\n    data.forEach((row, index) => {\n      const px = readNumber(row, x);\n      const py = readNumber(row, y);\n      if (px === null || py === null) return;\n      const g = group ? order.indexOf(read(row, group)) : 0;\n      points.push({\n        row: index,\n        x: px,\n        y: py,\n        size: size ? readNumber(row, size) : null,\n        group: g,\n        name: read(row, name),\n      });\n    });\n    // Reading order is left to right, so the arrow keys follow the x axis.\n    points.sort((a, b) => a.x - b.x || a.y - b.y);\n    return { points, order };\n  }, [data, x, y, size, group, groups, name]);\n\n  const { points, order } = model;\n  const cursor = useChartCursor(points.length);\n  const value = formatValue ?? ((number: number) => formatNumber(number, locale));\n  const names = {\n    x: xLabel ?? x,\n    y: yLabel ?? y,\n    size: sizeLabel ?? size ?? \"\",\n  };\n  const grouped = Boolean(group) && order.length > 0;\n  const table = {\n    caption: label,\n    columns: [...(name ? [name] : [\"#\"]), names.x, names.y, ...(size ? [names.size] : []), ...(grouped ? [group ?? \"\"] : [])],\n    rows: points.map((point, index) => [\n      name ? point.name : String(index + 1),\n      value(point.x),\n      value(point.y),\n      ...(size ? [point.size === null ? \"\" : value(point.size)] : []),\n      ...(grouped ? [order[point.group] ?? \"\"] : []),\n    ]),\n  };\n  const current = cursor.active === null ? undefined : points[cursor.active];\n  const describe = (point: Point): string =>\n    [point.name, grouped ? order[point.group] : \"\", `${names.x} ${value(point.x)}`, `${names.y} ${value(point.y)}`, size && point.size !== null ? `${names.size} ${value(point.size)}` : \"\"]\n      .filter(Boolean)\n      .join(\", \");\n  const legend = showLegend ?? (grouped && order.length > 1);\n\n  return (\n    <div data-slot=\"scatter-chart\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      {legend ? <ChartLegend items={order.map((item, index) => ({ label: item, index }))} mark=\"rect\" /> : null}\n      <ChartContainer aspect={aspect ?? 4 / 3} height={height} table={table} announcement={cursor.keyboard && current ? describe(current) : \"\"}>\n        {({ width, height: plotHeight }) => {\n          if (points.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const xs = points.map((point) => point.x);\n          const ys = points.map((point) => point.y);\n          const lowX = Math.min(...xs, ...(zeroX ? [0] : []));\n          const highX = Math.max(...xs, ...(zeroX ? [0] : []));\n          const lowY = Math.min(...ys, ...(zeroY ? [0] : []));\n          const highY = Math.max(...ys, ...(zeroY ? [0] : []));\n          const top = 12;\n          const bottom = 44;\n          const probe = chartLinear(lowY, highY, [plotHeight - bottom, top]);\n          const axisY = formatValue ?? axisNumberFormatter(Math.max(Math.abs(lowY), Math.abs(highY)), locale);\n          const left = widestText(probe.ticks.map(axisY)) + 12;\n          const right = 12;\n          const sx = chartLinear(lowX, highX, [left, width - right], 80);\n          const sy = probe;\n          const axisX = formatValue ?? axisNumberFormatter(Math.max(Math.abs(lowX), Math.abs(highX)), locale);\n          const sizes = points.flatMap((point) => (point.size === null ? [] : [Math.max(0, point.size)]));\n          const reach = maxRadius ?? Math.min(28, Math.max(6, Math.min(width, plotHeight) / 12));\n          const radius = scaleSqrt()\n            .domain([0, Math.max(1e-9, ...sizes)])\n            .range([size ? 2 : 4, size ? reach : 4]);\n          const placed = points.map((point) => ({\n            point,\n            cx: sx.scale(point.x),\n            cy: sy.scale(point.y),\n            r: size ? radius(Math.max(0, point.size ?? 0)) : 4.5,\n          }));\n          const finder = Delaunay.from(\n            placed,\n            (item) => item.cx,\n            (item) => item.cy,\n          );\n          const onPointerMove = (event: PointerEvent<SVGSVGElement>): void => {\n            const box = event.currentTarget.getBoundingClientRect();\n            const px = event.clientX - box.left;\n            const py = event.clientY - box.top;\n            const index = finder.find(px, py);\n            const hit = placed[index];\n            cursor.point(hit && Math.hypot(hit.cx - px, hit.cy - py) <= Math.max(24, hit.r + 8) ? index : null);\n          };\n          const shown = cursor.active === null ? undefined : placed[cursor.active];\n          // Big bubbles behind small ones, so none is hidden.\n          const drawOrder = size ? [...placed].sort((a, b) => b.r - a.r) : placed;\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps} onPointerMove={onPointerMove}>\n                {showGrid ? (\n                  <>\n                    <ChartGrid offsets={sy.ticks.map((tick) => sy.scale(tick))} from={left} to={width - right} />\n                    <ChartGrid offsets={sx.ticks.map((tick) => sx.scale(tick))} from={top} to={plotHeight - bottom} vertical />\n                  </>\n                ) : null}\n                <ChartAxis\n                  side=\"left\"\n                  at={left - 8}\n                  ticks={sy.ticks.map((tick) => ({\n                    offset: sy.scale(tick),\n                    label: axisY(tick),\n                  }))}\n                />\n                <ChartAxis\n                  side=\"bottom\"\n                  at={plotHeight - bottom + 6}\n                  ticks={sx.ticks.map((tick) => ({\n                    offset: sx.scale(tick),\n                    label: axisX(tick),\n                  }))}\n                />\n                <g aria-hidden=\"true\" className=\"fill-muted-foreground\">\n                  <text x={(left + width - right) / 2} y={plotHeight - 4} textAnchor=\"middle\">\n                    {names.x}\n                  </text>\n                  <text x={left} y={top - 2} textAnchor=\"start\" className=\"sr-only\">\n                    {names.y}\n                  </text>\n                </g>\n                <g aria-hidden=\"true\">\n                  {drawOrder.map((item) =>\n                    size ? (\n                      <circle\n                        key={item.point.row}\n                        cx={item.cx}\n                        cy={item.cy}\n                        r={item.r}\n                        className={cn(\n                          chartSeries(item.point.group).fill,\n                          \"stroke-background opacity-75 transition-opacity duration-instant motion-reduce:transition-none\",\n                          shown && shown !== item && \"opacity-35\",\n                        )}\n                        strokeWidth={1.5}\n                      />\n                    ) : (\n                      <ChartMark\n                        key={item.point.row}\n                        index={item.point.group}\n                        x={item.cx}\n                        y={item.cy}\n                        radius={4.5}\n                        className={cn(\"transition-opacity duration-instant motion-reduce:transition-none\", shown && shown !== item && \"opacity-45\")}\n                      />\n                    ),\n                  )}\n                  {shown ? <circle cx={shown.cx} cy={shown.cy} r={shown.r + 3} fill=\"none\" className=\"stroke-foreground\" strokeWidth={2} /> : null}\n                </g>\n              </ChartSvg>\n              {shown ? (\n                <ChartTooltip\n                  x={shown.cx}\n                  y={shown.cy}\n                  side={shown.cx > width / 2 ? \"left\" : \"right\"}\n                  title={shown.point.name || (grouped ? order[shown.point.group] : undefined)}\n                  rows={[\n                    { label: names.x, value: value(shown.point.x) },\n                    { label: names.y, value: value(shown.point.y) },\n                    ...(size && shown.point.size !== null ? [{ label: names.size, value: value(shown.point.size) }] : []),\n                    ...(grouped && shown.point.name\n                      ? [\n                          {\n                            label: \"\",\n                            value: order[shown.point.group] ?? \"\",\n                            index: shown.point.group,\n                            mark: \"rect\" as const,\n                          },\n                        ]\n                      : []),\n                  ]}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Showing how two measures relate across many things: does one rise with the other, which stand apart. Give `size` for a third measure as bubble area. For change over time use line-chart; for one measure across categories use bar-chart or dot-plot; for thousands of overlapping points use density-chart.",
    "example": "<ScatterChart\n  label=\"Price against rating\"\n  data={[\n    { name: \"Alder\", price: 12, rating: 4.1, sold: 320, kind: \"Tea\" },\n    { name: \"Birch\", price: 18, rating: 4.6, sold: 120, kind: \"Tea\" },\n    { name: \"Cedar\", price: 9, rating: 3.8, sold: 540, kind: \"Coffee\" },\n  ]}\n  x=\"price\"\n  y=\"rating\"\n  size=\"sold\"\n  group=\"kind\"\n  name=\"name\"\n  xLabel=\"Price\"\n  yLabel=\"Rating\"\n/>",
    "client": true
  }
}
