{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "heatmap",
  "title": "Heatmap",
  "description": "Primitives for heatmaps: a single-hue colour scale, a keyboard-readable grid of squares or dots with the shared chart tooltip, optional bars above its columns, dots on flagged cells, a ripple out from one cell, and a legend.",
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/chart.json",
    "https://www.dashboardblocks.com/r/radix/format.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/heatmap.tsx",
      "content": "'use client'\n\nimport {\n  Skeleton,\n  useBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport {\n  ChartFloatingTooltip,\n  ChartPlaceholder,\n  ChartTooltipItem,\n  type ChartValueFormatter,\n  TinyBarChart,\n} from '@/registry/components/dashboardblocks/chart'\nimport { formatCompact, formatNumber } from '@/registry/lib/dashboardblocks/format'\nimport {\n  type CSSProperties,\n  type FocusEvent,\n  Fragment,\n  type KeyboardEvent,\n  type ReactNode,\n  useEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\ntype HeatmapValue = number | null\n\ntype HeatmapFormatter = (value: number) => string\n\ninterface HeatmapCellPosition {\n  column: number\n  row: number\n}\n\ninterface ActiveCell extends HeatmapCellPosition {\n  flip: boolean\n  x: number\n  y: number\n}\n\nconst RIPPLE_REACH = 5.5\n\nconst rippleStyles = `\n  @keyframes dashboardblocks-heatmap-ripple {\n    0% { opacity: 0; transform: scale(1); }\n    20% { opacity: var(--heatmap-ripple-peak); transform: scale(var(--heatmap-ripple-scale)); }\n    100% { opacity: 0; transform: scale(1); }\n  }\n  [data-heatmap-ripple] {\n    animation: dashboardblocks-heatmap-ripple 1.1s ease-out both;\n    opacity: 0;\n  }\n  @media (prefers-reduced-motion: reduce) {\n    [data-heatmap-ripple] { animation: none; }\n  }\n`\n\nfunction getHeatColor(t: number, color = 'var(--color-chart-2)') {\n  const share = Math.round(8 + Math.min(1, Math.max(0, t)) * 62)\n  return `color-mix(in oklab, ${color} ${share}%, var(--color-muted))`\n}\n\nfunction getExtent(values: HeatmapValue[][]) {\n  let min = Infinity\n  let max = -Infinity\n  for (const row of values) {\n    for (const value of row) {\n      if (value === null) continue\n      min = Math.min(min, value)\n      max = Math.max(max, value)\n    }\n  }\n  return min === Infinity ? { max: 0, min: 0 } : { max, min }\n}\n\nfunction getPeak(values: HeatmapValue[][]) {\n  let peak: (HeatmapCellPosition & { value: number }) | null = null\n  values.forEach((row, rowIndex) =>\n    row.forEach((value, column) => {\n      if (value !== null && (peak === null || value > peak.value)) {\n        peak = { column, row: rowIndex, value }\n      }\n    }),\n  )\n  return peak as (HeatmapCellPosition & { value: number }) | null\n}\n\nfunction getColumnTotals(values: HeatmapValue[][]) {\n  const totals: number[] = []\n  for (const row of values) {\n    row.forEach((value, column) => {\n      totals[column] = (totals[column] ?? 0) + (value ?? 0)\n    })\n  }\n  return totals\n}\n\ninterface HeatmapColumnSummary {\n  format?: ChartValueFormatter\n  /** Draws this bar in full colour, with its value above it. */\n  highlightIndex?: number\n  /** Names the bars for screen readers, such as `Sessions by hour, all week`. */\n  label: string\n  /** Names each bar in its tooltip; defaults to the column labels. */\n  labels?: string[]\n  /** One per column, such as the column's total. */\n  values: number[]\n}\n\ntype HeatmapShape = 'dot' | 'square'\n\ninterface HeatmapRipple extends HeatmapCellPosition {\n  /** Change it to ripple again. */\n  key: number\n}\n\ninterface HeatmapGridProps {\n  /** A sentence under the grid, such as the busiest cell. */\n  children?: ReactNode\n  className?: string\n  cellClassName?: string\n  cellLabels?: boolean\n  /** Names a cell in its tooltip, such as `Tue, 14:00–15:00`. */\n  cellName: (position: HeatmapCellPosition) => string\n  /** @default 'var(--color-chart-2)' */\n  color?: string\n  columnLabelEvery?: number\n  columns: string[]\n  /** Bars above the grid, lined up with its columns. */\n  columnSummary?: HeatmapColumnSummary\n  /** What screen readers say for a cell; defaults to its name and value. */\n  describe?: (position: HeatmapCellPosition, value: HeatmapValue) => string\n  /** Marks a cell with a dot, such as one over a target; name the dot with `HeatmapLegend`'s `flag`. */\n  flagged?: (position: HeatmapCellPosition, value: number) => boolean\n  footer?: ReactNode\n  format?: HeatmapFormatter\n  label: string\n  /** Fixes the colour scale. */\n  max?: number\n  min?: number\n  /** Keeps cells legible in narrow cards: below this width the grid scrolls sideways, starting at the end (the most recent columns). */\n  minWidth?: string\n  /** Ripples out from this cell over its neighbours each time `key` changes, such as when new events land on today. */\n  ripple?: HeatmapRipple\n  rowHeader: string\n  rowLabelClassName?: string\n  /** While loading with none, five blank rows are sketched. */\n  rows: string[]\n  /** Full row names for assistive technology, when `rows` are abbreviated or blank. */\n  rowNames?: string[]\n  /** Turns a value into its shade, from 0 to 1; by default its place between `min` and `max`. Return steps of 0.25 to match `HeatmapLegend`. */\n  scale?: (value: number) => number\n  /** @default 'square' */\n  shape?: HeatmapShape\n  /** Names the value in the tooltip, such as `Sessions`. */\n  valueName?: string\n  values: HeatmapValue[][]\n}\n\nfunction HeatmapGrid({\n  cellClassName,\n  cellLabels = false,\n  cellName,\n  children,\n  className,\n  color,\n  columnLabelEvery = 1,\n  columns,\n  columnSummary,\n  describe,\n  flagged,\n  footer,\n  format = (value) => formatNumber(value),\n  label,\n  max: maxProp,\n  min: minProp,\n  minWidth,\n  ripple,\n  rowHeader,\n  rowLabelClassName,\n  rowNames,\n  rows,\n  scale,\n  shape = 'square',\n  valueName,\n  values,\n}: HeatmapGridProps) {\n  const [active, setActive] = useState<ActiveCell | null>(null)\n  const [cursor, setCursor] = useState<HeatmapCellPosition>({\n    column: 0,\n    row: 0,\n  })\n  const frame = useRef<HTMLDivElement>(null)\n  const grid = useRef<HTMLDivElement>(null)\n  const scroller = useRef<HTMLDivElement>(null)\n  const state = useBlockState()\n\n  useEffect(() => {\n    const element = scroller.current\n    if (element) element.scrollLeft = element.scrollWidth\n  }, [state])\n\n  const stickyLabel =\n    minWidth && 'bg-background in-data-[slot=card]:bg-card sticky left-0 z-10'\n  const dot = shape === 'dot'\n\n  if (state) {\n    const sketched = rows.length > 0 ? rows : Array.from({ length: 5 }, () => '')\n    return (\n      <div aria-hidden className={cn('flex flex-col gap-3', className)}>\n        <div\n          ref={scroller}\n          className={cn(\n            minWidth && 'relative -my-1 overflow-x-auto py-1 [scrollbar-width:thin]',\n          )}\n        >\n          <div\n            className='grid gap-[3px]'\n            style={{\n              gridTemplateColumns: `auto repeat(${columns.length}, minmax(0, 1fr))`,\n              minWidth,\n            }}\n          >\n            {columnSummary && (\n              <div className='col-span-full grid grid-cols-subgrid pb-1'>\n                <span className={cn(stickyLabel)} />\n                <ChartPlaceholder className='col-span-full col-start-2' height={56} />\n              </div>\n            )}\n            <span className={cn(stickyLabel)} />\n            {columns.map((column, index) => (\n              <span\n                key={index}\n                className={cn(\n                  'text-muted-foreground overflow-visible text-xs leading-4 whitespace-nowrap tabular-nums',\n                  index === columns.length - 1 && 'flex justify-end',\n                )}\n              >\n                {index % columnLabelEvery === 0 && column}\n              </span>\n            ))}\n            {sketched.map((row, rowIndex) => (\n              <Fragment key={rowIndex}>\n                <span\n                  className={cn(\n                    'text-muted-foreground flex items-center pr-2 text-xs whitespace-nowrap',\n                    stickyLabel,\n                    rowLabelClassName,\n                  )}\n                >\n                  {row}\n                </span>\n                {columns.map((_, column) =>\n                  state === 'loading' ? (\n                    <Skeleton\n                      key={column}\n                      className={cn(\n                        'min-h-3',\n                        dot ? 'scale-70 rounded-full' : 'rounded-[3px]',\n                        cellClassName,\n                      )}\n                    />\n                  ) : (\n                    <span\n                      key={column}\n                      className={cn(\n                        'min-h-3',\n                        dot\n                          ? 'bg-muted scale-70 rounded-full'\n                          : 'rounded-[3px] border border-dashed',\n                        cellClassName,\n                      )}\n                    />\n                  ),\n                )}\n              </Fragment>\n            ))}\n          </div>\n        </div>\n        {state === 'loading' && footer}\n      </div>\n    )\n  }\n\n  const extent = getExtent(values)\n  const min = minProp ?? extent.min\n  const max = maxProp ?? extent.max\n  const range = max - min || 1\n  const fill = color ?? 'var(--color-chart-2)'\n  const heat = (value: number) =>\n    getHeatColor(scale ? scale(value) : (value - min) / range, color)\n  const describeCell = (position: HeatmapCellPosition, value: HeatmapValue) =>\n    describe?.(position, value) ??\n    `${cellName(position)}: ${value === null ? 'no data' : format(value)}`\n\n  const show = (position: HeatmapCellPosition, cell: HTMLElement) => {\n    const origin = frame.current?.getBoundingClientRect()\n    if (!origin) return\n    const box = cell.getBoundingClientRect()\n    const x = box.left - origin.left + box.width / 2\n    setActive({\n      ...position,\n      flip: x > origin.width / 2,\n      x,\n      y: box.top - origin.top + box.height / 2,\n    })\n  }\n\n  const focusCell = (position: HeatmapCellPosition) => {\n    setCursor(position)\n    grid.current\n      ?.querySelector<HTMLElement>(`[data-cell=\"${position.row}-${position.column}\"]`)\n      ?.focus()\n  }\n\n  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    const last = { column: columns.length - 1, row: rows.length - 1 }\n    const next = { ...cursor }\n    switch (event.key) {\n      case 'ArrowRight':\n        next.column = Math.min(last.column, cursor.column + 1)\n        break\n      case 'ArrowLeft':\n        next.column = Math.max(0, cursor.column - 1)\n        break\n      case 'ArrowDown':\n        next.row = Math.min(last.row, cursor.row + 1)\n        break\n      case 'ArrowUp':\n        next.row = Math.max(0, cursor.row - 1)\n        break\n      case 'Home':\n        next.column = 0\n        if (event.ctrlKey) next.row = 0\n        break\n      case 'End':\n        next.column = last.column\n        if (event.ctrlKey) next.row = last.row\n        break\n      default:\n        return\n    }\n    event.preventDefault()\n    focusCell(next)\n  }\n\n  const onBlur = (event: FocusEvent<HTMLDivElement>) => {\n    if (!event.currentTarget.contains(event.relatedTarget)) setActive(null)\n  }\n\n  const activeValue = active ? (values[active.row]?.[active.column] ?? null) : null\n\n  return (\n    <div className={cn('flex flex-col gap-3', className)}>\n      {ripple && (\n        <style href='dashboardblocks-heatmap-ripple' precedence='default'>\n          {rippleStyles}\n        </style>\n      )}\n      <div ref={frame} className='relative' onPointerLeave={() => setActive(null)}>\n        <div\n          ref={scroller}\n          className={cn(\n            minWidth && 'relative -my-1 overflow-x-auto py-1 [scrollbar-width:thin]',\n          )}\n        >\n          <div\n            className='grid gap-[3px]'\n            style={{\n              gridTemplateColumns: `auto repeat(${columns.length}, minmax(0, 1fr))`,\n              minWidth,\n            }}\n          >\n            {columnSummary && (\n              <div className='col-span-full grid grid-cols-subgrid pb-1'>\n                <span className={cn(stickyLabel)} />\n                <div\n                  role='img'\n                  aria-label={columnSummary.label}\n                  className='col-span-full col-start-2'\n                >\n                  <TinyBarChart\n                    accessibilityLayer={false}\n                    bars={[\n                      {\n                        dataKey: 'value',\n                        fill: color ?? 'var(--color-chart-2)',\n                        radius: [2, 2, 0, 0],\n                      },\n                    ]}\n                    data={columnSummary.values.map((value, index) => ({\n                      label: columnSummary.labels?.[index] ?? columns[index],\n                      value,\n                    }))}\n                    formatter={columnSummary.format ?? formatCompact}\n                    height={56}\n                    highlightIndex={columnSummary.highlightIndex}\n                  />\n                </div>\n              </div>\n            )}\n            <div\n              ref={grid}\n              role='grid'\n              tabIndex={-1}\n              aria-label={label}\n              onBlur={onBlur}\n              onKeyDown={onKeyDown}\n              className='col-span-full grid grid-cols-subgrid gap-[3px]'\n            >\n              <div role='row' className='col-span-full grid grid-cols-subgrid'>\n                <span role='columnheader' className={cn(stickyLabel)}>\n                  <span className='sr-only'>{rowHeader}</span>\n                </span>\n                {columns.map((column, index) => (\n                  <span\n                    key={index}\n                    role='columnheader'\n                    className={cn(\n                      'text-muted-foreground overflow-visible text-xs leading-4 font-normal whitespace-nowrap tabular-nums',\n                      index === columns.length - 1 && 'flex justify-end',\n                    )}\n                  >\n                    {index % columnLabelEvery === 0 ? (\n                      column\n                    ) : (\n                      <span className='sr-only'>{column}</span>\n                    )}\n                  </span>\n                ))}\n              </div>\n              {rows.map((row, rowIndex) => (\n                <div\n                  key={rowIndex}\n                  role='row'\n                  className='col-span-full grid grid-cols-subgrid'\n                >\n                  <span\n                    role='rowheader'\n                    className={cn(\n                      'text-muted-foreground flex items-center pr-2 text-xs whitespace-nowrap',\n                      stickyLabel,\n                      rowLabelClassName,\n                    )}\n                  >\n                    {row || <span className='sr-only'>{rowNames?.[rowIndex]}</span>}\n                  </span>\n                  {columns.map((_, column) => {\n                    const value = values[rowIndex]?.[column] ?? null\n                    const position = { column, row: rowIndex }\n                    const isActive = active?.row === rowIndex && active.column === column\n                    const isCursor = cursor.row === rowIndex && cursor.column === column\n                    const isFlagged = value !== null && flagged?.(position, value)\n                    const reach = ripple\n                      ? Math.hypot(column - ripple.column, rowIndex - ripple.row)\n                      : Infinity\n                    const style: CSSProperties =\n                      value === null ? {} : { backgroundColor: heat(value) }\n                    return (\n                      <span\n                        key={column}\n                        role='gridcell'\n                        tabIndex={isCursor ? 0 : -1}\n                        data-cell={`${rowIndex}-${column}`}\n                        aria-label={describeCell(position, value)}\n                        onFocus={(event) => {\n                          setCursor(position)\n                          show(position, event.currentTarget)\n                        }}\n                        onPointerEnter={(event) => show(position, event.currentTarget)}\n                        onPointerDown={(event) => show(position, event.currentTarget)}\n                        className={cn(\n                          'ring-offset-background relative flex min-h-3 items-center justify-center text-xs font-medium tabular-nums outline-none',\n                          dot ? 'rounded-full' : 'rounded-[3px]',\n                          value === null &&\n                            (dot ? 'pointer-events-none' : 'border border-dashed'),\n                          !dot && isActive && 'ring-foreground ring-2 ring-offset-1',\n                          cellClassName,\n                        )}\n                        style={dot ? undefined : style}\n                      >\n                        {dot && (\n                          <span\n                            aria-hidden\n                            data-slot='heatmap-dot'\n                            className={cn(\n                              'absolute inset-[15%] rounded-full transition-[background-color,scale] duration-200 ease-out motion-reduce:transition-none',\n                              value === null && (isActive ? 'bg-muted' : 'hidden'),\n                              isActive && 'scale-150',\n                            )}\n                            style={\n                              isActive && value !== null\n                                ? { backgroundColor: fill }\n                                : style\n                            }\n                          />\n                        )}\n                        {ripple && value !== null && reach <= RIPPLE_REACH && (\n                          <span\n                            key={ripple.key}\n                            aria-hidden\n                            data-heatmap-ripple\n                            className={cn(\n                              'pointer-events-none absolute',\n                              dot ? 'inset-[15%] rounded-full' : 'inset-0 rounded-[3px]',\n                            )}\n                            style={\n                              {\n                                '--heatmap-ripple-peak': (\n                                  1 -\n                                  reach / (RIPPLE_REACH + 1)\n                                ).toFixed(2),\n                                '--heatmap-ripple-scale': (\n                                  1.2 +\n                                  0.3 * (1 - reach / RIPPLE_REACH)\n                                ).toFixed(2),\n                                animationDelay: `${Math.round(reach * 70)}ms`,\n                                backgroundColor: fill,\n                              } as CSSProperties\n                            }\n                          />\n                        )}\n                        {cellLabels && value !== null ? (\n                          <span aria-hidden>{format(value)}</span>\n                        ) : null}\n                        {isFlagged && <HeatmapFlag className='absolute top-1 right-1' />}\n                      </span>\n                    )\n                  })}\n                </div>\n              ))}\n            </div>\n          </div>\n        </div>\n        {active && (\n          <ChartFloatingTooltip active flip={active.flip} x={active.x} y={active.y}>\n            <span className='font-medium'>{cellName(active)}</span>\n            <ChartTooltipItem\n              color={activeValue === null ? undefined : heat(activeValue)}\n              name={valueName}\n              value={activeValue === null ? 'No data' : format(activeValue)}\n            />\n          </ChartFloatingTooltip>\n        )}\n      </div>\n      {(children || footer) && (\n        <div className='flex flex-wrap items-center justify-between gap-x-6 gap-y-2'>\n          {children && <p className='text-muted-foreground text-sm'>{children}</p>}\n          {footer}\n        </div>\n      )}\n    </div>\n  )\n}\n\nfunction HeatmapFlag({ className }: { className?: string }) {\n  return (\n    <span\n      aria-hidden\n      className={cn(\n        'ring-background block size-1.5 rounded-full bg-red-600 ring-1 dark:bg-red-400',\n        className,\n      )}\n    />\n  )\n}\n\ninterface HeatmapLegendProps {\n  className?: string\n  /** @default 'var(--color-chart-2)' */\n  color?: string\n  /** Names the dot `HeatmapGrid` draws on `flagged` cells, such as `Over target`. */\n  flag?: string\n  high?: string\n  low?: string\n  /** Match the grid's. @default 'square' */\n  shape?: HeatmapShape\n  /** @default 5 */\n  steps?: number\n}\n\nfunction HeatmapLegend({\n  className,\n  color,\n  flag,\n  high = 'More',\n  low = 'Less',\n  shape = 'square',\n  steps = 5,\n}: HeatmapLegendProps) {\n  return (\n    <div\n      aria-hidden\n      className={cn(\n        'text-muted-foreground flex flex-wrap items-center gap-x-4 gap-y-2 text-xs',\n        className,\n      )}\n    >\n      {flag && (\n        <span className='flex items-center gap-1.5'>\n          <HeatmapFlag />\n          {flag}\n        </span>\n      )}\n      <span className='flex items-center gap-1.5'>\n        <span className='mr-0.5'>{low}</span>\n        {Array.from({ length: steps }, (_, index) => (\n          <span\n            key={index}\n            className={shape === 'dot' ? 'size-2.5 rounded-full' : 'size-3 rounded-[3px]'}\n            style={{\n              backgroundColor: getHeatColor(index / (steps - 1), color),\n            }}\n          />\n        ))}\n        <span className='ml-0.5'>{high}</span>\n      </span>\n    </div>\n  )\n}\n\nexport {\n  HeatmapFlag,\n  HeatmapGrid,\n  HeatmapLegend,\n  getColumnTotals,\n  getExtent,\n  getHeatColor,\n  getPeak,\n}\n\nexport type {\n  HeatmapCellPosition,\n  HeatmapColumnSummary,\n  HeatmapFormatter,\n  HeatmapGridProps,\n  HeatmapLegendProps,\n  HeatmapRipple,\n  HeatmapShape,\n  HeatmapValue,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/heatmap.tsx"
    }
  ],
  "type": "registry:component"
}
