{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "density-chart",
  "type": "registry:component",
  "title": "Density Chart",
  "description": "Where many points crowd together, drawn as filled contour bands of one hue from faint to strong (like the lines of a height map), with the points optionally on top and each point reachable by arrow keys.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-contour",
    "d3-delaunay"
  ],
  "devDependencies": [
    "@types/d3-contour",
    "@types/d3-delaunay"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/density-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/density-chart.tsx",
      "content": "\"use client\";\n/**\n * @name density-chart\n * @category viz\n * @description Where many points crowd together, drawn as filled contour bands of one hue from faint to strong (like the lines of a height map), with the points optionally on top and each point reachable by arrow keys.\n * @when Two measures over hundreds or thousands of points, where a scatter-chart would be a blot: where the bulk lies, whether there are two clusters. For under a few hundred points use scatter-chart; for one measure's spread use histogram.\n * @example\n * <DensityChart\n *   label=\"Trip length against fare\"\n *   data={[{ km: 2, fare: 8 }, { km: 3, fare: 10 }, { km: 2.5, fare: 9 }, { km: 12, fare: 31 }, { km: 11, fare: 29 }]}\n *   x=\"km\"\n *   y=\"fare\"\n *   xLabel=\"Distance (km)\"\n *   yLabel=\"Fare\"\n *   showPoints\n * />\n */\nimport { contourDensity } from \"d3-contour\";\nimport { Delaunay } from \"d3-delaunay\";\nimport { useId, useMemo, type PointerEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  axisNumberFormatter,\n  ChartAxis,\n  ChartContainer,\n  ChartEmpty,\n  ChartGrid,\n  chartLinear,\n  chartSequential,\n  ChartSvg,\n  ChartTooltip,\n  formatNumber,\n  readNumber,\n  useChartCursor,\n  widestText,\n  type ChartBaseProps,\n} from \"@/components/viz/chart\";\n\nexport type DensityChartProps<T extends object> = ChartBaseProps & {\n  /** One object per point. */\n  data: readonly T[];\n  x: keyof T & string;\n  y: keyof T & string;\n  /** A field whose number weights each point. Default: every point counts once. */\n  weight?: keyof T & string;\n  /** The names of the measures. Default: the field names. */\n  xLabel?: string;\n  yLabel?: string;\n  /** How smooth the bands are, in pixels. Default 20. */\n  bandwidth?: number;\n  /** About how many bands. Default 8. */\n  levels?: number;\n  /** Draw the points over the bands. Default: when there are 300 or fewer. */\n  showPoints?: boolean;\n  showGrid?: boolean;\n};\n\n\n/** A contour's rings as an SVG path: its coordinates are already in pixels. */\nfunction ringsPath(polygons: number[][][][]): string {\n  return polygons.map((polygon) => polygon.map((ring) => `M${ring.map((p) => `${p[0] ?? 0},${p[1] ?? 0}`).join(\"L\")}Z`).join(\"\")).join(\"\");\n}\n\nexport function DensityChart<T extends object>({\n  data,\n  x,\n  y,\n  weight,\n  xLabel,\n  yLabel,\n  bandwidth = 20,\n  levels = 8,\n  showPoints,\n  showGrid = true,\n  label,\n  aspect = 4 / 3,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: DensityChartProps<T>) {\n  const points = useMemo(\n    () =>\n      data\n        .flatMap((row, index) => {\n          const px = readNumber(row, x);\n          const py = readNumber(row, y);\n          if (px === null || py === null) return [];\n          return [{ x: px, y: py, w: weight ? Math.max(0, readNumber(row, weight) ?? 0) : 1, row: index }];\n        })\n        .sort((a, b) => a.x - b.x || a.y - b.y),\n    [data, x, y, weight],\n  );\n  const cursor = useChartCursor(points.length);\n  const clip = `density-${useId().replace(/[^a-zA-Z0-9]/g, \"\")}`;\n  const number = formatValue ?? ((value: number) => formatNumber(value, locale));\n  const names = { x: xLabel ?? x, y: yLabel ?? y };\n  const table = {\n    caption: label,\n    columns: [\"#\", names.x, names.y, ...(weight ? [weight] : [])],\n    rows: points.map((p, i) => [String(i + 1), number(p.x), number(p.y), ...(weight ? [number(p.w)] : [])]),\n  };\n  const current = cursor.active === null ? undefined : points[cursor.active];\n  const dots = showPoints ?? points.length <= 300;\n\n  return (\n    <div data-slot=\"density-chart\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      <ChartContainer aspect={aspect} height={height} table={table} announcement={cursor.keyboard && current ? `${names.x} ${number(current.x)}, ${names.y} ${number(current.y)}` : \"\"}>\n        {({ width, height: plotHeight }) => {\n          if (points.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const top = 22;\n          const bottom = 44;\n          const xs = points.map((p) => p.x);\n          const ys = points.map((p) => p.y);\n          const sy = chartLinear(Math.min(...ys), Math.max(...ys), [plotHeight - bottom, top]);\n          const axisY = formatValue ?? axisNumberFormatter(Math.max(...ys.map(Math.abs)), locale);\n          const left = widestText(sy.ticks.map(axisY)) + 12;\n          const right = 12;\n          const sx = chartLinear(Math.min(...xs), Math.max(...xs), [left, width - right], 80);\n          const axisX = formatValue ?? axisNumberFormatter(Math.max(...xs.map(Math.abs)), locale);\n          const placed = points.map((p) => ({ p, px: sx.scale(p.x), py: sy.scale(p.y) }));\n          const contours = contourDensity<(typeof placed)[number]>()\n            .x((d) => d.px)\n            .y((d) => d.py)\n            .weight((d) => d.p.w)\n            .size([width, plotHeight])\n            .bandwidth(bandwidth)\n            .thresholds(levels)(placed);\n          const highest = Math.max(1e-12, ...contours.map((c) => c.value));\n          const finder = Delaunay.from(\n            placed,\n            (d) => d.px,\n            (d) => d.py,\n          );\n          const onPointerMove = (event: PointerEvent<SVGSVGElement>): void => {\n            const box = event.currentTarget.getBoundingClientRect();\n            const mx = event.clientX - box.left;\n            const my = event.clientY - box.top;\n            const index = finder.find(mx, my);\n            const hit = placed[index];\n            cursor.point(hit && Math.hypot(hit.px - mx, hit.py - my) <= 24 ? index : null);\n          };\n          const shown = cursor.active === null ? undefined : placed[cursor.active];\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps} onPointerMove={onPointerMove}>\n                <defs>\n                  <clipPath id={clip}>\n                    <rect x={left} y={top} width={Math.max(0, width - left - right)} height={Math.max(0, plotHeight - top - bottom)} />\n                  </clipPath>\n                </defs>\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 side=\"left\" at={left - 8} ticks={sy.ticks.map((tick) => ({ offset: sy.scale(tick), label: axisY(tick) }))} />\n                <ChartAxis side=\"bottom\" at={plotHeight - bottom + 6} ticks={sx.ticks.map((tick) => ({ offset: sx.scale(tick), label: axisX(tick) }))} />\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={0} y={10}>\n                    {names.y}\n                  </text>\n                </g>\n                <g aria-hidden=\"true\" clipPath={`url(#${clip})`}>\n                  {contours.map((contour, index) => (\n                    <path\n                      key={index}\n                      d={ringsPath(contour.coordinates)}\n                      style={{ fill: chartSequential(0.15 + 0.85 * (contour.value / highest)) }}\n                      className=\"stroke-background\"\n                      strokeWidth={0.75}\n                      fillOpacity={0.85}\n                    />\n                  ))}\n                  {dots ? placed.map((d) => <circle key={d.p.row} cx={d.px} cy={d.py} r={1.75} className=\"fill-foreground\" fillOpacity={0.55} />) : null}\n                  {shown ? <circle cx={shown.px} cy={shown.py} r={5} className={cn(\"fill-foreground stroke-background\")} strokeWidth={2} /> : null}\n                </g>\n              </ChartSvg>\n              {shown ? (\n                <ChartTooltip\n                  x={shown.px}\n                  y={shown.py}\n                  side={shown.px > width / 2 ? \"left\" : \"right\"}\n                  rows={[\n                    { label: names.x, value: number(shown.p.x) },\n                    { label: names.y, value: number(shown.p.y) },\n                  ]}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Two measures over hundreds or thousands of points, where a scatter-chart would be a blot: where the bulk lies, whether there are two clusters. For under a few hundred points use scatter-chart; for one measure's spread use histogram.",
    "example": "<DensityChart\n  label=\"Trip length against fare\"\n  data={[{ km: 2, fare: 8 }, { km: 3, fare: 10 }, { km: 2.5, fare: 9 }, { km: 12, fare: 31 }, { km: 11, fare: 29 }]}\n  x=\"km\"\n  y=\"fare\"\n  xLabel=\"Distance (km)\"\n  yLabel=\"Fare\"\n  showPoints\n/>",
    "client": true
  }
}
