{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "heatmap-chart",
  "title": "Heatmap chart",
  "description": "Values as coloured cells on the chart’s cells and grid reader: a grid named by two values, such as days by hours, or a calendar of days. Each value takes one of a few steps of its colour, which the legend names. The cell under the pointer stays bright while the rest step back, the axes mark its column and row, the arrows step through the cells, and a new range fills them in a wave.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/chart.json",
    "https://kinoui.com/r/chart-cells.json",
    "https://kinoui.com/r/chart-core.json",
    "https://kinoui.com/r/chart-grid.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/dates.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/heatmap-chart.tsx",
      "content": "'use client'\n\nimport {\n  type CategoryChartProps,\n  figureProps,\n  localeTag,\n  pickedName,\n} from '@/registry/lib/chart-base'\nimport {\n  type CellAt,\n  cellAnchor,\n  cellAt,\n  CellGridCells,\n  type CellGridLayout,\n  CellGridPlaceholder,\n  CellGridSizer,\n  CellGridTooltipContent,\n  CellsChartFrame,\n  type CellsContextValue,\n  CellStepLegend,\n  laidOutCells,\n  lineNames,\n  StepLegendContext,\n  stepFill,\n  useCellsChart,\n} from '@/registry/lib/chart-cells'\nimport {\n  calendarGrid,\n  type CellShape,\n  columnBand,\n  keyedGrid,\n  rowBand,\n  stepEdges,\n  stepExtent,\n  stepOf,\n} from '@/registry/lib/chart-grid'\nimport { gridReader, squareLayout } from '@/registry/lib/chart-grid-reader'\nimport { allWhole, numberOf } from '@/registry/lib/chart-math'\nimport type { ChartDatum } from '@/registry/lib/chart-math'\nimport { linearScale } from '@/registry/lib/chart-scale'\nimport {\n  formatDate,\n  monthName,\n  monthOf,\n  useLocale,\n  type Weekday,\n  weekdayNames,\n  weekStart,\n} from '@/registry/lib/dates'\nimport { type ComponentProps, useMemo, useState } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The Heatmap chart: values as coloured cells, in a grid named by two of\n * each row's values, such as days by hours, or as a calendar of days, as a\n * year of activity is. The cells are squares, or hexagons in offset rows,\n * so a dense field of values reads as a surface. Each value takes one of a\n * few steps of its colour, at the value axis's round numbers, and the\n * legend names them. It is drawn on the cells (`chart-cells`) with the grid\n * reader: the cell under the pointer stays bright while the rest step back,\n * hexagons by how far they are, the axes mark its column and its row, and\n * the arrows step through the cells by column and by row. A new range fills\n * the cells in a wave along the columns.\n */\n\ninterface HeatmapChartBaseProps extends Omit<\n  CategoryChartProps,\n  'index' | 'ordered' | 'patterns' | 'categoryFormat' | 'tickValues'\n> {\n  /** The key of each row's value, a key of the config, which colours its cell. */\n  value: string\n  /** The cells' shape: squares, or pointy-top hexagons whose odd rows sit half a cell toward the inline end. */\n  cell?: CellShape\n}\n\n/** A grid named by two of each row's values, such as days by hours. */\ninterface HeatmapGridProps {\n  layout?: 'grid'\n  /** The key of each row's column: a column for each value, numbers from the lowest, others in the order the data gives them. */\n  x: string\n  /** The key of each row's row: a row for each value, numbers from the lowest, others in the order the data gives them. */\n  y: string\n  /** How a column's value is written, on the x axis and in a cell's name; `String` by default. */\n  xFormat?: (value: unknown) => string\n  /** How a row's value is written, on the y axis and in a cell's name; `String` by default. */\n  yFormat?: (value: unknown) => string\n  /** Every column's value, in order, when the data can't say: a column for each, with rows or none. */\n  xValues?: readonly unknown[]\n  /** Every row's value, in order, when the data can't say: a row for each, with rows or none. */\n  yValues?: readonly unknown[]\n  date?: never\n  weekStartsOn?: never\n}\n\n/** A calendar of days, a column for each week. */\ninterface HeatmapCalendarProps {\n  layout: 'calendar'\n  /** The key of each row's day, a `yyyy-mm-dd` date: every day from the first to the last is a cell. */\n  date: string\n  /** The day each week starts on, from 0 for Sunday; the locale's by default. */\n  weekStartsOn?: Weekday\n  x?: never\n  y?: never\n  xFormat?: never\n  yFormat?: never\n  xValues?: never\n  yValues?: never\n}\n\ntype HeatmapChartProps = HeatmapChartBaseProps & (HeatmapGridProps | HeatmapCalendarProps)\n\nconst heatmapChartKeys = [\n  'value',\n  'cell',\n  'layout',\n  'x',\n  'y',\n  'xFormat',\n  'yFormat',\n  'xValues',\n  'yValues',\n  'date',\n  'weekStartsOn',\n]\n\nfunction gridLayout(\n  shape: CellShape,\n  data: readonly ChartDatum[],\n  x: string,\n  y: string,\n  xFormat: (value: unknown) => string,\n  yFormat: (value: unknown) => string,\n  xValues: readonly unknown[] | undefined,\n  yValues: readonly unknown[] | undefined,\n): CellGridLayout {\n  const grid = keyedGrid(data, x, y, { columns: xValues, rows: yValues })\n  const columns = grid.columns.length\n  const rows = grid.rows.length\n  return {\n    cells: laidOutCells(\n      grid.cells,\n      (cell) => `${yFormat(cell.at.y)}, ${xFormat(cell.at.x)}`,\n      (cell) => cellKey(cell.at.x, cell.at.y),\n      ({ column, row }) => ({ column, row, x: column, y: row }),\n    ),\n    columns,\n    rowCount: rows,\n    x: {\n      names: lineNames(grid.columns, (at) => columnBand(shape, at, at, columns, rows)),\n      format: xFormat,\n    },\n    y: {\n      names: lineNames(grid.rows, (at) => rowBand(shape, at, rows)),\n      format: yFormat,\n    },\n  }\n}\n\n/**\n * A grid cell's key, for `selected`: its column's value and its row's, as\n * `x|y`, so values that hold a `|` themselves can name two cells alike.\n */\nfunction cellKey(x: unknown, y: unknown) {\n  return `${String(x)}|${String(y)}`\n}\n\nfunction calendarLayout(\n  shape: CellShape,\n  data: readonly ChartDatum[],\n  date: string,\n  first: Weekday,\n  locale: string,\n): CellGridLayout {\n  const grid = calendarGrid(data, date, first)\n  const days = weekdayNames(locale, first, 'short')\n  const columns = Math.max(1, grid.columns)\n  const monthAt = new Map(grid.months.map((month, index) => [month.month, index]))\n  return {\n    cells: laidOutCells(\n      grid.cells,\n      (cell) =>\n        formatDate(cell.at, locale, {\n          weekday: 'short',\n          day: 'numeric',\n          month: 'short',\n          year: 'numeric',\n        }),\n      (cell) => cell.at,\n      (cell): CellAt => ({\n        column: cell.column,\n        row: cell.row,\n        x: monthAt.get(monthOf(cell.at)) ?? null,\n        y: cell.row,\n      }),\n    ),\n    columns: grid.columns,\n    rowCount: 7,\n    x: {\n      // Each month over the weeks it reaches.\n      names: grid.months.map(({ month, from, to }, index) => ({\n        key: month,\n        value: month,\n        index,\n        band: columnBand(shape, from, to, columns, 7),\n        leaving: false,\n      })),\n      format: (value) => monthName(String(value), locale),\n    },\n    y: {\n      names: lineNames(\n        days.map((_, row) => row),\n        (row) => rowBand(shape, row, 7),\n      ),\n      format: (value) => days[Number(value)] ?? String(value),\n    },\n  }\n}\n\n/**\n * The chart's root: it lays the rows out as cells, works out the colour's\n * steps, and sizes the plot so its cells keep their shape: squares up to a\n * height, and hexagons always.\n */\nfunction HeatmapChart(props: HeatmapChartProps) {\n  const {\n    data,\n    value,\n    cell: shape = 'square',\n    config,\n    domain,\n    tickCount = 5,\n    allowDecimals,\n    locale,\n    description,\n    empty,\n    className,\n    children,\n    ref,\n  } = props\n  const dateLocale = useLocale(localeTag(locale))\n  const calendar = props.layout === 'calendar'\n  const dateKey = calendar ? props.date : undefined\n  const first: Weekday = calendar ? (props.weekStartsOn ?? weekStart(dateLocale)) : 1\n  const xKey = calendar ? undefined : props.x\n  const yKey = calendar ? undefined : props.y\n  const xFormat = (calendar ? undefined : props.xFormat) ?? String\n  const yFormat = (calendar ? undefined : props.yFormat) ?? String\n  const xValues = calendar ? undefined : props.xValues\n  const yValues = calendar ? undefined : props.yValues\n  const layout = useMemo(\n    () =>\n      dateKey !== undefined\n        ? calendarLayout(shape, data, dateKey, first, dateLocale)\n        : gridLayout(\n            shape,\n            data,\n            xKey ?? '',\n            yKey ?? '',\n            xFormat,\n            yFormat,\n            xValues,\n            yValues,\n          ),\n    [\n      shape,\n      data,\n      dateKey,\n      first,\n      dateLocale,\n      xKey,\n      yKey,\n      xFormat,\n      yFormat,\n      xValues,\n      yValues,\n    ],\n  )\n  const values = layout.cells.map((cell) => numberOf(cell.datum?.[value]))\n  const scale = linearScale(stepExtent(values), {\n    domain,\n    tickCount,\n    nice: true,\n    allowDecimals:\n      allowDecimals ??\n      !allWhole(\n        layout.cells.flatMap((cell) => (cell.datum ? [cell.datum] : [])),\n        [value],\n      ),\n  })\n  const edges = stepEdges(scale.domain, scale.ticks)\n  const steps = edges.length - 1\n  const [emphasis, setEmphasis] = useState<number | null>(null)\n  const chart = useCellsChart(props, layout)\n  const { state } = chart\n  const valueLabel = config[value]?.label\n  const valueName = typeof valueLabel === 'string' ? valueLabel : value\n  const columns = Math.max(1, layout.columns || (calendar ? 53 : 24))\n  const rows = Math.max(1, layout.rowCount || 7)\n  const cells: CellsContextValue = {\n    slot: 'heatmap-chart',\n    cells: chart.cells,\n    drawn: chart.drawn,\n    shape,\n    columns,\n    rows,\n    value,\n    edges,\n    emphasis,\n    fillOf: (stop) =>\n      stepFill(value, stepOf(numberOf(stop.datum?.[value]), edges), steps),\n    nameText: (stop) => stop.value,\n    datumText: chart.datumText,\n  }\n  const valueText = (stop: { datum: ChartDatum | null }) =>\n    chart.datumText(stop.datum?.[value])\n  const reader = gridReader({\n    current: chart.cells,\n    layout: squareLayout,\n    direction: state.direction,\n    hit: (point) => cellAt(point, chart.cells, shape, columns, rows, state.direction),\n    anchor: (stop) => cellAnchor(stop, shape, columns, rows, state.direction),\n    words: {\n      describe: (stop) =>\n        `${pickedName(stop.value, chart.picked === stop.key, state.messages)}: ${valueName} ${valueText(stop)}`,\n      tooltip: (stop) => <CellGridTooltipContent stop={stop} name={valueName} />,\n      table: {\n        header: state.messages.category,\n        columns: [valueName],\n        rows: chart.cells.map((stop) => ({\n          key: stop.key,\n          name: stop.value,\n          cells: [valueText(stop)],\n        })),\n        footer: [],\n      },\n    },\n    // A calendar scrolls and opens at its end, the latest week, so the keys start there too.\n    start: calendar ? 'last' : 'first',\n  })\n  return (\n    <StepLegendContext\n      value={{\n        slot: 'heatmap-chart',\n        label: valueLabel ?? value,\n        edges,\n        fillOf: (step) => stepFill(value, step, steps),\n        valueText: state.valueText,\n        textWidth: state.textWidth,\n        emphasis,\n        setEmphasis,\n      }}\n    >\n      <CellsChartFrame\n        chart={chart}\n        reader={reader}\n        cells={cells}\n        axes={layout}\n        scrolls={calendar}\n        ref={ref}\n        description={description}\n        empty={empty}\n        className={cn('h-auto', className)}\n        placeholder={\n          chart.placeholder && (\n            <CellGridPlaceholder\n              slot='heatmap-chart'\n              shape={shape}\n              columns={columns}\n              rows={rows}\n            />\n          )\n        }\n        {...figureProps(props, heatmapChartKeys)}\n      >\n        <CellGridSizer shape={shape} columns={columns} rows={rows} />\n        {children}\n      </CellsChartFrame>\n    </StepLegendContext>\n  )\n}\n\n/**\n * The cells: a cell for each column and row, in its step of the value's\n * colour, and a dashed outline, or a hollow hexagon, where there is no\n * value. While a cell is lit, the rest step back and it is outlined; new\n * values fill the cells in a wave along the columns.\n */\nfunction Heatmap(\n  props: Omit<ComponentProps<'div'>, 'children'> & {\n    /** Each cell writes its value on itself where it fits. */\n    label?: boolean\n  },\n) {\n  return <CellGridCells {...props} />\n}\n\n/**\n * The colour's steps, from the lowest to the highest, with the value at\n * each edge, under or over the plot. Pointing at a step brings its cells\n * forward. A screen reader reads each step's range.\n */\nfunction HeatmapLegend(\n  props: Omit<ComponentProps<'div'>, 'children'> & { position?: 'top' | 'bottom' },\n) {\n  return <CellStepLegend {...props} />\n}\n\nexport { Heatmap, HeatmapChart, type HeatmapChartProps, HeatmapLegend }\n",
      "type": "registry:component",
      "target": "@components/kino/heatmap-chart.tsx"
    }
  ],
  "type": "registry:component"
}