{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "heatmap",
  "type": "registry:component",
  "title": "Heatmap",
  "description": "A matrix of cells (day by hour, for example) coloured on one-hue scale from faint to the highlight colour, with a tooltip, arrow-key reading and a scale legend.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-scale"
  ],
  "devDependencies": [
    "@types/d3-scale"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/heatmap.tsx",
      "type": "registry:component",
      "target": "components/viz/heatmap.tsx",
      "content": "\"use client\";\n/**\n * @name heatmap\n * @category viz\n * @description A matrix of cells (day by hour, for example) coloured on one-hue scale from faint to the highlight colour, with a tooltip, arrow-key reading and a scale legend.\n * @when Spotting patterns across two categories at once: when it is busy, which pairs stand out. To compare exact amounts use bar-chart; for one row of values over time use line-chart.\n * @example\n * <Heatmap\n *   label=\"Sessions by day and hour\"\n *   data={[\n *     { day: \"Mon\", hour: \"09\", sessions: 12 },\n *     { day: \"Mon\", hour: \"10\", sessions: 30 },\n *     { day: \"Tue\", hour: \"09\", sessions: 8 },\n *     { day: \"Tue\", hour: \"10\", sessions: 21 },\n *   ]}\n *   x=\"hour\"\n *   y=\"day\"\n *   value=\"sessions\"\n * />\n */\nimport { scaleBand, scaleLinear } from \"d3-scale\";\nimport { useMemo, useState, type ComponentProps, type KeyboardEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { ChartAxis, ChartContainer, ChartSvg, ChartTooltip, estimateTextWidth, formatNumber, readNumber, type ChartFormat } from \"@/components/viz/chart\";\n\nexport type HeatmapProps<T extends object> = Omit<ComponentProps<\"div\">, \"children\"> &\n  Omit<ChartFormat, \"timeZone\"> & {\n    /** One object per cell. Pairs that are missing are drawn as empty cells. */\n    data: readonly T[];\n    /** The field for the column. */\n    x: keyof T & string;\n    /** The field for the row. */\n    y: keyof T & string;\n    /** The field that holds the cell's number. */\n    value: keyof T & string;\n    /** What the chart shows, for assistive technology. */\n    label: string;\n    /** The columns, in order. Default: in order of first appearance. */\n    xs?: readonly string[];\n    /** The rows, in order. Default: in order of first appearance. */\n    ys?: readonly string[];\n    /** The scale under the chart, with its lowest and highest values. Default true. */\n    showLegend?: boolean;\n    /** Width / height of the plot. Default: from the number of columns and rows, so cells are near square. */\n    aspect?: number;\n    /** A fixed plot height in pixels instead of a ratio. */\n    height?: number;\n  };\n\n/** The space in the surface colour between cells. */\nconst GAP = 2;\n/** Cells take the theme's roundness, halved and capped, so \"none\" is square and \"full\" stays a cell. */\nconst ROUND = \"[rx:min(calc(var(--radius)*0.5),4px)] [ry:min(calc(var(--radius)*0.5),4px)]\";\nconst LEGEND_STEPS = [0, 0.25, 0.5, 0.75, 1];\n\n/**\n * One hue, by amount: a straight line through OKLab (the rectangular form of oklch) from the muted surface to\n * the highlight colour, so the hue holds and only lightness and chroma move. In the light theme more is\n * darker, in the dark theme more is lighter: either way, more contrast with the ground means more. The\n * lowest step is not the surface itself, so a low value still reads as a cell.\n */\nfunction heat(amount: number): string {\n  return `color-mix(in oklab, var(--highlight) ${Math.round(14 + 86 * Math.max(0, Math.min(1, amount)))}%, var(--muted))`;\n}\n\nexport function Heatmap<T extends object>({ data, x, y, value, label, xs, ys, showLegend = true, aspect, height, locale, formatValue, className, ...props }: HeatmapProps<T>) {\n  const [active, setActive] = useState<{ column: number; row: number } | null>(null);\n  const [keyboard, setKeyboard] = useState(false);\n\n  const model = useMemo(() => {\n    const read = (row: T, key: string): string => String((row as Record<string, unknown>)[key] ?? \"\");\n    const columns = xs ?? [...new Set(data.map((row) => read(row, x)))];\n    const rows = ys ?? [...new Set(data.map((row) => read(row, y)))];\n    const cells = new Map<string, number>();\n    let low = Infinity;\n    let high = -Infinity;\n    for (const row of data) {\n      const amount = readNumber(row, value);\n      if (amount === null) continue;\n      cells.set(`${read(row, y)}\\u0000${read(row, x)}`, amount);\n      low = Math.min(low, amount);\n      high = Math.max(high, amount);\n    }\n    if (low === Infinity) {\n      low = 0;\n      high = 0;\n    }\n    return { columns, rows, cells, low, high };\n  }, [data, x, y, value, xs, ys]);\n\n  const { columns, rows, cells, low, high } = model;\n  const number = formatValue ?? ((amount: number) => formatNumber(amount, locale));\n  const cell = (row: number, column: number): number | undefined => cells.get(`${rows[row] ?? \"\"}\\u0000${columns[column] ?? \"\"}`);\n  const level = scaleLinear().domain(low === high ? [low - 1, high] : [low, high]).range([0, 1]).clamp(true);\n  const table = {\n    caption: label,\n    columns: [y, ...columns],\n    rows: rows.map((name, row) => [\n      name,\n      ...columns.map((_, column) => {\n        const amount = cell(row, column);\n        return amount === undefined ? \"\" : number(amount);\n      }),\n    ]),\n  };\n  const activeValue = active ? cell(active.row, active.column) : undefined;\n  const activeTitle = active ? `${rows[active.row] ?? \"\"} · ${columns[active.column] ?? \"\"}` : \"\";\n  const activeText = activeValue === undefined ? \"No value\" : number(activeValue);\n  const announcement = keyboard && active ? `${activeTitle}: ${activeText}` : \"\";\n\n  const move = (columnStep: number, rowStep: number): void => {\n    if (columns.length === 0 || rows.length === 0) return;\n    setKeyboard(true);\n    setActive((current) =>\n      current === null\n        ? { column: 0, row: 0 }\n        : { column: Math.max(0, Math.min(columns.length - 1, current.column + columnStep)), row: Math.max(0, Math.min(rows.length - 1, current.row + rowStep)) },\n    );\n  };\n  const onKeyDown = (event: KeyboardEvent<SVGSVGElement>): void => {\n    if (event.key === \"ArrowRight\") move(1, 0);\n    else if (event.key === \"ArrowLeft\") move(-1, 0);\n    else if (event.key === \"ArrowDown\") move(0, 1);\n    else if (event.key === \"ArrowUp\") move(0, -1);\n    else if (event.key === \"Home\") move(-columns.length, 0);\n    else if (event.key === \"End\") move(columns.length, 0);\n    else if (event.key === \"Escape\") setActive(null);\n    else return;\n    event.preventDefault();\n  };\n\n  const widest = (texts: readonly string[]): number => Math.ceil(Math.max(0, ...texts.map((text) => estimateTextWidth(text))));\n  const shape = aspect ?? Math.max(1, Math.min(6, (columns.length + 2) / (rows.length + 1.5)));\n\n  return (\n    <div data-slot=\"heatmap\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      <ChartContainer aspect={shape} height={height} table={table} announcement={announcement}>\n        {(size) => {\n          if (columns.length === 0 || rows.length === 0) {\n            return <p className=\"absolute inset-0 flex items-center justify-center text-sm text-muted-foreground\">No data</p>;\n          }\n          const left = Math.min(Math.round(size.width * 0.3), widest(rows) + 10);\n          const bottom = 24;\n          const bandX = scaleBand<number>().domain(columns.map((_, index) => index)).range([left, size.width]);\n          const bandY = scaleBand<number>().domain(rows.map((_, index) => index)).range([0, size.height - bottom]);\n          const cellWidth = Math.max(1, bandX.bandwidth() - GAP);\n          const cellHeight = Math.max(1, bandY.bandwidth() - GAP);\n          // Column names that would run into each other are thinned out; every name stays in the table.\n          const every = Math.max(1, Math.ceil((widest(columns) + 8) / bandX.step()));\n          const fits = Math.max(3, Math.floor((left - 10) / (12 * 0.58)));\n          const activeX = active ? (bandX(active.column) ?? 0) + bandX.bandwidth() / 2 : 0;\n          const activeY = active ? (bandY(active.row) ?? 0) + bandY.bandwidth() / 2 : 0;\n          return (\n            <>\n              <ChartSvg\n                label={label}\n                width={size.width}\n                height={size.height}\n                interactive\n                onKeyDown={onKeyDown}\n                onPointerLeave={() => setActive(null)}\n                onFocus={(event) => {\n                  if (event.currentTarget.matches(\":focus-visible\")) move(0, 0);\n                }}\n                onBlur={() => setActive(null)}\n              >\n                <ChartAxis side=\"left\" at={left - 8} ticks={rows.map((name, index) => ({ offset: (bandY(index) ?? 0) + bandY.bandwidth() / 2, label: name.length > fits ? `${name.slice(0, fits - 1)}…` : name }))} />\n                <ChartAxis\n                  side=\"bottom\"\n                  at={size.height - bottom + 6}\n                  ticks={columns.flatMap((name, index) => (index % every === 0 ? [{ offset: (bandX(index) ?? 0) + bandX.bandwidth() / 2, label: name }] : []))}\n                />\n                <g aria-hidden=\"true\">\n                  {rows.map((_, row) =>\n                    columns.map((__, column) => {\n                      const amount = cell(row, column);\n                      const box = { x: (bandX(column) ?? 0) + GAP / 2, y: (bandY(row) ?? 0) + GAP / 2, width: cellWidth, height: cellHeight };\n                      return (\n                        <g\n                          key={`${row}:${column}`}\n                          onPointerEnter={() => {\n                            setKeyboard(false);\n                            setActive({ column, row });\n                          }}\n                        >\n                          {/* The hit area is the whole band, gap included. */}\n                          <rect x={bandX(column) ?? 0} y={bandY(row) ?? 0} width={bandX.bandwidth()} height={bandY.bandwidth()} fill=\"transparent\" />\n                          {amount === undefined ? <rect {...box} fill=\"none\" className={cn(\"stroke-border\", ROUND)} strokeWidth={1} /> : <rect {...box} className={ROUND} style={{ fill: heat(level(amount)) }} />}\n                        </g>\n                      );\n                    }),\n                  )}\n                  {active ? (\n                    <rect\n                      x={(bandX(active.column) ?? 0) + GAP / 2}\n                      y={(bandY(active.row) ?? 0) + GAP / 2}\n                      width={cellWidth}\n                      height={cellHeight}\n                      fill=\"none\"\n                      className={cn(\"pointer-events-none stroke-foreground\", ROUND)}\n                      strokeWidth={2}\n                    />\n                  ) : null}\n                </g>\n              </ChartSvg>\n              {active ? <ChartTooltip x={activeX} y={activeY} side={activeX > size.width / 2 ? \"left\" : \"right\"} title={activeTitle} rows={[{ label: value, value: activeText }]} /> : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n      {showLegend && columns.length > 0 ? (\n        <div data-slot=\"heatmap-legend\" aria-hidden=\"true\" className=\"flex items-center gap-2 text-xs text-muted-foreground tabular-nums\">\n          <span>{number(low)}</span>\n          <span className=\"flex gap-0.5\">\n            {LEGEND_STEPS.map((step) => (\n              <span key={step} className=\"size-3 rounded-[min(calc(var(--radius)*0.5),4px)]\" style={{ backgroundColor: heat(step) }} />\n            ))}\n          </span>\n          <span>{number(high)}</span>\n        </div>\n      ) : null}\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Spotting patterns across two categories at once: when it is busy, which pairs stand out. To compare exact amounts use bar-chart; for one row of values over time use line-chart.",
    "example": "<Heatmap\n  label=\"Sessions by day and hour\"\n  data={[\n    { day: \"Mon\", hour: \"09\", sessions: 12 },\n    { day: \"Mon\", hour: \"10\", sessions: 30 },\n    { day: \"Tue\", hour: \"09\", sessions: 8 },\n    { day: \"Tue\", hour: \"10\", sessions: 21 },\n  ]}\n  x=\"hour\"\n  y=\"day\"\n  value=\"sessions\"\n/>",
    "client": true
  }
}
