{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-grid",
  "title": "Chart grid",
  "description": "How a chart drawn as a grid of cells lays its data out, in columns and rows named by two of each row’s values or as the weeks of a calendar, with a cell for every pair or day the data leaves out, and the steps of the colour its cells take. Pure functions, so they are tested on their own.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/dates.json"
  ],
  "files": [
    {
      "path": "registry/lib/chart-grid.ts",
      "content": "import {\n  type ChartDatum,\n  type GridCell,\n  gridCellAt,\n  type ReadingDirection,\n  type Span,\n} from '@/registry/lib/chart-math'\nimport {\n  addDays,\n  daysBetween,\n  isISODate,\n  monthOf,\n  startOfWeek,\n  type Weekday,\n  weekday,\n} from '@/registry/lib/dates'\n\n/*\n * How a chart drawn as a grid of cells, such as a heatmap, lays its rows of\n * data out, in columns and rows named by two of each row's values, or as\n * the weeks of a calendar, and the steps of the colour its cells take. Pure,\n * so it is tested on its own; the chart core steps and points through the\n * cells it gives, and `chart-cells` draws them.\n */\n\n/** A cell of the grid: where it sits, and the row of data it shows, or none. */\ninterface LaidCell<T> extends GridCell {\n  /** What the cell is: a column and row's values, or a date. */\n  at: T\n  datum: ChartDatum | null\n}\n\n/** A grid of `columns` by `rows`, with its cells in reading order, a row at a time. */\ninterface KeyedGrid {\n  /** Each column's value, in order. */\n  columns: readonly unknown[]\n  /** Each row's value, in order. */\n  rows: readonly unknown[]\n  cells: readonly LaidCell<{ x: unknown; y: unknown }>[]\n}\n\n/** The values each column and row takes, in order, where the data alone can't say. */\ninterface GridOrder {\n  /** Every column's value, in order: each is a column, with rows or none. */\n  columns?: readonly unknown[]\n  /** Every row's value, in order: each is a row, with rows of data or none. */\n  rows?: readonly unknown[]\n}\n\n/**\n * The grid named by each row's `x` and `y`: a column for each `x` and a row\n * for each `y`, and a cell for every pair, so a pair the data leaves out is\n * a cell with no value. Where two rows name the same pair, the first is the\n * cell's. The columns and rows are `order`'s, when it gives them; otherwise\n * numbers run from the lowest, and other values come in the order the data\n * gives them.\n */\nfunction keyedGrid(\n  data: readonly ChartDatum[],\n  x: string,\n  y: string,\n  order: GridOrder = {},\n): KeyedGrid {\n  const columns = order.columns ?? dataOrder(data, x, y)\n  const rows = order.rows ?? dataOrder(data, y, x)\n  const byPair = new Map<string, ChartDatum>()\n  for (const row of data) {\n    const pair = pairKey(row[x], row[y])\n    if (!byPair.has(pair)) byPair.set(pair, row)\n  }\n  const cells = rows.flatMap((yValue, row) =>\n    columns.map((xValue, column) => ({\n      column,\n      row,\n      at: { x: xValue, y: yValue },\n      datum: byPair.get(pairKey(xValue, yValue)) ?? null,\n    })),\n  )\n  return { columns, rows, cells }\n}\n\n/**\n * Each value under `key` once, by its text: numbers from the lowest, and\n * other values in the order the data gives them within each `group`, so a\n * value one group leaves out, such as a day the first week has no rows\n * for, takes its place from the next group that has it: before the value\n * that follows it there, or last when none does.\n */\nfunction dataOrder(data: readonly ChartDatum[], key: string, group: string): unknown[] {\n  // Values go by their text; each text keeps the first value that gave it.\n  const valueOf = new Map<string, unknown>()\n  const groups = new Map<string, string[]>()\n  for (const row of data) {\n    const text = String(row[key])\n    if (!valueOf.has(text)) valueOf.set(text, row[key])\n    const name = String(row[group])\n    const texts = groups.get(name) ?? []\n    texts.push(text)\n    groups.set(name, texts)\n  }\n  const order: string[] = []\n  for (const texts of groups.values()) {\n    texts.forEach((text, at) => {\n      if (order.includes(text)) return\n      const after = texts.slice(at + 1).find((other) => order.includes(other))\n      const index = after === undefined ? order.length : order.indexOf(after)\n      order.splice(index, 0, text)\n    })\n  }\n  const values = order.map((text) => valueOf.get(text))\n  if (values.every((value) => typeof value === 'number' && Number.isFinite(value))) {\n    return (values as number[]).toSorted((a, b) => a - b)\n  }\n  return values\n}\n\nfunction pairKey(x: unknown, y: unknown) {\n  return `${String(x)}\\u0000${String(y)}`\n}\n\n/** The days from the first date to the last, as weeks of a calendar. */\ninterface CalendarGrid {\n  /** How many weeks: a column each. */\n  columns: number\n  /** Each month the days reach, with the first and last column it takes. */\n  months: readonly { month: string; from: number; to: number }[]\n  /** A cell for each day, in order. */\n  cells: readonly LaidCell<string>[]\n}\n\n/**\n * Every day from the first date in `data`'s `date` to the last, as a\n * calendar: a column for each week, starting on `first`, and a row for each\n * day of the week. A day the data leaves out is a cell with no value, and a\n * row whose date isn't a `yyyy-mm-dd` date is left out. Where two rows give\n * the same day, the first is its cell's.\n */\nfunction calendarGrid(\n  data: readonly ChartDatum[],\n  date: string,\n  first: Weekday,\n): CalendarGrid {\n  const byDay = new Map<string, ChartDatum>()\n  for (const row of data) {\n    const day = row[date]\n    if (isISODate(day) && !byDay.has(day)) byDay.set(day, row)\n  }\n  const days = [...byDay.keys()].toSorted()\n  const from = days[0]\n  const to = days.at(-1)\n  if (from === undefined || to === undefined) return { columns: 0, months: [], cells: [] }\n  const start = startOfWeek(from, first)\n  const cells = Array.from({ length: daysBetween(from, to) + 1 }, (_, at) => {\n    const day = addDays(from, at)\n    return {\n      column: Math.floor(daysBetween(start, day) / 7),\n      row: (weekday(day) - first + 7) % 7,\n      at: day,\n      datum: byDay.get(day) ?? null,\n    }\n  })\n  const months: { month: string; from: number; to: number }[] = []\n  for (const cell of cells) {\n    const month = monthOf(cell.at)\n    const last = months.at(-1)\n    if (last?.month === month) last.to = cell.column\n    else months.push({ month, from: cell.column, to: cell.column })\n  }\n  return { columns: (cells.at(-1)?.column ?? 0) + 1, months, cells }\n}\n\n/**\n * The edges of the colour's steps over `domain`: its round numbers, `ticks`,\n * with its ends, so a value always lands in a step. Two edges make one step.\n */\nfunction stepEdges(domain: Span, ticks: readonly number[]): number[] {\n  const inside = ticks.filter((tick) => tick > domain[0] && tick < domain[1])\n  return [domain[0], ...inside, domain[1]]\n}\n\n/**\n * The step `value` falls in among the steps between `edges`: from 0 for the\n * lowest. A value on an edge takes the step above it, and one past either\n * end the step at that end. Null for no value.\n */\nfunction stepOf(value: number | null, edges: readonly number[]): number | null {\n  if (value === null) return null\n  const last = Math.max(0, edges.length - 2)\n  for (let step = 0; step < last; step += 1) {\n    if (value < edges[step + 1]!) return step\n  }\n  return last\n}\n\n/**\n * How strong the colour of the step at `step` among `steps` is, from a\n * faint tint for the lowest to the whole colour for the highest, evenly\n * between, so each step reads apart from the next.\n */\nfunction stepStrength(step: number, steps: number): number {\n  if (steps <= 1) return 1\n  return 0.22 + (0.78 * step) / (steps - 1)\n}\n\n/**\n * What the colour reaches: from zero, or the lowest value when it is below\n * zero, to the highest, so the lightest step means little and the darkest\n * the most. 0 to 1 with no values.\n */\nfunction stepExtent(values: readonly (number | null)[]): Span {\n  const numbers = values.filter((value): value is number => value !== null)\n  if (numbers.length === 0) return [0, 1]\n  return [Math.min(0, ...numbers), Math.max(0, ...numbers)]\n}\n\n/*\n * The cells' shape. Squares sit in columns and rows. Hexagons are\n * pointy-top, and each odd row sits half a cell toward the inline end, so\n * the rows still read across and a column's cells zigzag down it. A grid\n * keeps its shape's own proportions only for hexagons: a plot of square\n * cells widens them past its tallest, while hexagons never stretch.\n */\n\n/** The shape of a grid's cells. */\ntype CellShape = 'square' | 'hex'\n\n/** A cell's box, as fractions of the plot: across from its reading start, and down from its top. */\ninterface CellBox {\n  x: number\n  y: number\n  width: number\n  height: number\n}\n\n/** The odd rows' offset of a hexagon grid, in cells: none with one row. */\nfunction hexOffset(rows: number) {\n  return rows > 1 ? 0.5 : 0\n}\n\n/** How many radii tall a hexagon grid of `rows` is: a row every one and a half, and the last one's lower half. */\nfunction hexDown(rows: number) {\n  return 1.5 * rows + 0.5\n}\n\n/**\n * The plot's width over its height, at which the cells keep their shape:\n * square cells for squares, and regular hexagons, `√3` radii wide each.\n */\nfunction gridAspect(shape: CellShape, columns: number, rows: number): number {\n  if (shape === 'square') return columns / rows\n  return ((columns + hexOffset(rows)) * Math.sqrt(3)) / hexDown(rows)\n}\n\n/** The box of the cell at `cell` in a grid `columns` by `rows`, before the room between cells. */\nfunction cellBox(\n  shape: CellShape,\n  cell: GridCell,\n  columns: number,\n  rows: number,\n): CellBox {\n  if (shape === 'square') {\n    return {\n      x: cell.column / columns,\n      y: cell.row / rows,\n      width: 1 / columns,\n      height: 1 / rows,\n    }\n  }\n  const across = columns + hexOffset(rows)\n  const down = hexDown(rows)\n  const shift = cell.row % 2 === 1 ? hexOffset(rows) : 0\n  return {\n    x: (cell.column + shift) / across,\n    y: (1.5 * cell.row) / down,\n    width: 1 / across,\n    height: 2 / down,\n  }\n}\n\n/**\n * The cell under `at`, a point as fractions of the plot from its physical\n * left and its top: columns run from the reading start. A point past an\n * edge takes the cell at that edge. A hexagon is found by rounding the\n * point's cube coordinates, so a point in the room between two hexagons\n * takes the nearer one.\n */\nfunction cellUnder(\n  shape: CellShape,\n  at: { x: number; y: number },\n  columns: number,\n  rows: number,\n  direction: ReadingDirection,\n): GridCell {\n  if (shape === 'square') return gridCellAt(at, columns, rows, direction)\n  const along = direction === 'rtl' ? 1 - at.x : at.x\n  // In radii, from the centre of the first cell of the first row.\n  const x = along * (columns + hexOffset(rows)) * Math.sqrt(3) - Math.sqrt(3) / 2\n  // Held between the first row's centre and the last's, so a point in a notch along the top or\n  // bottom takes the nearer hexagon of the row it is beside.\n  const y = Math.min(1.5 * (rows - 1), Math.max(0, at.y * hexDown(rows) - 1))\n  const q = (Math.sqrt(3) / 3) * x - y / 3\n  const r = (2 / 3) * y\n  const rs = Math.round(-q - r)\n  let rq = Math.round(q)\n  let rr = Math.round(r)\n  const [dq, dr, ds] = [Math.abs(rq - q), Math.abs(rr - r), Math.abs(rs + q + r)]\n  if (dq > dr && dq > ds) rq = -rr - rs\n  else if (dr > ds) rr = -rq - rs\n  const clamp = (value: number, count: number) => Math.min(count - 1, Math.max(0, value))\n  const row = clamp(rr, rows)\n  return { column: clamp(rq + (rr - (rr & 1)) / 2, columns), row }\n}\n\n/**\n * How many steps apart two hexagons are, through neighbours: 1 for the six\n * around a cell. Their places are columns and rows with the odd rows\n * shifted, so they are made axial first.\n */\nfunction hexDistance(a: GridCell, b: GridCell): number {\n  const { q, r } = hexStep(b, a)\n  return (Math.abs(q) + Math.abs(q + r) + Math.abs(r)) / 2\n}\n\n/** The step from hexagon `from` to `to` in axial coordinates: the same for every pair of cells the same way apart. */\nfunction hexStep(from: GridCell, to: GridCell): { q: number; r: number } {\n  const q = (cell: GridCell) => cell.column - (cell.row - (cell.row & 1)) / 2\n  return { q: q(to) - q(from), r: to.row - from.row }\n}\n\n/** A key for the step from hexagon `from` to `to`, which stays the same as both move together. */\nfunction hexStepKey(from: GridCell, to: GridCell): string {\n  const { q, r } = hexStep(from, to)\n  return `${q},${r}`\n}\n\n/** The rings the spotlight steps back in: the lit cell is 0, and the last takes the rest. */\nconst SPOTLIGHT_RINGS = 3\n\n/**\n * The ring of the spotlight around `lit` that `cell` sits in: 0 for the\n * lit cell, then by how far it is, up to `SPOTLIGHT_RINGS` for the rest.\n * Hexagons make a surface, so their neighbours step back by distance;\n * square cells are a table's, so the rest step back together.\n */\nfunction spotlightRing(shape: CellShape, lit: GridCell, cell: GridCell): number {\n  if (lit.column === cell.column && lit.row === cell.row) return 0\n  if (shape === 'square') return SPOTLIGHT_RINGS\n  return Math.min(SPOTLIGHT_RINGS, hexDistance(lit, cell))\n}\n\n/** Where along the grid a column's name sits, over its columns `from` to `to`: on a hexagon grid, over its even rows. */\nfunction columnBand(\n  shape: CellShape,\n  from: number,\n  to: number,\n  columns: number,\n  rows: number,\n): { start: number; size: number } {\n  const across = shape === 'square' ? columns : columns + hexOffset(rows)\n  return { start: from / across, size: (to - from + 1) / across }\n}\n\n/** Where down the grid a row's name sits: over its row, centred on its cells. */\nfunction rowBand(\n  shape: CellShape,\n  row: number,\n  rows: number,\n): { start: number; size: number } {\n  if (shape === 'square') return { start: row / rows, size: 1 / rows }\n  // A row is 1.5 radii from the next, centred a radius below its top.\n  const down = hexDown(rows)\n  return { start: (1.5 * row + 0.25) / down, size: 1.5 / down }\n}\n\n/**\n * The least width and height a cell is drawn at, in px, that a label\n * `width` by `height` fits inside. A hexagon is its full width only across\n * its middle half, so a label taller than that needs it wider.\n */\nfunction labelRoom(\n  shape: CellShape,\n  width: number,\n  height: number,\n): { width: number; height: number } {\n  if (shape === 'square') return { width, height }\n  // A hexagon `w` wide is that wide for √3/6 × w either side of its middle, and narrows to its points beyond.\n  const half = height / 2\n  const flat = 2 * Math.sqrt(3) * half\n  return { width: width >= flat ? width : (width + flat) / 2, height: 0 }\n}\n\nexport {\n  calendarGrid,\n  type CalendarGrid,\n  type CellBox,\n  cellBox,\n  type CellShape,\n  cellUnder,\n  columnBand,\n  gridAspect,\n  type GridOrder,\n  hexDistance,\n  hexStepKey,\n  labelRoom,\n  rowBand,\n  SPOTLIGHT_RINGS,\n  spotlightRing,\n  keyedGrid,\n  type KeyedGrid,\n  type LaidCell,\n  stepEdges,\n  stepExtent,\n  stepOf,\n  stepStrength,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-grid.ts"
    }
  ],
  "type": "registry:lib"
}