{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "geo-hexbin",
  "type": "registry:component",
  "title": "Geo Hexbin",
  "description": "A geo-map layer that gathers many points into hexagons or squares of equal size on screen, each coloured on one hue by how many points (or how much weight) fall in it, re-gathered as the map zooms; each cell read by arrow keys and listed in a table.",
  "categories": [
    "viz"
  ],
  "dependencies": [],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn",
    "@rivier-ui/geo-map"
  ],
  "files": [
    {
      "path": "registry/viz/geo-hexbin.tsx",
      "type": "registry:component",
      "target": "components/viz/geo-hexbin.tsx",
      "content": "\"use client\";\n/**\n * @name geo-hexbin\n * @category viz\n * @description A geo-map layer that gathers many points into hexagons or squares of equal size on screen, each coloured on one hue by how many points (or how much weight) fall in it, re-gathered as the map zooms; each cell read by arrow keys and listed in a table.\n * @when Thousands of points where single marks would pile up: sightings, incidents, trips, addresses. For a few dozen named places use geo-markers; for values that belong to regions use choropleth. Goes inside geo-map.\n * @example\n * <GeoMap label=\"Sightings\" fit={area}>\n *   <GeoFeatures data={area} />\n *   <GeoHexbin label=\"Sightings\" points={sightings} radius={14} valueLabel=\"Sightings\" />\n * </GeoMap>\n */\nimport type { ComponentProps } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { chartSequential, formatNumber } from \"@/components/viz/chart\";\nimport { GeoLayer, GeoTable, useGeoMap } from \"@/components/viz/geo-map\";\n\nexport type GeoWeightedPoint = { lon: number; lat: number /** How much the point counts. Default 1. */; weight?: number };\n\nexport type GeoHexbinProps = Omit<ComponentProps<\"g\">, \"children\" | \"points\"> & {\n  label: string;\n  points: readonly GeoWeightedPoint[];\n  /** \"hex\" (the default: every neighbour the same distance away) or \"square\". */\n  shape?: \"hex\" | \"square\";\n  /** The cell's size in pixels: a hexagon's radius, half a square's side. Default 14. */\n  radius?: number;\n  /** The name of the cell's total in the tooltip and the table. Default \"Count\". */\n  valueLabel?: string;\n  /** Words for the table's column heads. */\n  labels?: { cell: string; latitude: string; longitude: string };\n  /** The scale under the map, in the overlay. Default true. */\n  showLegend?: boolean;\n  formatValue?: (value: number) => string;\n};\n\nconst LABELS = { cell: \"Cell\", latitude: \"Latitude\", longitude: \"Longitude\" };\n\ntype Cell = { x: number; y: number; total: number; count: number };\n\n/** The centre of the hexagon a pixel falls in (pointy-top hexagons in offset rows), as in d3-hexbin. */\nfunction hexCentre(x: number, y: number, dx: number, dy: number): [number, number] {\n  const py = y / dy;\n  let pj = Math.round(py);\n  const px = x / dx - (pj & 1) / 2;\n  let pi = Math.round(px);\n  const py1 = py - pj;\n  if (Math.abs(py1) * 3 > 1) {\n    const px1 = px - pi;\n    const pi2 = pi + (px < pi ? -1 : 1) / 2;\n    const pj2 = pj + (py < pj ? -1 : 1);\n    const px2 = px - pi2;\n    const py2 = py - pj2;\n    if (px1 * px1 + py1 * py1 > px2 * px2 + py2 * py2) {\n      pi = pi2 + ((pj & 1) !== 0 ? 1 : -1) / 2;\n      pj = pj2;\n    }\n  }\n  return [(pi + (pj & 1) / 2) * dx, pj * dy];\n}\n\nexport function GeoHexbin({ label, points, shape = \"hex\", radius = 14, valueLabel = \"Count\", labels = LABELS, showLegend = true, formatValue, className, ...props }: GeoHexbinProps) {\n  const { projection, width, height, locale } = useGeoMap(\"GeoHexbin\");\n  const number = formatValue ?? ((amount: number) => formatNumber(amount, locale));\n  const dx = shape === \"hex\" ? radius * 2 * Math.sin(Math.PI / 3) : radius * 2;\n  const dy = shape === \"hex\" ? radius * 1.5 : radius * 2;\n  const bins = new Map<string, Cell>();\n  for (const point of points) {\n    const at = projection([point.lon, point.lat]);\n    if (!at || at[0] < -radius || at[1] < -radius || at[0] > width + radius || at[1] > height + radius) continue;\n    const [cx, cy] = shape === \"hex\" ? hexCentre(at[0], at[1], dx, dy) : [Math.floor(at[0] / dx) * dx + dx / 2, Math.floor(at[1] / dy) * dy + dy / 2];\n    const key = `${Math.round(cx)}:${Math.round(cy)}`;\n    const cell = bins.get(key) ?? { x: cx, y: cy, total: 0, count: 0 };\n    cell.total += point.weight ?? 1;\n    cell.count += 1;\n    bins.set(key, cell);\n  }\n  // Reading order: top to bottom, then start to end.\n  const cells = [...bins.values()].sort((a, b) => a.y - b.y || a.x - b.x);\n  const highest = Math.max(1e-9, ...cells.map((c) => c.total));\n  const hexagon = Array.from({ length: 6 }, (_, i) => {\n    const angle = Math.PI / 6 + (i * Math.PI) / 3;\n    return `${(Math.cos(angle) * (radius - 0.75)).toFixed(2)},${(Math.sin(angle) * (radius - 0.75)).toFixed(2)}`;\n  }).join(\" \");\n  const coordinate = (value: number): string => formatNumber(value, locale, { maximumFractionDigits: 2 });\n  const where = (cell: Cell): [number, number] | null => projection.invert?.([cell.x, cell.y]) ?? null;\n  const items = cells.map((cell, index) => {\n    const at = where(cell);\n    return { x: cell.x, y: cell.y, title: at ? `${coordinate(at[1])}, ${coordinate(at[0])}` : `${labels.cell} ${index + 1}`, rows: [{ label: valueLabel, value: number(cell.total) }] };\n  });\n  return (\n    <>\n      <GeoLayer label={label} items={items} className={className} {...props}>\n        {(active, point) => (\n          <g data-slot=\"geo-hexbin\" aria-hidden=\"true\">\n            {cells.map((cell, index) =>\n              shape === \"hex\" ? (\n                <polygon\n                  key={index}\n                  points={hexagon}\n                  transform={`translate(${cell.x},${cell.y})`}\n                  style={{ fill: chartSequential(0.15 + 0.85 * (cell.total / highest)) }}\n                  className={cn(\"stroke-background\", active === index && \"stroke-foreground\")}\n                  strokeWidth={active === index ? 2 : 0.75}\n                  fillOpacity={0.9}\n                  onPointerEnter={() => point(index)}\n                />\n              ) : (\n                <rect\n                  key={index}\n                  x={cell.x - radius + 0.75}\n                  y={cell.y - radius + 0.75}\n                  width={radius * 2 - 1.5}\n                  height={radius * 2 - 1.5}\n                  style={{ fill: chartSequential(0.15 + 0.85 * (cell.total / highest)) }}\n                  className={cn(\"stroke-background [rx:min(var(--radius),2px)]\", active === index && \"stroke-foreground\")}\n                  strokeWidth={active === index ? 2 : 0.75}\n                  fillOpacity={0.9}\n                  onPointerEnter={() => point(index)}\n                />\n              ),\n            )}\n          </g>\n        )}\n      </GeoLayer>\n      {showLegend && cells.length > 0 ? (\n        <g data-slot=\"geo-hexbin-legend\" aria-hidden=\"true\" transform={`translate(${width - 132},${height - 24})`}>\n          <rect x={-6} y={-6} width={130} height={26} className=\"fill-background [rx:min(var(--radius),4px)]\" fillOpacity={0.85} />\n          {[0, 0.25, 0.5, 0.75, 1].map((share, i) => (\n            <rect key={i} x={i * 14} y={0} width={12} height={12} style={{ fill: chartSequential(0.15 + 0.85 * share) }} className=\"[rx:min(var(--radius),2px)]\" />\n          ))}\n          <text x={74} y={6} dy=\"0.32em\" className=\"fill-foreground text-xs tabular-nums\">\n            {number(highest)}\n          </text>\n        </g>\n      ) : null}\n      <GeoTable\n        caption={label}\n        columns={[labels.latitude, labels.longitude, valueLabel]}\n        rows={cells.map((cell) => {\n          const at = where(cell);\n          return [at ? coordinate(at[1]) : \"\", at ? coordinate(at[0]) : \"\", number(cell.total)];\n        })}\n      />\n    </>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Thousands of points where single marks would pile up: sightings, incidents, trips, addresses. For a few dozen named places use geo-markers; for values that belong to regions use choropleth. Goes inside geo-map.",
    "example": "<GeoMap label=\"Sightings\" fit={area}>\n  <GeoFeatures data={area} />\n  <GeoHexbin label=\"Sightings\" points={sightings} radius={14} valueLabel=\"Sightings\" />\n</GeoMap>",
    "client": true
  }
}
