{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-math",
  "title": "Chart maths",
  "description": "The maths every chart shares: series and stacks, the scales (bands and points of categories, numbers and times) and their ticks, where the pointer and the keys land, label spacing and the cascade order. Pure functions, so they are tested on their own.",
  "dependencies": [
    "d3-array"
  ],
  "devDependencies": [
    "@types/d3-array"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/dates.json"
  ],
  "files": [
    {
      "path": "registry/lib/chart-math.ts",
      "content": "import type { Band } from '@/registry/lib/chart-scale'\nimport type { ReactNode } from 'react'\n\n/*\n * The arithmetic every chart with categories shares: which values a series\n * spans once it is stacked, where a mark sits on the plot, which key steps\n * where, and which category names fit. The scales themselves, the range an\n * axis shows and its ticks, are in the chart scale lib. Everything here is a pure function of the data and the\n * chart's options, so the parts that draw only place what it returns. What\n * one kind of chart alone works out, such as a bar's clip, lives in its file.\n */\n\n/** A fill drawn over a series' colour, so series differ by more than colour. */\nexport type ChartPattern = 'solid' | 'stripes' | 'dots' | 'grid' | 'diagonal'\n\n/** How a series is named and drawn, keyed by its key in the data: shadcn's `ChartConfig`, and a little more. */\nexport interface ChartSeries {\n  label?: ReactNode\n  /** Any CSS colour, such as `var(--chart-1)`. */\n  color?: string\n  /** A colour for each theme, in place of `color`. */\n  theme?: { light: string; dark: string }\n  /** A pattern over the colour; the chart's `patterns` gives each series one by default. */\n  pattern?: ChartPattern\n  /** When the chart stacks, the series with the same `stack` stack together, beside the other stacks. */\n  stack?: string\n  /** What the series is drawn as; the chart's own mark by default. */\n  mark?: ChartMark\n  /** The value axis the series is read against, by its id; `'value'`, the chart's own, by default. */\n  axis?: string\n}\n\n/** What a series is drawn as on a cartesian chart. */\nexport type ChartMark = 'bar' | 'line' | 'area' | 'point'\n\n/** Every key is a series the chart draws, in the order written, which is also the order they stack in. */\nexport type ChartConfig = Record<string, ChartSeries>\n\n/** One row of the data: a category and a value for each series. */\nexport type ChartDatum = Record<string, unknown>\n\nexport type ChartOrientation = 'vertical' | 'horizontal'\n\nexport type ReadingDirection = 'ltr' | 'rtl'\n\n/**\n * How the series of one category combine: side by side, stacked on each\n * other, or stacked to fill the axis as shares of their total. As shares,\n * a row with negative values fills the axis from below zero to above it.\n * Overlapped, the series of one stack stand in front of one another, each\n * from zero, the first written at the back, such as hours booked in front\n * of the hours there are; the stacks sit side by side.\n */\nexport type ChartStack = 'none' | 'stacked' | 'expand' | 'overlap'\n\n/** Whether the series of a stack add up: stacked or as shares, never side by side or overlapped. */\nexport function addsUp(stack: ChartStack): boolean {\n  return stack === 'stacked' || stack === 'expand'\n}\n\n/** A number that can be drawn, or null for a missing value. */\nexport function numberOf(value: unknown): number | null {\n  return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\n/** Where a series' value starts and ends on the value axis, in data units. */\nexport type Span = readonly [from: number, to: number]\n\n/** A value given as its two ends, `[from, to]`, such as a range or a step of a waterfall. */\nexport function rangeOf(value: unknown): Span | null {\n  if (!Array.isArray(value) || value.length !== 2) return null\n  const from = numberOf(value[0])\n  const to = numberOf(value[1])\n  return from === null || to === null ? null : [from, to]\n}\n\n/** A series' value at a stop, by its place: what the spans of a cartesian chart read, never its rows. */\nexport type SeriesValueOf = (series: string, index: number) => unknown\n\n/** The values of `rows` as the spans read them: each series' under its key in each row. */\nexport function rowValues(rows: readonly ChartDatum[]): SeriesValueOf {\n  return (series, index) => rows[index]?.[series]\n}\n\n/**\n * Each series' span at each of `count` stops, null where its value is\n * missing. Side by side or overlapped, a bar runs from zero to its value. Stacked,\n * positive values stack up from zero and negative ones down from it, in the\n * order of `keys`, each stack on its own (`stackOf`); as shares, each stack\n * is divided by the total of its values' sizes, so it fills the axis. A\n * value given as `[from, to]` spans exactly that and never stacks.\n */\nexport function seriesSpans(\n  count: number,\n  valueOf: SeriesValueOf,\n  keys: readonly string[],\n  stack: ChartStack,\n  stackOf: (key: string) => string = () => '',\n): Record<string, (Span | null)[]> {\n  const spans: Record<string, (Span | null)[]> = {}\n  for (const key of keys) spans[key] = []\n  for (let at = 0; at < count; at += 1) {\n    const raw = keys.map((key) => valueOf(key, at))\n    const values = raw.map(numberOf)\n    const totals = new Map<string, number>()\n    if (stack === 'expand') {\n      keys.forEach((key, index) => {\n        const group = stackOf(key)\n        totals.set(group, (totals.get(group) ?? 0) + Math.abs(values[index] ?? 0))\n      })\n    }\n    const up = new Map<string, number>()\n    const down = new Map<string, number>()\n    keys.forEach((key, index) => {\n      const range = rangeOf(raw[index])\n      if (range) {\n        spans[key]!.push(range)\n        return\n      }\n      const value = values[index]\n      if (value === null || value === undefined) {\n        spans[key]!.push(null)\n        return\n      }\n      if (!addsUp(stack)) {\n        spans[key]!.push([0, value])\n        return\n      }\n      const group = stackOf(key)\n      const total = stack === 'expand' ? (totals.get(group) ?? 0) : 1\n      const share = total === 0 ? 0 : value / total\n      const ends = share >= 0 ? up : down\n      const from = ends.get(group) ?? 0\n      spans[key]!.push([from, from + share])\n      ends.set(group, from + share)\n    })\n  }\n  return spans\n}\n\n/**\n * The spans of each series in `series` that isn't `shown`: where it would\n * sit among the shown series, stacked in its place, were it shown with\n * nothing in it. A hidden bar or area collapses there, so it leaves from\n * and comes back to its own place in the stack.\n */\nexport function hiddenSpans(\n  count: number,\n  valueOf: SeriesValueOf,\n  series: readonly string[],\n  shown: readonly string[],\n  stack: ChartStack,\n  stackOf: (key: string) => string = () => '',\n): Record<string, (Span | null)[]> {\n  return Object.fromEntries(\n    series\n      .filter((key) => !shown.includes(key))\n      .map((key) => {\n        const order = series.filter((k) => k === key || shown.includes(k))\n        const zeroed: SeriesValueOf = (k, at) => (k === key ? 0 : valueOf(k, at))\n        return [key, seriesSpans(count, zeroed, order, stack, stackOf)[key] ?? []]\n      }),\n  )\n}\n\n/** The stacks of a stacked chart, in the order their first series is written: one for each `stack` in the config. */\nexport function stacksOf(keys: readonly string[], stackOf: (key: string) => string) {\n  return [...new Set(keys.map(stackOf))]\n}\n\n/** The lowest and highest value any span reaches, always taking in zero, where bars start. */\nexport function spanExtent(spans: Record<string, readonly (Span | null)[]>): Span {\n  let low = 0\n  let high = 0\n  for (const series of Object.values(spans)) {\n    for (const span of series) {\n      if (!span) continue\n      low = Math.min(low, span[0], span[1])\n      high = Math.max(high, span[0], span[1])\n    }\n  }\n  return [low, high]\n}\n\n/**\n * How far from zero the spans of `keys` in row `index` reach: the highest\n * value above zero, or with `below`, the lowest below it. Zero when none do.\n */\nexport function reachOf(\n  spans: Record<string, readonly (Span | null)[]>,\n  keys: readonly string[],\n  index: number,\n  below = false,\n): number {\n  let far = 0\n  for (const key of keys) {\n    const span = spans[key]?.[index]\n    if (!span) continue\n    far = below ? Math.min(far, span[0], span[1]) : Math.max(far, span[0], span[1])\n  }\n  return far\n}\n\n/** Whether every value in `data` under `keys` is a whole number, so its ticks should be too. */\nexport function allWhole(data: readonly ChartDatum[], keys: readonly string[]): boolean {\n  return data.every((row) =>\n    keys.every((key) => {\n      const range = rangeOf(row[key])\n      if (range) return Number.isInteger(range[0]) && Number.isInteger(range[1])\n      const value = numberOf(row[key])\n      return value === null || Number.isInteger(value)\n    }),\n  )\n}\n\n/** The physical start of `band` from the left, or from the top for an axis that runs down. */\nexport function physicalStart(\n  band: Band,\n  axis: 'inline' | 'block',\n  direction: ReadingDirection,\n): number {\n  return axis === 'inline' && direction === 'rtl'\n    ? 1 - band.start - band.size\n    : band.start\n}\n\n/**\n * The point on a category at `along` of the value axis, centred across its\n * `band`, as fractions of the plot from its physical left and top: where a\n * tooltip or a value label sits. A tooltip there opens past the marks' far\n * end: above upright ones, and after lying ones in reading order.\n */\nexport function plotPoint(\n  band: Band,\n  along: number,\n  orientation: ChartOrientation,\n  direction: ReadingDirection,\n): { x: number; y: number; side: 'top' | 'inline-end' } {\n  const centre =\n    physicalStart(band, orientation === 'vertical' ? 'inline' : 'block', direction) +\n    band.size / 2\n  if (orientation === 'vertical') return { x: centre, y: 1 - along, side: 'top' }\n  return { x: direction === 'rtl' ? 1 - along : along, y: centre, side: 'inline-end' }\n}\n\n/**\n * The step from `index` that a key asks for along the categories, or null\n * for a key that isn't one of the chart's. The keys follow the WAI-ARIA\n * slider, whose value is `sliderValue`: Up and the arrow pointing along\n * reading order raise it, Down and the other arrow lower it, Page Up and\n * Page Down move a tenth of the way, and Home and End go to its ends.\n */\nexport function stepIndex(\n  key: string,\n  index: number,\n  count: number,\n  orientation: ChartOrientation,\n  direction: ReadingDirection,\n): number | null {\n  if (count === 0) return null\n  const page = Math.max(1, Math.round(count / 10))\n  const forward = direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight'\n  const back = direction === 'rtl' ? 'ArrowRight' : 'ArrowLeft'\n  const value = sliderValue(index, count, orientation)\n  const next =\n    key === 'ArrowUp' || key === forward\n      ? value + 1\n      : key === 'ArrowDown' || key === back\n        ? value - 1\n        : key === 'PageUp'\n          ? value + page\n          : key === 'PageDown'\n            ? value - page\n            : key === 'Home'\n              ? 1\n              : key === 'End'\n                ? count\n                : null\n  if (next === null) return null\n  return indexOfValue(Math.min(count, Math.max(1, next)), count, orientation)\n}\n\n/**\n * The slider value of the category at `index`, from 1 to `count`: along\n * reading order for upright bars, and from the bottom for lying ones, which\n * run down the page, so Up raises it as the slider pattern asks.\n */\nexport function sliderValue(index: number, count: number, orientation: ChartOrientation) {\n  return orientation === 'vertical' ? index + 1 : count - index\n}\n\nfunction indexOfValue(value: number, count: number, orientation: ChartOrientation) {\n  return orientation === 'vertical' ? value - 1 : count - value\n}\n\n/**\n * Where a point is along the category axis of a plot whose box is `box`, as\n * a fraction from the reading start: across the page for upright bars, down\n * it for lying ones.\n */\nexport function alongCategories(\n  point: { x: number; y: number },\n  box: { left: number; top: number; width: number; height: number },\n  orientation: ChartOrientation,\n  direction: ReadingDirection,\n): number {\n  if (orientation === 'horizontal') {\n    return box.height === 0 ? 0 : (point.y - box.top) / box.height\n  }\n  const fromLeft = box.width === 0 ? 0 : (point.x - box.left) / box.width\n  return direction === 'rtl' ? 1 - fromLeft : fromLeft\n}\n\n/**\n * The column a category's trigger fills, so the columns meet: from halfway\n * to the category before to halfway to the next, and out to the ends for the\n * first and last, as fractions from the physical left, or the top.\n */\nexport function columnOf(\n  index: number,\n  centres: readonly number[],\n  orientation: ChartOrientation,\n  direction: ReadingDirection,\n): Band {\n  const centre = centres[index] ?? 0\n  const before = centres[index - 1]\n  const after = centres[index + 1]\n  const start = before === undefined ? 0 : (before + centre) / 2\n  const end = after === undefined ? 1 : (centre + after) / 2\n  const size = end - start\n  return orientation === 'vertical' && direction === 'rtl'\n    ? { start: 1 - end, size }\n    : { start, size }\n}\n\n/**\n * The change from `previous` to `value` as a share of `previous`'s size,\n * such as 0.25 for a quarter up, or null when there is nothing to compare\n * with: no previous value, or a previous value of zero.\n */\nexport function changeSince(value: unknown, previous: unknown): number | null {\n  const now = numberOf(value)\n  const before = numberOf(previous)\n  if (now === null || before === null || before === 0) return null\n  return (now - before) / Math.abs(before)\n}\n\n/** A value worked out from the data, for a reference line. */\nexport type ChartSummary = 'average' | 'median' | 'min' | 'max'\n\n/** The `kind` of `values`, missing ones left out, or null with none to go on. */\nexport function summaryOf(values: readonly unknown[], kind: ChartSummary): number | null {\n  const numbers = values.flatMap((value) => {\n    const number = numberOf(value)\n    return number === null ? [] : [number]\n  })\n  if (numbers.length === 0) return null\n  if (kind === 'min') return Math.min(...numbers)\n  if (kind === 'max') return Math.max(...numbers)\n  if (kind === 'average') return numbers.reduce((all, n) => all + n, 0) / numbers.length\n  const sorted = numbers.toSorted((a, b) => a - b)\n  const middle = Math.floor(sorted.length / 2)\n  return sorted.length % 2 === 1\n    ? sorted[middle]!\n    : (sorted[middle - 1]! + sorted[middle]!) / 2\n}\n\n/**\n * How many categories one label stands for, so labels `minLength` px long\n * never crowd an axis `length` px long: 1 shows every label, 2 every other.\n */\nexport function labelStep(count: number, length: number, minLength: number): number {\n  if (count === 0 || length <= 0) return 1\n  return Math.max(1, Math.ceil((count * minLength) / length))\n}\n\n/**\n * About how long a category's label is, in px, at the axis's 12px text: each\n * character at about its width in a sans-serif such as Geist or Inter, and\n * room either side. Close enough to thin out a long run of labels without\n * measuring each one, and to lay an axis out as it will look before the font\n * is known.\n */\nexport function labelLength(text: string): number {\n  let length = 12\n  for (const character of text) length += characterWidth(character)\n  return length\n}\n\n/** About how wide a character is at 12px, by its kind. */\nfunction characterWidth(character: string): number {\n  if (/\\d/.test(character)) return 7.7\n  if (character === ' ') return 3\n  if (/[A-Z]/.test(character)) return 8.1\n  if (/[a-z]/.test(character)) return 6.2\n  // Han, kana and hangul, a full em each.\n  if (/[\\u2e80-\\u9fff\\uac00-\\ud7af\\uff00-\\uffef]/.test(character)) return 12\n  if (/\\p{L}/u.test(character)) return 6.6\n  return 4\n}\n\n/**\n * Where a name `width` px wide sits on an axis `length` px long, as its\n * start and end in px: centred on `centre` (a fraction of the axis), but\n * kept inside it, so a whole name at either end stays in view.\n */\nexport function labelBox(centre: number, width: number, length: number): Span {\n  const start = Math.min(\n    Math.max(0, centre * length - width / 2),\n    Math.max(0, length - width),\n  )\n  return [start, start + width]\n}\n\n/** Whether two names' boxes come closer than `gap` px. */\nexport function labelsMeet(a: Span, b: Span, gap = 4): boolean {\n  return a[0] < b[1] + gap && b[0] < a[1] + gap\n}\n\n/**\n * How far apart a category axis's names sit, as a share of the axis: an even\n * share each, or less where they don't fill it, as the columns of a grid of\n * hexagons don't, half a cell short of its end.\n */\nexport function namePitch(names: readonly { centre: number }[]): number {\n  if (names.length === 0) return 0\n  const even = 1 / names.length\n  if (names.length === 1) return even\n  // Evenly spread names sit an even share apart, give or take the float's last digits.\n  const apart = Math.abs(names[1]!.centre - names[0]!.centre)\n  return apart < even - 1e-9 ? apart : even\n}\n\n/**\n * The names a category axis `length` px long shows, as `skipped` indexes, and\n * the room each has, in px: every few in a long run, each `minLength` px or\n * more apart, and none that would meet the lit name or the last one shown, as\n * a name kept inside the axis at either end can. Each name has its centre, a\n * share of the axis, and its width in px; the lit one shows whole.\n */\nexport function axisNames(\n  names: readonly { centre: number; width: number }[],\n  length: number,\n  { minLength, gap, lit = null }: { minLength: number; gap: number; lit?: number | null },\n): { every: number; room: number; skipped: Set<number> } {\n  const pitch = namePitch(names) * length\n  // Less a hair, so a name that fits exactly isn't pushed to the next step by the float's last digits.\n  const every = pitch <= 0 ? 1 : Math.max(1, Math.ceil(minLength / pitch - 1e-9))\n  const room = names.length === 0 ? 0 : Math.max(0, pitch * every - gap)\n  const skipped = new Set<number>()\n  const litName = lit === null ? undefined : names[lit]\n  const litBox = litName ? labelBox(litName.centre, litName.width, length) : null\n  let last: Span | null = null\n  names.forEach((name, index) => {\n    if (index === lit) return\n    const box = labelBox(name.centre, Math.min(name.width, room), length)\n    if (\n      index % every !== 0 ||\n      (litBox !== null && labelsMeet(box, litBox)) ||\n      (last !== null && labelsMeet(box, last))\n    ) {\n      skipped.add(index)\n      return\n    }\n    last = box\n  })\n  return { every, room, skipped }\n}\n\n/**\n * The order a cascade reaches the bar at `index` among `count`, from 0 for\n * the first to 1 for the last: from the reading start, from the end, or out\n * from the centre. `rank` orders them by value instead, 0 for the largest.\n */\nexport function cascadeAt(\n  index: number,\n  count: number,\n  from: 'start' | 'end' | 'centre' = 'start',\n  rank?: number,\n): number {\n  if (count <= 1) return 0\n  if (rank !== undefined) return rank / (count - 1)\n  if (from === 'end') return (count - 1 - index) / (count - 1)\n  if (from === 'centre') {\n    const middle = (count - 1) / 2\n    return middle === 0 ? 0 : Math.abs(index - middle) / middle\n  }\n  return index / (count - 1)\n}\n\n/** A point of a chart whose x is a value too, such as a scatter's: its two values. */\nexport interface XYValue {\n  x: number\n  y: number\n}\n\n/**\n * The point nearest `at` among `points`, each placed as fractions of a plot\n * `size` px across from its physical left and its top, and measured in px,\n * so a wide plot doesn't favour points above and below. A missing point is\n * skipped; null with none.\n */\nexport function nearestPoint(\n  points: readonly (XYValue | null)[],\n  at: XYValue,\n  size: { width: number; height: number },\n): number | null {\n  let nearest: number | null = null\n  let distance = Infinity\n  points.forEach((point, index) => {\n    if (!point) return\n    const dx = (point.x - at.x) * size.width\n    const dy = (point.y - at.y) * size.height\n    const squared = dx * dx + dy * dy\n    if (squared < distance) {\n      nearest = index\n      distance = squared\n    }\n  })\n  return nearest\n}\n\n/**\n * Where a key goes from the point at `from`, among points placed by two\n * values, or null for a key that isn't the chart's. The arrows along the x\n * axis step to the next point by x, the one pointing along reading order to\n * a higher one, and Up and Down to the next by y; Page Up and Page Down move\n * a tenth of the way by x, and Home and End go to the lowest and highest x.\n * Points that tie take their y, then their place in the data, so every\n * point is reached.\n */\nexport function stepPoint(\n  points: readonly XYValue[],\n  from: number,\n  key: string,\n  direction: ReadingDirection,\n): number | null {\n  if (points.length === 0) return null\n  const forward = direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight'\n  const back = direction === 'rtl' ? 'ArrowRight' : 'ArrowLeft'\n  const order = pointOrder(points, keyAxis(key))\n  const at = Math.max(0, order.indexOf(from))\n  const page = Math.max(1, Math.round(points.length / 10))\n  const next =\n    key === forward || key === 'ArrowUp'\n      ? at + 1\n      : key === back || key === 'ArrowDown'\n        ? at - 1\n        : key === 'PageUp'\n          ? at + page\n          : key === 'PageDown'\n            ? at - page\n            : key === 'Home'\n              ? 0\n              : key === 'End'\n                ? order.length - 1\n                : null\n  if (next === null) return null\n  return order[Math.min(order.length - 1, Math.max(0, next))] ?? null\n}\n\n/** The axis a key steps along among points placed by two values: Up and Down step by y, every other key by x. */\nexport function keyAxis(key: string): 'x' | 'y' {\n  return key === 'ArrowUp' || key === 'ArrowDown' ? 'y' : 'x'\n}\n\n/** The points' indexes from the lowest `along` value up, ties taking the other value, then their place in the data. */\nfunction pointOrder(points: readonly XYValue[], along: 'x' | 'y'): number[] {\n  const other = along === 'x' ? 'y' : 'x'\n  return points\n    .map((point, index) => ({ point, index }))\n    .toSorted(\n      (a, b) =>\n        a.point[along] - b.point[along] ||\n        a.point[other] - b.point[other] ||\n        a.index - b.index,\n    )\n    .map(({ index }) => index)\n}\n\n/**\n * The place of the point at `index` among `points` along `along`, from 1,\n * in the order the arrows on that axis step through: a slider's value over\n * them, so the key that steps to a higher point raises it.\n */\nexport function pointRank(\n  points: readonly XYValue[],\n  index: number,\n  along: 'x' | 'y' = 'x',\n): number {\n  return Math.max(0, pointOrder(points, along).indexOf(index)) + 1\n}\n\n/**\n * A cell of a chart drawn as a grid of cells, such as a heatmap's: its\n * column, from 0 at the reading start, and its row, from 0 at the top.\n */\nexport interface GridCell {\n  column: number\n  row: number\n}\n\n/**\n * Where a key goes from the cell at `from` among `cells`, as the WAI-ARIA\n * grid's keys move: the arrow pointing along reading order to the next\n * column and the other to the one before, Up and Down a row, Home and End\n * to the first and last cell of its row, and Page Up and Page Down to the\n * top and the bottom of its column. Where no cell is there, past an edge,\n * the cell reached stays. Null for a key that isn't the chart's.\n */\nexport function stepCell(\n  cells: readonly GridCell[],\n  from: number,\n  key: string,\n  direction: ReadingDirection,\n): number | null {\n  const at = cells[from]\n  if (!at) return null\n  const forward = direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight'\n  const back = direction === 'rtl' ? 'ArrowRight' : 'ArrowLeft'\n  const inRow = (index: number) => cells[index]?.row === at.row\n  const inColumn = (index: number) => cells[index]?.column === at.column\n  const indexes = cells.map((_, index) => index)\n  const ends = (\n    keep: (index: number) => boolean,\n    along: 'column' | 'row',\n    last: boolean,\n  ) =>\n    indexes\n      .filter(keep)\n      .reduce((best, index) =>\n        cells[index]![along] > cells[best]![along] === last ? index : best,\n      )\n  const target =\n    key === forward\n      ? { column: at.column + 1, row: at.row }\n      : key === back\n        ? { column: at.column - 1, row: at.row }\n        : key === 'ArrowUp'\n          ? { column: at.column, row: at.row - 1 }\n          : key === 'ArrowDown'\n            ? { column: at.column, row: at.row + 1 }\n            : null\n  if (target) {\n    const found = cells.findIndex(\n      (cell) => cell.column === target.column && cell.row === target.row,\n    )\n    return found === -1 ? from : found\n  }\n  if (key === 'Home') return ends(inRow, 'column', false)\n  if (key === 'End') return ends(inRow, 'column', true)\n  if (key === 'PageUp') return ends(inColumn, 'row', false)\n  if (key === 'PageDown') return ends(inColumn, 'row', true)\n  return null\n}\n\n/**\n * The column and row under `at`, a point given as fractions of a grid of\n * `columns` by `rows` from its physical left and its top: columns run from\n * the reading start. A point past an edge takes the cell at that edge.\n */\nexport function gridCellAt(\n  at: { x: number; y: number },\n  columns: number,\n  rows: number,\n  direction: ReadingDirection,\n): GridCell {\n  const along = direction === 'rtl' ? 1 - at.x : at.x\n  const clamp = (value: number, count: number) =>\n    Math.min(count - 1, Math.max(0, Math.floor(value * count)))\n  return { column: clamp(along, columns), row: clamp(at.y, rows) }\n}\n\n/**\n * Where a step up (-1) or down (1) `order`, drawn top first, lands from\n * `from`: Up and Down through a chart's series. From none, or from one not\n * in it, Up goes to the top and Down to the bottom, as they point; a step\n * past either end goes back to none, so every series shows again.\n */\nexport function stepThrough(\n  order: readonly string[],\n  from: string | null,\n  step: -1 | 1,\n): string | null {\n  const at = from === null ? -1 : order.indexOf(from)\n  if (at === -1) return (step === -1 ? order[0] : order.at(-1)) ?? null\n  return order[at + step] ?? null\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-math.ts"
    },
    {
      "path": "registry/lib/chart-scale.ts",
      "content": "import { labelBox, labelsMeet, type Span } from '@/registry/lib/chart-math'\nimport {\n  timeIntervals,\n  timeTicks,\n  type TimeUnit,\n  timeUnitOf,\n  unitLength,\n  type Weekday,\n} from '@/registry/lib/dates'\nimport { nice, ticks } from 'd3-array'\n\n/*\n * A chart's scales: where a value sits along an axis, as a fraction of its\n * length, and back. One union, so every part that places something reads\n * any axis the same way: a band of categories, which bars stand in; points\n * of categories, edge to edge, which lines run through; numbers; and\n * times, as instants. A log scale is one more member. Every function\n * here is pure: the frame makes the scales from the data and the props\n * while the chart renders, so the server draws the range the browser does.\n */\n\n/** One end of a value axis: a value of its own, or `'auto'` to fit the data. */\ntype DomainEnd = number | 'auto'\n\n/** A stretch of an axis, as fractions of its length, measured from where reading starts. */\ninterface Band {\n  start: number\n  size: number\n}\n\n/** How much room categories leave, each a share of one category's step, as in d3's band scale. */\ninterface BandGaps {\n  /** Between two categories. */\n  gap?: number\n  /** Before the first and after the last. */\n  outer?: number\n}\n\n/** Numbers along an axis, from the value at its start to the value at its end. */\ninterface LinearScale {\n  kind: 'linear'\n  /** The values at the axis's two ends. */\n  domain: Span\n  /** The values a tick and a grid line mark, lowest first. */\n  ticks: readonly number[]\n  /**\n   * The round ticks it marks where its axis has room for only about `count`,\n   * lowest first: the coarser steps a short axis shows. `ticks` at the count\n   * it was made with, or more.\n   */\n  ticksFor: (count: number) => readonly number[]\n  /** Where `value` sits, from 0 at the axis's start to 1 at its end, held inside them. */\n  place: (value: number) => number\n  /** The value at `fraction` of the axis, past its ends too. */\n  valueAt: (fraction: number) => number\n}\n\n/**\n * Categories along an axis, in the data's order, from the reading start: as\n * bands, which bars stand in, or as points edge to edge, the first at the\n * start and the last at the end, which a line runs through.\n */\ninterface CategoryScale {\n  kind: 'band' | 'point'\n  /** Each category's key, in order. */\n  keys: readonly string[]\n  /** The band of the category at `index`; a point's has no size. */\n  bandAt: (index: number) => Band\n  /** Where the category keyed `key` sits: its band's centre, or null for one not on the axis. */\n  place: (key: string) => number | null\n  /** The category nearest `fraction` of the axis: the next one from halfway between two, the first or last past the ends. */\n  valueAt: (fraction: number) => string | null\n}\n\n/**\n * Times along an axis, as instants in ms, each where it falls, so a missing\n * date stays a gap. Its ticks fall on the calendar of `timeZone`'s clock.\n */\ninterface TimeScale {\n  kind: 'time'\n  /** The instants at the axis's two ends. */\n  domain: Span\n  /** The clock its ticks and times are written on: UTC for calendar values, which name no zone. */\n  timeZone: string\n  /** The finest unit its times hold, which a time is written as fine as. */\n  unit: Exclude<TimeUnit, 'week'>\n  /** The instants of every tick it may mark, earliest first. */\n  ticks: readonly number[]\n  /**\n   * The ticks of each calendar step that fits its span, coarsest first, such\n   * as quarters, months and weeks: an axis shows the finest its length has\n   * room for (`timeLadder`).\n   */\n  tickSets: readonly (readonly number[])[]\n  /**\n   * Where `time` sits, from 0 at the axis's start to 1 at its end, and past\n   * them for a time outside its domain, as the rows of a window before and\n   * after it are.\n   */\n  place: (time: number) => number\n  /** The instant at `fraction` of the axis, past its ends too. */\n  valueAt: (fraction: number) => number\n  /** The band a mark at `time` stands in, centred on it: as wide as bars on the closest two times allow, or none for points. */\n  bandOf: (time: number) => Band\n  /**\n   * The time the axis shows of a longer stretch it scrolls along, such as a\n   * live chart's, in ms, its domain at one moment and its ticks running on\n   * past both ends; null for an axis that shows all of its times.\n   */\n  window: number | null\n}\n\ntype ChartScale = LinearScale | CategoryScale | TimeScale\n\ninterface LinearScaleOptions {\n  domain?: readonly [DomainEnd, DomainEnd]\n  /** About how many ticks to mark. */\n  tickCount?: number\n  /** Round the ends left to fit the data out to the next tick. */\n  nice?: boolean\n  /** Ticks between whole numbers, such as 0.5; off for counts. */\n  allowDecimals?: boolean\n  /** The ticks to mark, in place of round ones; the ends left to fit reach them. */\n  tickValues?: readonly number[]\n}\n\n/**\n * The scale of a value axis that shows `extent`. Given its ends the other\n * way round, it runs from the higher value, as ranks do, 1 at the top. An end left to fit the data\n * is rounded out to the next tick, so the tallest bar never touches the\n * edge; an end given stays exactly as given. With no range to show (no data,\n * or every value zero), it shows 0 to 1. With `nice` off, the ends stay where\n * the data reaches, as shares stacked to fill the axis do.\n */\nfunction linearScale(\n  extent: Span,\n  {\n    domain = ['auto', 'auto'],\n    tickCount = 5,\n    nice: rounded = true,\n    allowDecimals = true,\n    tickValues,\n  }: LinearScaleOptions = {},\n): LinearScale {\n  const reach = tickValues?.length ? extentWith(extent, tickValues) : extent\n  let low = domain[0] === 'auto' ? reach[0] : domain[0]\n  let high = domain[1] === 'auto' ? reach[1] : domain[1]\n  if (low === high) {\n    if (domain[1] === 'auto') high = low + 1\n    else low = high - 1\n  }\n  if (rounded && !tickValues?.length) {\n    const [niceLow, niceHigh] = nice(low, high, tickCount)\n    if (domain[0] === 'auto') low = niceLow\n    if (domain[1] === 'auto') high = niceHigh\n    if (!allowDecimals) {\n      if (domain[0] === 'auto') low = Math.floor(low)\n      if (domain[1] === 'auto') high = Math.ceil(high)\n    }\n  }\n  if (tickValues?.length) {\n    return linearOver(\n      [low, high],\n      [...tickValues]\n        .filter((tick) => tick >= Math.min(low, high) && tick <= Math.max(low, high))\n        .toSorted((a, b) => a - b),\n    )\n  }\n  const marked = wholeTicks(low, high, tickCount, allowDecimals)\n  return linearOver([low, high], marked, (count) =>\n    count >= tickCount ? marked : wholeTicks(low, high, count, allowDecimals),\n  )\n}\n\n/**\n * The scale of numbers from `domain[0]` to `domain[1]`, marking `marked`, and\n * `ticksFor` where its axis is short: the same ticks by default.\n */\nfunction linearOver(\n  domain: Span,\n  marked: readonly number[],\n  ticksFor: (count: number) => readonly number[] = () => marked,\n): LinearScale {\n  const [low, high] = domain\n  return {\n    kind: 'linear',\n    domain,\n    ticks: marked,\n    ticksFor,\n    place: (value) =>\n      high === low ? 0 : Math.min(1, Math.max(0, (value - low) / (high - low))),\n    valueAt: (fraction) => low + fraction * (high - low),\n  }\n}\n\n/** `extent` stretched to take in `values` too, such as a reference line's. */\nfunction extentWith(extent: Span, values: readonly number[]): Span {\n  return [Math.min(extent[0], ...values), Math.max(extent[1], ...values)]\n}\n\n/**\n * `extent` stretched so `room` px are left past each end that has values on\n * it, along an axis `length` px long, for labels that sit beyond the bars.\n */\nfunction extentWithRoom(extent: Span, room: number, length: number): Span {\n  const [low, high] = extent\n  const ends = (high > 0 ? 1 : 0) + (low < 0 ? 1 : 0)\n  if (room <= 0 || ends === 0 || length <= room * ends) return extent\n  const grow = ((high - low) * room) / (length - room * ends)\n  return [low < 0 ? low - grow : low, high > 0 ? high + grow : high]\n}\n\n/**\n * The lowest and highest of `values`, numbers placed along an axis of their\n * own such as a scatter's, or 0 to 1 with none. Values that are all the same\n * get a range around them, a tenth of their size each way, so a single point\n * sits in the middle of the plot rather than in its corner.\n */\nfunction numberExtent(values: readonly number[]): Span {\n  if (values.length === 0) return [0, 1]\n  const low = Math.min(...values)\n  const high = Math.max(...values)\n  if (low !== high) return [low, high]\n  const room = Math.abs(low) / 10 || 1\n  return [low - room, high + room]\n}\n\n/**\n * Where marks grow from on `scale`, as a fraction of the axis: `base`, zero\n * by default, held inside the axis's ends, so bars stand on the lower end of\n * a range above zero.\n */\nfunction baselineOf(scale: LinearScale, base = 0): number {\n  const [low, high] = scale.domain\n  return scale.place(Math.min(Math.max(low, high), Math.max(Math.min(low, high), base)))\n}\n\n/**\n * About how many ticks an axis `length` px long has room for, at most\n * `count`: each at least `spacing` px from the next, and never fewer than\n * two. Before the axis is measured, `count`.\n */\nfunction tickCountFor(count: number, length: number, spacing: number): number {\n  if (length <= 0) return count\n  return Math.max(2, Math.min(count, Math.floor(length / spacing)))\n}\n\n/** Which of an axis's ticks show while its length is at least `from` px and below `to`. */\ninterface TickStep {\n  from: number\n  /** Null past the longest step. */\n  to: number | null\n  shown: readonly number[]\n}\n\n/**\n * The ticks an axis draws, and which show at each of its lengths: `scale`'s\n * `ticksFor` the count of `spacing` px the axis holds, never fewer than two,\n * which d3 rounds to its nearest round step. A short axis shows coarser\n * round steps, such as 0, 5 and 10 in place of every 2, with the same range.\n * Container queries read the steps, so they are right from the first paint,\n * before the axis is measured. One step alone when the length changes none.\n */\nfunction tickLadder(\n  scale: LinearScale,\n  spacing: number,\n): { ticks: readonly number[]; steps: readonly TickStep[] } {\n  const steps: TickStep[] = []\n  for (let count = 2; ; count += 1) {\n    const shown = scale.ticksFor(count)\n    const last = steps.at(-1)\n    const from = count === 2 ? 0 : count * spacing\n    if (!last || !sameTicks(last.shown, shown)) {\n      if (last) last.to = from\n      steps.push({ from, to: null, shown })\n    }\n    if (shown === scale.ticks || sameTicks(shown, scale.ticks)) break\n  }\n  const ticks = [...new Set(steps.flatMap((step) => step.shown))].toSorted(\n    (a, b) => a - b,\n  )\n  return { ticks, steps }\n}\n\nfunction sameTicks(a: readonly number[], b: readonly number[]) {\n  return a.length === b.length && a.every((tick, at) => tick === b[at])\n}\n\n/** d3's round ticks, or with `allowDecimals` off, only the whole ones, at least a step of 1 apart. */\nfunction wholeTicks(low: number, high: number, count: number, allowDecimals: boolean) {\n  const round = ticks(low, high, count)\n  if (allowDecimals) return round\n  const whole = round.filter((tick) => Number.isInteger(tick))\n  // Round ticks over a wide range are whole already, however few; only a step under 1 counts up by ones.\n  if (whole.length >= 2 || whole.length === round.length) return whole\n  const out: number[] = []\n  for (let tick = Math.ceil(low); tick <= Math.floor(high); tick += 1) out.push(tick)\n  return out\n}\n\n/**\n * How values placed by where they fall, sorted and each once, spread along\n * an axis: its ends, and the share of it a band takes. As points, the\n * first value is at the start and the last at the end; as bands with\n * `gaps`, each band is the closest two values' gap less the gap between\n * categories, with half a band and the outer gap of room at each end, so\n * values an even step apart lay out exactly as bands of categories do. One\n * value alone has `alone` on each side, as if its neighbours were that far.\n */\nfunction spreadAlong(\n  values: readonly number[],\n  gaps: BandGaps | null,\n  alone: number,\n  steady = false,\n): { domain: Span; size: number } {\n  const first = values[0]\n  const last = values.at(-1)\n  if (first === undefined || last === undefined) return { domain: [0, 1], size: 0 }\n  const apart = values.slice(1).map((value, at) => value - values[at]!)\n  // The closest two keep bars apart; on a window that scrolls, the usual gap does, so one late\n  // row doesn't thin every bar while it crosses the plot.\n  const step = apart.length === 0 ? alone : steady ? middleOf(apart) : Math.min(...apart)\n  if (gaps === null) {\n    return {\n      domain: values.length > 1 ? [first, last] : [first - alone, first + alone],\n      size: 0,\n    }\n  }\n  const { gap = 0.3, outer = 0.15 } = gaps\n  const room = step * (outer + (1 - gap) / 2)\n  const domain: Span = [first - room, last + room]\n  return { domain, size: (step * (1 - gap)) / (domain[1] - domain[0]) }\n}\n\n/**\n * How `times` spread along an axis whose bars stand on `bands.times`: as\n * wide as the bars' own times allow, with the domain reaching every time.\n * With no bars, or none with a row, the times lie edge to edge.\n */\nfunction spreadOf(\n  times: readonly number[],\n  bands: TimeScaleOptions['bands'],\n  alone: number,\n  steady: boolean,\n): { domain: Span; size: number } {\n  if (!bands || bands.times.length === 0) return spreadAlong(times, null, alone, steady)\n  const bars = spreadAlong(bands.times, bands.gaps, alone, steady)\n  const first = times[0] ?? bars.domain[0]\n  const last = times.at(-1) ?? bars.domain[1]\n  const domain: Span = [Math.min(first, bars.domain[0]), Math.max(last, bars.domain[1])]\n  const length = domain[1] - domain[0]\n  return {\n    domain,\n    size: length === 0 ? 0 : (bars.size * (bars.domain[1] - bars.domain[0])) / length,\n  }\n}\n\n/** The middle of `values`, or the mean of the two in the middle. */\nfunction middleOf(values: readonly number[]): number {\n  const sorted = values.toSorted((a, b) => a - b)\n  const half = Math.floor(sorted.length / 2)\n  return sorted.length % 2 ? sorted[half]! : (sorted[half - 1]! + sorted[half]!) / 2\n}\n\n/** A value axis to line up with another: what its marks reach, and its ends where they are given. */\ninterface AlignInput {\n  /** What the axis's marks and reference lines reach, zero among them when it keeps zero. */\n  extent: Span\n  domain?: readonly [DomainEnd, DomainEnd]\n  /** Ticks between whole numbers, such as 0.5; off for counts. */\n  allowDecimals?: boolean\n}\n\n/** What each step the first axis widens by costs, against how well the marks fill both axes. */\nconst WIDEN_COST = 0.1\n\n/** The round steps a second axis may take, within each power of ten. */\nconst ALIGN_STEPS = [1, 2, 2.5, 5] as const\n\n/** The round thinnings a short aligned axis may take, as every so many of its steps. */\nconst ALIGN_THINNING = [2, 5, 10, 20, 50, 100] as const\n\n/**\n * Two value axes whose ticks fall on the same gridlines: `primary`, as fitted\n * on its own, and a second axis that shows `second`. The second takes the\n * first's number of steps, in a round step of its own, and where both hold\n * zero, their zeros line up; where one must reach further below or above\n * zero, both widen there by whole steps. Of the ways that fit, the one whose\n * marks fill both axes best wins, less a tenth for each step the first axis\n * widens by, then the one with fewer steps. An end\n * given stays as given. Null where they can't line up: the first axis isn't\n * a run of even round ticks with one at each end, or the ends given rule\n * out every way.\n */\nfunction alignScales(\n  primary: {\n    scale: LinearScale\n    extent: Span\n    domain?: readonly [DomainEnd, DomainEnd]\n  },\n  second: AlignInput,\n): { primary: LinearScale; second: LinearScale } | null {\n  const { ticks: marked } = primary.scale\n  const [first, last] = [marked[0], marked.at(-1)]\n  if (first === undefined || last === undefined || marked.length < 2) return null\n  const step = marked[1]! - first\n  const steps = marked.length - 1\n  const [low, high] = primary.scale.domain\n  const even = marked.every((tick, at) => near(tick, first + at * step))\n  if (!even || step <= 0 || !near(low, first) || !near(high, last)) return null\n\n  const [givenLow, givenHigh] = second.domain ?? ['auto', 'auto']\n  let [from, to] = second.extent\n  if (givenLow !== 'auto') from = givenLow\n  if (givenHigh !== 'auto') to = givenHigh\n  if (from === to) to = from + 1\n  const whole = second.allowDecimals === false\n  const fill = (extent: Span, span: number) =>\n    span <= 0 ? 0 : Math.min(1, (extent[1] - extent[0]) / span)\n\n  // Both hold zero at a tick: below it and above it, each axis takes whole steps.\n  const zeroAt = -low / step\n  if (low <= 0 && high >= 0 && near(zeroAt, Math.round(zeroAt)) && from <= 0 && to >= 0) {\n    const below = Math.round(zeroAt)\n    const above = steps - below\n    const primaryLowGiven = (primary.domain?.[0] ?? 'auto') !== 'auto'\n    const primaryHighGiven = (primary.domain?.[1] ?? 'auto') !== 'auto'\n    const most = Math.max(steps * 2, 10)\n    let best: { down: number; up: number; size: number; score: number } | null = null\n    for (let down = below; down <= (primaryLowGiven ? below : most); down += 1) {\n      for (let up = above; up <= (primaryHighGiven ? above : most - down); up += 1) {\n        if (down + up < 1) continue\n        // A given end away from zero sets the step; one at zero only holds that side at none.\n        const sizes =\n          givenHigh !== 'auto' && givenHigh !== 0\n            ? up > 0\n              ? [givenHigh / up]\n              : []\n            : givenLow !== 'auto' && givenLow !== 0\n              ? down > 0\n                ? [-givenLow / down]\n                : []\n              : roundSteps((to - from) / (down + up), whole)\n        for (const size of sizes) {\n          if (!(size > 0)) continue\n          if (givenLow !== 'auto' && !near(-down * size, givenLow)) continue\n          if (givenHigh !== 'auto' && !near(up * size, givenHigh)) continue\n          if (down * size < -from - size * 1e-9 || up * size < to - size * 1e-9) continue\n          // Each step the first axis widens by costs a tenth: it keeps its own steps where the\n          // second fits them at all well.\n          const score =\n            Math.min(\n              fill(primary.extent, (down + up) * step),\n              fill([from, to], (down + up) * size),\n            ) -\n            (down + up - steps) * WIDEN_COST\n          if (\n            !best ||\n            score > best.score + 1e-9 ||\n            (near(score, best.score) && down + up < best.down + best.up)\n          ) {\n            best = { down, up, size, score }\n          }\n        }\n      }\n    }\n    if (!best) return null\n    return {\n      primary: evenScale(-best.down, best.up, step, true),\n      second: evenScale(-best.down, best.up, best.size, true),\n    }\n  }\n\n  // Otherwise the second axis's lowest tick sits on the first's, and it climbs as many steps.\n  let best: { start: number; size: number; score: number } | null = null\n  const sizes =\n    givenLow !== 'auto' && givenHigh !== 'auto'\n      ? [(givenHigh - givenLow) / steps]\n      : roundSteps((to - from) / steps, whole)\n  for (const size of sizes) {\n    if (!(size > 0)) continue\n    const start =\n      givenLow !== 'auto'\n        ? givenLow / size\n        : givenHigh !== 'auto'\n          ? givenHigh / size - steps\n          : Math.floor(from / size + 1e-9)\n    // A given low end stays where it was given, so it must fall on a step.\n    if (!near(start, Math.round(start))) continue\n    if (givenHigh !== 'auto' && !near((start + steps) * size, givenHigh)) continue\n    if (start * size > from + size * 1e-9 || (start + steps) * size < to - size * 1e-9)\n      continue\n    const score = fill([from, to], steps * size)\n    if (!best || score > best.score + 1e-9) best = { start, size, score }\n  }\n  if (!best) return null\n  return {\n    primary: evenScale(first / step, first / step + steps, step, false),\n    second: evenScale(\n      Math.round(best.start),\n      Math.round(best.start) + steps,\n      best.size,\n      false,\n    ),\n  }\n}\n\n/** Whether two values are the same but for floating-point error. */\nfunction near(a: number, b: number) {\n  return Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b))\n}\n\n/** The round steps near `raw`, smallest first: 1, 2, 2.5 and 5 in the powers of ten around it, whole ones only when `whole`. */\nfunction roundSteps(raw: number, whole: boolean): number[] {\n  const power = Math.floor(Math.log10(Math.max(raw, Number.MIN_VALUE)))\n  const out: number[] = []\n  for (let exponent = power - 1; exponent <= power + 1; exponent += 1) {\n    for (const base of ALIGN_STEPS) {\n      const size = exponent < 0 ? base / 10 ** -exponent : base * 10 ** exponent\n      if (whole && !Number.isInteger(size)) continue\n      out.push(size)\n    }\n  }\n  return out\n}\n\n/**\n * The scale from tick `from` to tick `to`, counted in steps of `size` from\n * zero. On a short axis it shows every so many ticks, both ends and, with\n * `zero`, zero among them where a thinning keeps them all; where only the\n * ends and zero would show, every second, fifth or tenth tick from zero\n * shows instead when that is more. The choice rests only on the steps below\n * and above zero, or with no zero, on the count of steps from the lowest,\n * so two axes lined up this way thin out alike.\n */\nfunction evenScale(from: number, to: number, size: number, zero: boolean): LinearScale {\n  const at = (count: number) => {\n    const value = count * size\n    // A step such as 0.1 adds up to 0.30000000000000004; twelve figures hold every real tick.\n    return Number(value.toPrecision(12)) + 0\n  }\n  const [low, high] = [Math.round(from), Math.round(to)]\n  const counts: number[] = []\n  for (let count = low; count <= high; count += 1) counts.push(count)\n  const marked = counts.map(at)\n  // Every so many steps lands on both ends, and on zero where it holds, when it divides each side.\n  const span = zero ? greatestDivisor(-low, high) : high - low\n  const anchor = zero ? 0 : low\n  const every = (step: number) => counts.filter((count) => (count - anchor) % step === 0)\n  return linearOver([at(low), at(high)], marked, (most) => {\n    const room = Math.max(2, most)\n    let shown = [...new Set([low, ...(zero ? [0] : []), high])]\n    for (let step = 1; step <= span; step += 1) {\n      if (span % step !== 0 || every(step).length > room) continue\n      shown = every(step)\n      break\n    }\n    // Where keeping the ends leaves only them, a round thinning that shows more wins, its far end left off.\n    for (const step of ALIGN_THINNING) {\n      const thinned = every(step)\n      if (thinned.length > room) continue\n      if (thinned.length > shown.length) shown = thinned\n      break\n    }\n    return shown.map(at)\n  })\n}\n\n/** The largest whole number that divides both `a` and `b`, which may be 0. */\nfunction greatestDivisor(a: number, b: number): number {\n  return b === 0 ? Math.abs(a) : greatestDivisor(b, a % b)\n}\n\ninterface TimeScaleOptions {\n  /** The clock ticks fall on: UTC for calendar values. */\n  timeZone: string\n  /** The day weeks start on, which a tick a week marks. */\n  firstDay?: Weekday\n  /**\n   * Bars stand on `times`, the times their series have rows at, `gaps`\n   * apart, so a line's rows between them never make them thinner; points,\n   * edge to edge, when null. The domain still reaches every time.\n   */\n  bands: { gaps: BandGaps; times: readonly number[] } | null\n  /**\n   * Shows `length` ms from `from`, of a stretch its ticks cover from the\n   * times, or the window, to `through`, whichever reaches further: an axis\n   * that scrolls, such as a live chart's. Its steps suit the window.\n   */\n  window?: { from: number; length: number; through: number } | null\n}\n\n/**\n * The scale of `times`, instants in ms in order, each once: from the first\n * to the last, or with room for bars at each end, with ticks on\n * `timeZone`'s calendar. With no times, the axis shows the first second of\n * 1970 and marks none.\n */\nfunction timeScale(\n  times: readonly number[],\n  { timeZone, firstDay = 1, bands, window = null }: TimeScaleOptions,\n): TimeScale {\n  const unit = timeUnitOf(times, timeZone)\n  const spread = spreadOf(times, bands, unitLength(unit), window !== null)\n  const domain: Span = window ? [window.from, window.from + window.length] : spread.domain\n  const [low, high] = domain\n  const span = high - low\n  // A window's ticks run on along the stretch it scrolls over, at the steps the window suits.\n  const reach: Span = window\n    ? [\n        Math.min(domain[0], times[0] ?? domain[0]),\n        Math.max(domain[1], times.at(-1) ?? domain[1], window.through),\n      ]\n    : domain\n  const tickSets =\n    times.length === 0 && !window\n      ? []\n      : timeIntervals(span)\n          // No tick finer than the times themselves: days get no 12:00.\n          .filter(\n            (interval) => unitLength(interval.unit) * interval.step >= unitLength(unit),\n          )\n          .map((interval) => timeTicks(reach, interval, timeZone, firstDay))\n          .filter((set) => set.length > 0)\n  const place = (time: number) =>\n    span === 0\n      ? 0.5\n      : window\n        ? (time - low) / span\n        : Math.min(1, Math.max(0, (time - low) / span))\n  // Bars on a window are as wide as their times' gaps along it allow.\n  const size = window\n    ? (spread.size * (spread.domain[1] - spread.domain[0])) / span\n    : spread.size\n  return {\n    kind: 'time',\n    domain,\n    timeZone,\n    unit,\n    ticks: [...new Set(tickSets.flat())].toSorted((a, b) => a - b),\n    tickSets,\n    place,\n    valueAt: (fraction) => low + fraction * span,\n    bandOf: (time) => ({ start: place(time) - size / 2, size }),\n    window: window?.length ?? null,\n  }\n}\n\n/**\n * The least length, in px, an axis needs for labels `widths` px wide at\n * `places`, fractions of it in order, to stand `gap` px apart or more, each\n * kept inside the axis as a name at either end is. Infinity when no length\n * up to 20,000 px does.\n */\nfunction labelsLength(\n  places: readonly number[],\n  widths: readonly number[],\n  gap: number,\n): number {\n  const fits = (length: number) =>\n    places.every((place, at) => {\n      const width = widths[at] ?? 0\n      if (width > length) return false\n      if (at === 0) return true\n      const before = labelBox(places[at - 1]!, widths[at - 1] ?? 0, length)\n      return !labelsMeet(before, labelBox(place, width, length), gap)\n    })\n  let high = 20_000\n  if (!fits(high)) return Number.POSITIVE_INFINITY\n  let low = 0\n  while (high - low > 1) {\n    const middle = Math.floor((low + high) / 2)\n    if (fits(middle)) high = middle\n    else low = middle\n  }\n  return high\n}\n\n/**\n * The least length, in px, an axis needs for labels `widths` px wide,\n * centred on `places`, fractions of it in order that may run past its ends,\n * to stand `gap` px apart or more: those of a window scrolling past.\n */\nfunction passingLength(\n  places: readonly number[],\n  widths: readonly number[],\n  gap: number,\n): number {\n  let least = 0\n  for (let at = 1; at < places.length; at += 1) {\n    const apart = places[at]! - places[at - 1]!\n    const room = ((widths[at - 1] ?? 0) + (widths[at] ?? 0)) / 2 + gap\n    least = Math.max(\n      least,\n      // A float a hair past a whole px rounds onto it rather than past the next.\n      apart > 0 ? Math.ceil(room / apart - 1e-9) : Number.POSITIVE_INFINITY,\n    )\n  }\n  return least\n}\n\n/**\n * Every `k`th of `ticks` from the first, for each `k` from all of them down\n * to every other, coarsest first: what an axis too short for even its\n * coarsest calendar step shows, so its labels never overlap.\n */\nfunction thinned(ticks: readonly number[]): (readonly number[])[] {\n  const sets: (readonly number[])[] = []\n  for (let k = ticks.length; k >= 2; k--) {\n    const set = ticks.filter((_, at) => at % k === 0)\n    if (set.length !== sets.at(-1)?.length) sets.push(set)\n  }\n  return sets\n}\n\n/**\n * The ticks an axis of times draws, and which show at each of its lengths:\n * of `scale`'s calendar steps, the finest whose labels, `width(tick)` px\n * wide, stand `gap` px apart at that length, without its ticks at the axis's\n * ends while only the ticks between fit. Below the coarsest step's own\n * length, every other of its ticks, or fewer, down to the first alone. Read\n * by container queries, as `tickLadder`'s are.\n */\nfunction timeLadder(\n  scale: TimeScale,\n  width: (tick: number) => number,\n  gap: number,\n): { ticks: readonly number[]; steps: readonly TickStep[] } {\n  const steps: TickStep[] = []\n  let least = 0\n  // A tick at either end of the axis is kept inside it, so it needs a step's room more than\n  // the ticks between; each step is tried without those first, then whole.\n  const inner = (set: readonly number[]) =>\n    set.filter((tick) => scale.place(tick) > 0 && scale.place(tick) < 1)\n  // Along a window that scrolls, each step's ticks pass through its ends, so none is kept\n  // inside or thinned by its place, which would change as it scrolls.\n  const scrolls = scale.window !== null\n  const candidates = scrolls\n    ? scale.tickSets\n    : [\n        ...thinned(scale.tickSets[0] ?? []),\n        ...scale.tickSets.flatMap((set) =>\n          set.length > 2 && inner(set).length < set.length ? [inner(set), set] : [set],\n        ),\n      ]\n  for (const set of candidates) {\n    const need = scrolls\n      ? passingLength(set.map(scale.place), set.map(width), gap)\n      : labelsLength(set.map(scale.place), set.map(width), gap)\n    const last = steps.at(-1)\n    if (!last) {\n      steps.push({ from: 0, to: null, shown: set })\n      least = need\n      continue\n    }\n    if (need === Number.POSITIVE_INFINITY) continue\n    // A finer step that needs no more room than the one before takes its place.\n    if (need <= least) {\n      last.shown = set\n      continue\n    }\n    // One that needs more room but shows no more ticks only moves them.\n    if (set.length <= last.shown.length) continue\n    last.to = need\n    steps.push({ from: need, to: null, shown: set })\n    least = need\n  }\n  const ticks = [...new Set(steps.flatMap((step) => step.shown))].toSorted(\n    (a, b) => a - b,\n  )\n  return { ticks, steps }\n}\n\n/** The band of the category at `index` among `count`, in reading order, as d3's band scale lays it out. */\nfunction bandAt(\n  index: number,\n  count: number,\n  { gap = 0.3, outer = 0.15 }: BandGaps = {},\n): Band {\n  const step = 1 / Math.max(1, count - gap + outer * 2)\n  return { start: step * (outer + index), size: step * (1 - gap) }\n}\n\n/** Where the category at `index` among `count` sits as a point: edge to edge, or the middle for one alone. */\nfunction pointAt(index: number, count: number): Band {\n  return { start: count <= 1 ? 0.5 : index / (count - 1), size: 0 }\n}\n\n/** The categories keyed `keys` as bands, `gaps` apart. */\nfunction bandScale(keys: readonly string[], gaps: BandGaps = {}): CategoryScale {\n  return categoryScale('band', keys, (index) => bandAt(index, keys.length, gaps))\n}\n\n/** The categories keyed `keys` as points, edge to edge. */\nfunction pointScale(keys: readonly string[]): CategoryScale {\n  return categoryScale('point', keys, (index) => pointAt(index, keys.length))\n}\n\nfunction categoryScale(\n  kind: CategoryScale['kind'],\n  keys: readonly string[],\n  of: (index: number) => Band,\n): CategoryScale {\n  const centres = keys.map((_, index) => bandCentre(of(index)))\n  const places = new Map(keys.map((key, index) => [key, centres[index]!]))\n  return {\n    kind,\n    keys,\n    bandAt: of,\n    place: (key) => places.get(key) ?? null,\n    valueAt: (fraction) => {\n      const index = indexAt(fraction, centres)\n      return index === null ? null : (keys[index] ?? null)\n    },\n  }\n}\n\n/** The centre of `band`, as a fraction from the reading start. */\nfunction bandCentre(band: Band): number {\n  return band.start + band.size / 2\n}\n\n/**\n * Which of `centres`, fractions of an axis from its reading start in\n * order, `at` is nearest: the next one from halfway between two; past the\n * ends, the first or last.\n */\nfunction indexAt(at: number, centres: readonly number[]): number | null {\n  if (centres.length === 0) return null\n  // A binary search: the last centre whose halfway point from the one before is at or before `at`.\n  let low = 0\n  let high = centres.length - 1\n  while (low < high) {\n    const middle = (low + high + 1) >> 1\n    if (at >= (centres[middle - 1]! + centres[middle]!) / 2) low = middle\n    else high = middle - 1\n  }\n  return low\n}\n\n/** What tells two scales apart, so what follows a scale moves only when it changes. */\nfunction scaleSignature(scale: ChartScale): string {\n  if (scale.kind === 'linear')\n    return `linear|${scale.domain.join()}|${scale.ticks.join()}`\n  if (scale.kind === 'time')\n    return `time|${scale.timeZone}|${scale.domain.join()}|${scale.ticks.join()}`\n  return `${scale.kind}|${scale.keys.join('\\u0000')}`\n}\n\nexport {\n  alignScales,\n  type Band,\n  type BandGaps,\n  bandAt,\n  bandCentre,\n  bandScale,\n  baselineOf,\n  type CategoryScale,\n  type ChartScale,\n  type DomainEnd,\n  extentWith,\n  extentWithRoom,\n  indexAt,\n  linearOver,\n  linearScale,\n  type LinearScale,\n  type LinearScaleOptions,\n  numberExtent,\n  pointAt,\n  pointScale,\n  scaleSignature,\n  labelsLength,\n  spreadAlong,\n  tickCountFor,\n  tickLadder,\n  type TickStep,\n  timeLadder,\n  timeScale,\n  type TimeScale,\n  type TimeScaleOptions,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-scale.ts"
    }
  ],
  "type": "registry:lib"
}