{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "choropleth",
  "type": "registry:component",
  "title": "Choropleth",
  "description": "A geo-map layer that colours each region by a number, on one hue from faint to strong, on two hues either side of a midpoint, or in classes with stated edges; with a legend that says each step's range in words and a table of every region's value.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-geo"
  ],
  "devDependencies": [
    "@types/d3-geo"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn",
    "@rivier-ui/geo-map"
  ],
  "files": [
    {
      "path": "registry/viz/choropleth.tsx",
      "type": "registry:component",
      "target": "components/viz/choropleth.tsx",
      "content": "\"use client\";\n/**\n * @name choropleth\n * @category viz\n * @description A geo-map layer that colours each region by a number, on one hue from faint to strong, on two hues either side of a midpoint, or in classes with stated edges; with a legend that says each step's range in words and a table of every region's value.\n * @when Showing a rate or a share that varies by region: turnout by district, rainfall by county. Use rates, not raw counts (large regions look important whatever their count); for counts use geo-markers bubbles. Goes inside geo-map.\n * @example\n * const scale = choroplethScale(regions.features.map((f) => f.properties.rate), { thresholds: [10, 20, 30] });\n * <GeoMap label=\"Rate by region\" fit={regions}>\n *   <Choropleth label=\"Rate by region\" data={regions} value={(f) => f.properties?.rate} name={(f) => f.properties?.name} scale={scale} />\n * </GeoMap>\n * <ChoroplethLegend title=\"Rate (%)\" scale={scale} />\n */\nimport type { ExtendedFeature, ExtendedFeatureCollection } from \"d3-geo\";\nimport type { ComponentProps } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { chartDiverging, chartSequential, formatNumber } from \"@/components/viz/chart\";\nimport { GeoLayer, GeoTable, useGeoMap } from \"@/components/viz/geo-map\";\n\nexport type ChoroplethScaleOptions = {\n  /** \"sequential\": one hue, more is stronger. \"diverging\": two hues either side of `midpoint`. Ignored with `thresholds`. */\n  kind?: \"sequential\" | \"diverging\";\n  /** Class edges, low to high: [10, 20, 30] makes four classes (below 10, 10 to 20, 20 to 30, 30 and above). */\n  thresholds?: readonly number[];\n  /** The values at the ends of the scale. Default: the data's own. */\n  domain?: readonly [number, number];\n  /** The neutral middle of a diverging scale. Default 0. */\n  midpoint?: number;\n};\n\nexport type ChoroplethStep = { color: string; from: number | null; to: number | null };\n\nexport type ChoroplethScale = {\n  color: (value: number) => string;\n  /** The steps a legend shows, low to high. */\n  steps: readonly ChoroplethStep[];\n  kind: \"sequential\" | \"diverging\" | \"classes\";\n};\n\n/** The colour scale of a choropleth, to share between the layer and its legend. */\nexport function choroplethScale(values: readonly (number | null | undefined)[], options: ChoroplethScaleOptions = {}): ChoroplethScale {\n  const numbers = values.filter((v): v is number => typeof v === \"number\" && Number.isFinite(v));\n  const low = options.domain?.[0] ?? (numbers.length ? Math.min(...numbers) : 0);\n  const high = options.domain?.[1] ?? (numbers.length ? Math.max(...numbers) : 1);\n  if (options.thresholds && options.thresholds.length > 0) {\n    const edges = [...options.thresholds].sort((a, b) => a - b);\n    const classes = edges.length + 1;\n    const colorOf = (index: number): string => chartSequential(classes === 1 ? 1 : index / (classes - 1));\n    return {\n      kind: \"classes\",\n      color: (value) => colorOf(edges.filter((edge) => value >= edge).length),\n      steps: Array.from({ length: classes }, (_, i) => ({ color: colorOf(i), from: i === 0 ? null : (edges[i - 1] ?? null), to: i === classes - 1 ? null : (edges[i] ?? null) })),\n    };\n  }\n  if (options.kind === \"diverging\") {\n    const mid = options.midpoint ?? 0;\n    const reach = Math.max(Math.abs(high - mid), Math.abs(low - mid)) || 1;\n    return {\n      kind: \"diverging\",\n      color: (value) => chartDiverging((value - mid) / reach),\n      steps: [-1, -0.5, 0, 0.5, 1].map((share) => ({ color: chartDiverging(share), from: mid + share * reach, to: null })),\n    };\n  }\n  const span = high - low || 1;\n  return {\n    kind: \"sequential\",\n    color: (value) => chartSequential((value - low) / span),\n    steps: [0, 0.25, 0.5, 0.75, 1].map((share) => ({ color: chartSequential(share), from: low + share * span, to: null })),\n  };\n}\n\nexport type ChoroplethProps = Omit<ComponentProps<\"g\">, \"children\" | \"name\" | \"scale\"> & {\n  /** The layer's name, for screen readers and the table. */\n  label: string;\n  data: ExtendedFeatureCollection;\n  /** Each region's number; null or undefined for no value. */\n  value: (feature: ExtendedFeature) => number | null | undefined;\n  /** Each region's name. */\n  name: (feature: ExtendedFeature) => string;\n  /** The colour scale; make it with choroplethScale to share it with the legend. Default: sequential over the data. */\n  scale?: ChoroplethScale;\n  /** The name of the value in the tooltip and the table. Default \"Value\". */\n  valueLabel?: string;\n  /** Said for a region with no value. Default \"No value\". */\n  noValue?: string;\n  formatValue?: (value: number) => string;\n};\n\nexport function Choropleth({ label, data, value, name, scale, valueLabel = \"Value\", noValue = \"No value\", formatValue, className, ...props }: ChoroplethProps) {\n  const { path, locale } = useGeoMap(\"Choropleth\");\n  const number = formatValue ?? ((amount: number) => formatNumber(amount, locale));\n  const regions = data.features.map((feature) => {\n    const amount = value(feature);\n    return { feature, name: name(feature), value: typeof amount === \"number\" && Number.isFinite(amount) ? amount : null, d: path(feature) ?? \"\", centre: path.centroid(feature) };\n  });\n  const colors = scale ?? choroplethScale(regions.map((region) => region.value));\n  const order = regions.map((_, i) => i).sort((a, b) => (regions[a]?.name ?? \"\").localeCompare(regions[b]?.name ?? \"\", locale));\n  const items = order.map((i) => {\n    const region = regions[i];\n    return {\n      x: region?.centre[0] ?? 0,\n      y: region?.centre[1] ?? 0,\n      title: region?.name ?? \"\",\n      rows: [{ label: valueLabel, value: region?.value === null || region === undefined ? noValue : number(region.value) }],\n    };\n  });\n  return (\n    <>\n      <GeoLayer label={label} items={items} className={className} {...props}>\n        {(active, point) => (\n          <g data-slot=\"choropleth\" aria-hidden=\"true\">\n            {order.map((i, position) => {\n              const region = regions[i];\n              if (!region || !region.d) return null;\n              return (\n                <path\n                  key={i}\n                  d={region.d}\n                  style={region.value === null ? undefined : { fill: colors.color(region.value) }}\n                  className={cn(\"stroke-background\", region.value === null && \"fill-none stroke-border-strong\")}\n                  strokeWidth={region.value === null ? 0.75 : 1}\n                  strokeDasharray={region.value === null ? \"3 2\" : undefined}\n                  onPointerEnter={() => point(position)}\n                />\n              );\n            })}\n            {active !== null && regions[order[active] ?? -1] ? <path d={regions[order[active] ?? -1]?.d ?? \"\"} fill=\"none\" className=\"pointer-events-none stroke-foreground\" strokeWidth={2} /> : null}\n          </g>\n        )}\n      </GeoLayer>\n      <GeoTable caption={label} columns={[label, valueLabel]} rows={order.map((i) => [regions[i]?.name ?? \"\", regions[i]?.value === null ? noValue : number(regions[i]?.value ?? 0)])} />\n    </>\n  );\n}\n\nexport type ChoroplethLegendProps = ComponentProps<\"div\"> & {\n  /** What the colours measure, with its unit. */\n  title: string;\n  scale: ChoroplethScale;\n  /** Show the no-value swatch, with these words. Leave out to hide it. */\n  noValue?: string;\n  locale?: string;\n  formatValue?: (value: number) => string;\n  /** Words for \"below\" and \"and above\" in class ranges. */\n  labels?: { below: (value: string) => string; above: (value: string) => string };\n};\n\nconst RANGE_WORDS = { below: (value: string) => `Below ${value}`, above: (value: string) => `${value} and above` };\n\n/** The key to a choropleth: each step's colour with its range in words, so no value rests on colour alone. */\nexport function ChoroplethLegend({ title, scale, noValue, locale = \"en-US\", formatValue, labels = RANGE_WORDS, className, ...props }: ChoroplethLegendProps) {\n  const number = formatValue ?? ((value: number) => formatNumber(value, locale));\n  const text = (step: ChoroplethStep): string => {\n    if (scale.kind !== \"classes\") return step.from === null ? \"\" : number(step.from);\n    if (step.from === null && step.to !== null) return labels.below(number(step.to));\n    if (step.to === null && step.from !== null) return labels.above(number(step.from));\n    return `${number(step.from ?? 0)} – ${number(step.to ?? 0)}`;\n  };\n  return (\n    <div data-slot=\"choropleth-legend\" className={cn(\"flex flex-col gap-1.5 text-xs\", className)} {...props}>\n      <span className=\"font-medium text-foreground\">{title}</span>\n      <ul className={cn(\"flex flex-wrap gap-x-3 gap-y-1 text-muted-foreground\", scale.kind !== \"classes\" && \"gap-x-0\")}>\n        {scale.steps.map((step, index) => (\n          <li key={index} className={cn(\"flex items-center gap-1.5\", scale.kind !== \"classes\" && \"flex-col items-start gap-0.5\")}>\n            <span aria-hidden=\"true\" className={cn(\"h-3 rounded-[min(var(--radius),3px)]\", scale.kind === \"classes\" ? \"w-4\" : \"w-10\")} style={{ backgroundColor: step.color }} />\n            <span className=\"tabular-nums\">{text(step)}</span>\n          </li>\n        ))}\n        {noValue ? (\n          <li className=\"flex items-center gap-1.5 self-start\">\n            <span aria-hidden=\"true\" className=\"h-3 w-4 rounded-[min(var(--radius),3px)] border border-dashed border-border-strong\" />\n            <span>{noValue}</span>\n          </li>\n        ) : null}\n      </ul>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Showing a rate or a share that varies by region: turnout by district, rainfall by county. Use rates, not raw counts (large regions look important whatever their count); for counts use geo-markers bubbles. Goes inside geo-map.",
    "example": "const scale = choroplethScale(regions.features.map((f) => f.properties.rate), { thresholds: [10, 20, 30] });\n<GeoMap label=\"Rate by region\" fit={regions}>\n  <Choropleth label=\"Rate by region\" data={regions} value={(f) => f.properties?.rate} name={(f) => f.properties?.name} scale={scale} />\n</GeoMap>\n<ChoroplethLegend title=\"Rate (%)\" scale={scale} />",
    "client": true
  }
}
