{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "heat-grid",
  "title": "Heat Grid",
  "description": "Matrix heatmap holding one value per cell, with tone variants.",
  "dependencies": [
    "class-variance-authority@^0.7.1"
  ],
  "registryDependencies": [
    "@pestoui/style",
    "@pestoui/utils"
  ],
  "files": [
    {
      "path": "pestoui/components/heat-grid.tsx",
      "content": "import * as React from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"@/lib/utils\"\n\n/* Matrix heatmap — activity by day and hour, contributions by week, any dense\n   grid holding one number per cell.\n\n   The tone lands on the root as a text colour and every cell paints from\n   currentColor, which is what keeps the ramp below to five opacity steps\n   instead of five fills per tone. Written out, ten tones against five steps is\n   fifty class strings that all have to stay in sync. */\nconst heatGridVariants = cva(\"grid w-fit gap-1.5\", {\n  variants: {\n    tone: {\n      selected: \"text-selected\",\n      success: \"text-success\",\n      warning: \"text-warning\",\n      destructive: \"text-destructive\",\n      info: \"text-info\",\n      muted: \"text-muted-foreground\",\n      \"chart-1\": \"text-chart-1\",\n      \"chart-2\": \"text-chart-2\",\n      \"chart-3\": \"text-chart-3\",\n      \"chart-4\": \"text-chart-4\",\n      \"chart-5\": \"text-chart-5\",\n    },\n    /* --heat-cell is a ceiling, not a fixed size: the tracks are\n       minmax(0, var(--heat-cell)), so a matrix too wide for its container\n       shrinks its cells rather than overflowing. --heat-gap rides on the root\n       because three separate grids — cells, row labels, column labels — have to\n       space themselves identically or the labels slide off their rows.\n\n       The root's own gap is deliberately not --heat-gap: at size=\"sm\" a 2px\n       gutter would pull the header labels onto the first row of cells. */\n    size: {\n      sm: \"[--heat-cell:--spacing(3)] [--heat-gap:--spacing(0.5)]\",\n      default: \"[--heat-cell:--spacing(4)] [--heat-gap:--spacing(1)]\",\n      lg: \"[--heat-cell:--spacing(6)] [--heat-gap:--spacing(1.5)]\",\n    },\n  },\n  defaultVariants: {\n    tone: \"selected\",\n    size: \"default\",\n  },\n})\n\n/* Five discrete steps, never a continuous ramp. Mapping value → opacity\n   linearly spends most of its range inside a band the eye cannot separate, so\n   the middle of the data turns to mud; quantising first buys five categories\n   that stay apart from each other. The steps are even quintiles because the two\n   ends are what have to hold — step 1 has to clear the empty fill, step 5 has\n   to arrive at the solid tone.\n\n   Zero keeps a muted fill instead of going transparent, so a sparse matrix\n   still shows its shape rather than a scatter of floating marks.\n\n   rounded-xs holds at every cell size on purpose: tracks shrink under minmax,\n   and a radius past half the edge turns the square into a circle. */\nconst heatGridCellVariants = cva(\n  \"aspect-square rounded-xs transition-colors duration-base ease-out-expo\",\n  {\n    variants: {\n      level: {\n        0: \"bg-muted\",\n        1: \"bg-current/20\",\n        2: \"bg-current/40\",\n        3: \"bg-current/60\",\n        4: \"bg-current/80\",\n        5: \"bg-current\",\n      },\n    },\n    defaultVariants: {\n      level: 0,\n    },\n  }\n)\n\nconst HEAT_LEVELS = [0, 1, 2, 3, 4, 5] as const\nconst HEAT_STEPS = HEAT_LEVELS.length - 1\n\ntype HeatGridTone = NonNullable<VariantProps<typeof heatGridVariants>[\"tone\"]>\ntype HeatGridSize = NonNullable<VariantProps<typeof heatGridVariants>[\"size\"]>\ntype HeatGridLevel = (typeof HEAT_LEVELS)[number]\n\n/* Steps are ceilings: anything above zero lands on at least step 1, so a single\n   event in an otherwise quiet week stays visible instead of rounding back into\n   the empty fill and reading as nothing happened. */\nfunction levelOf(value: number, max: number): HeatGridLevel {\n  if (max <= 0 || value <= 0) return 0\n  const step = Math.ceil((Math.min(value, max) / max) * HEAT_STEPS)\n  return HEAT_LEVELS[Math.min(step, HEAT_STEPS)]\n}\n\n/* Counts read better whole; a 0–1 scale says nothing without the decimals. */\nfunction formatHeatValue(value: number) {\n  return Number.isInteger(value) ? String(value) : value.toFixed(2)\n}\n\ntype HeatGridProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n  /** Rows of values. Rows may differ in length — short rows leave holes. */\n  data: number[][]\n  /** Fixes the top of the scale. Omit to normalise against the data's own max. */\n  max?: number\n  /** Positional; a short array leaves the rest of the matrix unlabelled. */\n  rowLabels?: string[]\n  /** Positional, and each one sits in a single cell's track — keep them short. */\n  columnLabels?: string[]\n  /** Names the matrix in the accessible summary, e.g. \"Commits per hour\". */\n  srLabel?: string\n  /** Applied to each cell's hover title and to the range in the summary. */\n  formatValue?: (value: number) => string\n  tone?: HeatGridTone\n  size?: HeatGridSize\n}\n\nfunction HeatGrid({\n  data,\n  max,\n  rowLabels,\n  columnLabels,\n  srLabel,\n  formatValue = formatHeatValue,\n  tone = \"selected\",\n  size = \"default\",\n  className,\n  ...props\n}: HeatGridProps) {\n  /* One pass for both the column count and the auto scale. Ragged input is\n     ordinary here — a half-finished week, a sensor that dropped a sample — so\n     the matrix takes its width from the longest row and every row is walked out\n     to that width. */\n  let columns = 0\n  let dataMax = 0\n  for (const row of data) {\n    if (row.length > columns) columns = row.length\n    for (const value of row) {\n      if (Number.isFinite(value) && value > dataMax) dataMax = value\n    }\n  }\n\n  const scaleMax = max != null && Number.isFinite(max) && max > 0 ? max : dataMax\n  const hasRowLabels = rowLabels != null && rowLabels.length > 0\n  const hasColumnLabels = columnLabels != null && columnLabels.length > 0\n\n  /* repeat(0, …) is invalid and would drop the declaration entirely, taking the\n     gap and the labels' alignment down with it. */\n  const columnTemplate = `repeat(${Math.max(1, columns)}, minmax(0, var(--heat-cell)))`\n  const rowTemplate = `repeat(${Math.max(1, data.length)}, minmax(0, 1fr))`\n\n  /* role=\"img\" collapses the subtree, so the per-cell titles below never reach a\n     screen reader — they are a pointer affordance, and this string is the whole\n     spoken account of the matrix.\n\n     Dimensions and a scale range are not that account. \"7 rows by 24 columns,\n     values 0 to 12\" tells a non-sighted reader the grid exists and nothing\n     about what it shows, which is the shape of the data. Announcing all 168\n     cells is equally useless, so each row is reduced to the two facts a\n     heat map is read for: where it peaks and how loaded it is overall. */\n  const rowSummary = (row: readonly number[], index: number) => {\n    const finite = row.filter(Number.isFinite)\n    if (!finite.length) return null\n    const peak = Math.max(...finite)\n    const at = row.indexOf(peak)\n    const mean = finite.reduce((a, b) => a + b, 0) / finite.length\n    const name = rowLabels?.[index] ?? `row ${index + 1}`\n    const where = columnLabels?.[at] ?? `column ${at + 1}`\n    return `${name}: peak ${formatValue(peak)} at ${where}, average ${formatValue(\n      Math.round(mean * 100) / 100,\n    )}`\n  }\n\n  const summary = [\n    srLabel,\n    `heat map, ${data.length} rows by ${columns} columns`,\n    scaleMax > 0 ? `values 0 to ${formatValue(scaleMax)}` : \"no values\",\n    ...data.map(rowSummary),\n  ]\n    .filter(Boolean)\n    .join(\", \")\n\n  return (\n    <div\n      data-slot=\"heat-grid\"\n      data-tone={tone}\n      data-size={size}\n      role=\"img\"\n      aria-label={summary}\n      className={cn(\n        heatGridVariants({ tone, size }),\n        hasRowLabels ? \"grid-cols-[auto_minmax(0,1fr)]\" : \"grid-cols-1\",\n        className\n      )}\n      {...props}\n    >\n      {hasColumnLabels ? (\n        <>\n          {hasRowLabels ? <div aria-hidden=\"true\" /> : null}\n          <div\n            data-slot=\"heat-grid-column-labels\"\n            className=\"grid gap-(--heat-gap)\"\n            style={{ gridTemplateColumns: columnTemplate }}\n          >\n            {Array.from({ length: columns }, (_, column) => (\n              <span\n                key={column}\n                className=\"min-w-0 truncate text-center text-xs leading-none text-muted-foreground\"\n              >\n                {columnLabels?.[column] ?? \"\"}\n              </span>\n            ))}\n          </div>\n        </>\n      ) : null}\n\n      {hasRowLabels ? (\n        /* Equal fractions of the cells block's own height, which the outer grid\n           row hands over by stretching this column to match it — that is what\n           keeps a label on its row without hard-coding the cell size twice.\n\n           overflow-hidden is load-bearing, not cosmetic: it drops this column's\n           automatic minimum size to zero. Without it, a container narrow enough\n           to squeeze the cells below the label's line box would let the labels\n           set the row height instead, and every row would drift off its own\n           data. Clipped text is the better failure. */\n        <div\n          data-slot=\"heat-grid-row-labels\"\n          className=\"grid gap-(--heat-gap) overflow-hidden\"\n          style={{ gridTemplateRows: rowTemplate }}\n        >\n          {data.map((_, row) => (\n            <span\n              key={row}\n              className=\"flex items-center justify-end text-xs leading-none whitespace-nowrap text-muted-foreground\"\n            >\n              {rowLabels?.[row] ?? \"\"}\n            </span>\n          ))}\n        </div>\n      ) : null}\n\n      <div\n        data-slot=\"heat-grid-cells\"\n        className=\"grid gap-(--heat-gap)\"\n        style={{ gridTemplateColumns: columnTemplate }}\n      >\n        {data.flatMap((row, rowIndex) =>\n          Array.from({ length: columns }, (_, columnIndex) => {\n            const value = row[columnIndex]\n\n            /* A short row leaves `undefined` here and Number.isFinite turns it\n               away alongside NaN. The hole still occupies its square: a missing\n               reading is not a quiet one, and dropping the box would slide every\n               later row out from under its label. */\n            if (!Number.isFinite(value)) {\n              return (\n                <div\n                  key={`${rowIndex}-${columnIndex}`}\n                  data-slot=\"heat-grid-hole\"\n                  aria-hidden=\"true\"\n                  className=\"aspect-square\"\n                />\n              )\n            }\n\n            const level = levelOf(value, scaleMax)\n            const rowName = rowLabels?.[rowIndex] ?? `Row ${rowIndex + 1}`\n            const columnName =\n              columnLabels?.[columnIndex] ?? `Column ${columnIndex + 1}`\n\n            return (\n              <div\n                key={`${rowIndex}-${columnIndex}`}\n                data-slot=\"heat-grid-cell\"\n                data-level={level}\n                title={`${rowName}, ${columnName}: ${formatValue(value)}`}\n                className={cn(heatGridCellVariants({ level }))}\n              />\n            )\n          })\n        )}\n      </div>\n    </div>\n  )\n}\n\nexport { HeatGrid, heatGridVariants, heatGridCellVariants }\nexport type { HeatGridProps, HeatGridTone, HeatGridSize, HeatGridLevel }\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}