{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-frame",
  "title": "Chart frame",
  "description": "The cartesian frame: an x axis, a value axis for each axis the config names, and each series’ spans and the tooltip’s place, worked out by the kinds of mark a chart draws. One pure function of the props, so the server draws the range the browser does.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/dates.json"
  ],
  "files": [
    {
      "path": "registry/lib/chart-frame.ts",
      "content": "import {\n  allWhole,\n  type ChartConfig,\n  type ChartDatum,\n  type ChartMark,\n  type ChartStack,\n  numberOf,\n  type SeriesValueOf,\n  type Span,\n  type XYValue,\n} from '@/registry/lib/chart-math'\nimport {\n  alignScales,\n  type Band,\n  type BandGaps,\n  bandScale,\n  baselineOf,\n  type ChartScale,\n  type DomainEnd,\n  extentWith,\n  extentWithRoom,\n  linearScale,\n  type LinearScale,\n  numberExtent,\n  pointScale,\n  timeScale,\n  type TimeScaleOptions,\n} from '@/registry/lib/chart-scale'\nimport { isoInstant, readTime, type Weekday } from '@/registry/lib/dates'\n\n/*\n * The cartesian frame: an x axis, one or more value axes and the marks\n * between them. Each series says in the config what it is drawn as and\n * which value axis it is read against; each kind of mark works out its own\n * series' spans, stacked among themselves, and the frame fits every axis to\n * what its series and reference lines reach. One pure function of the props,\n * so the server draws the same range the browser does. The kinds of mark\n * are in files of their own, and a chart hands the frame only the kinds it\n * draws. On an x of times, a series may bring rows of its own, such as a\n * trend or a second stream: the stops are every dataset's times joined\n * (`joinStops`), and each series is read from its own rows.\n */\n\n/** Each series' span in every row, null for a missing value. */\ntype SeriesSpans = Readonly<Record<string, readonly (Span | null)[]>>\n\n/** What a kind of mark works out from the values of its series on one value axis. */\ninterface MarkKind {\n  mark: ChartMark\n  /** Whether its series stack when the chart stacks, as bars and areas do; lines and points never do. */\n  stacks: boolean\n  /**\n   * Each of `series`' span at each of `count` stops, from its value there\n   * (`valueOf`), in its axis's units: a hidden one where it would sit, so it\n   * leaves from there and comes back to it. `extent` is what the `shown`\n   * ones reach, null with nothing to show. Series with the same `stackOf`\n   * stack together, when the chart stacks.\n   */\n  spans: (input: {\n    count: number\n    valueOf: SeriesValueOf\n    series: readonly string[]\n    shown: readonly string[]\n    stack: ChartStack\n    stackOf: (key: string) => string\n  }) => { spans: SeriesSpans; extent: Span | null }\n  /**\n   * How far row `index`'s marks of the `shown` series reach on `scale`, as\n   * a fraction of the axis: where the tooltip sits over them. Null where none\n   * has a value.\n   */\n  reach: (\n    spans: SeriesSpans,\n    shown: readonly string[],\n    index: number,\n    scale: LinearScale,\n  ) => number | null\n}\n\n/** How a value axis fits what it shows. */\ninterface ValueAxisOptions {\n  /** The values at its ends; `'auto'` fits what its series reach. */\n  domain?: readonly [DomainEnd, DomainEnd]\n  /** About how many ticks it marks, and its ends round out to. */\n  tickCount?: number\n  /** The ticks it marks, in place of round ones. */\n  tickValues?: readonly number[]\n  /** Ticks between whole numbers; by default, only where a value isn't whole. */\n  allowDecimals?: boolean\n  /** Round the ends left to fit out to the next tick. */\n  nice?: boolean\n  /** Keep zero in the range, so marks read in proportion. */\n  zero?: boolean\n  /** The value marks grow from, held inside the range; zero by default. */\n  base?: number\n  /**\n   * On an axis other than the chart's own, its ticks on the own axis's\n   * gridlines, with the zeros lined up (`alignScales`); on by default. Off\n   * fits it to its series alone.\n   */\n  align?: boolean\n}\n\n/** What runs along the x axis: the rows' categories in order, a number of each row's, or a time. */\ntype CartesianX =\n  | { kind: 'category'; keys: readonly string[]; gaps?: BandGaps }\n  | {\n      kind: 'time'\n      /** The key of each row's time. */\n      key: string\n      /** The clock instants are written on; calendar values are written on UTC's, which names no zone. */\n      timeZone: string\n      /** The day weeks start on. */\n      firstDay?: Weekday\n      gaps?: BandGaps\n      /** The stretch of time the plot shows, when it shows less than its rows, as a live chart does: see `timeScale`. */\n      window?: TimeScaleOptions['window']\n    }\n  | {\n      kind: 'number'\n      /** The key of each row's value along the x axis. */\n      key: string\n      domain?: readonly [DomainEnd, DomainEnd]\n      tickCount?: number\n      /** Ticks between whole numbers; by default, only where a value isn't whole. */\n      allowDecimals?: boolean\n    }\n\n/** A value a reference line or area marks, which its axis reaches. */\ninterface ChartReference {\n  /** `'x'`, or a value axis's id. */\n  axis: string\n  value: number\n}\n\ninterface CartesianInput {\n  /** The rows drawn, in order. */\n  rows: readonly ChartDatum[]\n  /** The rows of each series that brings its own, by its key, on an x of times: drawn from them in place of `rows`. */\n  own: Readonly<Record<string, readonly ChartDatum[]>>\n  config: ChartConfig\n  hidden: readonly string[]\n  /** The kinds of mark the chart draws, its own first: a series that names no mark is drawn as that. */\n  kinds: readonly [MarkKind, ...MarkKind[]]\n  stack: ChartStack\n  x: CartesianX\n  /** The chart's own value axis, `'value'`. */\n  y: ValueAxisOptions\n  /** Every other value axis a series names, by its id; one not here fits what it reaches. */\n  axes?: Readonly<Record<string, ValueAxisOptions>>\n  references: readonly ChartReference[]\n  /** The px kept past the ends of the chart's own value axis, `length` px long, for labels beyond the bars. */\n  room: { px: number; length: number }\n}\n\ninterface CartesianModel {\n  x: ChartScale\n  /** How many stops there are along x: the rows, or on an x of times, every dataset's times joined. */\n  count: number\n  /** On an x of times, each stop: its time, and the rows there; null on other axes, whose stops are the rows. */\n  timeStops: readonly JoinedStop[] | null\n  /** On an x of times, a dataset's times (`JoinedStops.timesOf`); null on other axes. */\n  timesOf: JoinedStops['timesOf'] | null\n  /** The row `key` is drawn from at stop `index`: its own, or the chart's for a series with none; null where it has none. */\n  rowOf: (key: string, index: number) => ChartDatum | null\n  /** Each value axis's scale, by its id; the chart's own, `value`, always. */\n  y: Readonly<Record<string, LinearScale>> & { value: LinearScale }\n  /** Where marks grow from on each value axis, as a fraction of it. */\n  baselines: Readonly<Record<string, number>> & { value: number }\n  /** The band the row at `index` stands in along x: its category's, or centred on its time; none along numbers, where rows are points. */\n  bandOf: (index: number) => Band\n  /** The kind of mark of a series. */\n  markOf: (key: string) => ChartMark\n  /** The id of the value axis a series is read against. */\n  axisOf: (key: string) => string\n  /** Whether a series adds to its category's total: a mark that stacks, read against the chart's own value axis, with no rows of its own. */\n  totals: (key: string) => boolean\n  /** The scale of the value axis a series is read against, and where its marks grow from on it, as a fraction of it. */\n  valueAxisOf: (key: string) => { scale: LinearScale; baseline: number }\n  /** The stack a series stacks in, which only its own kind of mark on its axis shares; one with rows of its own stacks alone. */\n  stackOf: (key: string) => string\n  /** Each series' span in every row, a hidden one where it would sit. */\n  spans: SeriesSpans\n  /** How far row `index`'s shown marks reach, as a fraction of the value axis, or null with none. */\n  reach: (index: number) => number | null\n  /**\n   * Row `index` as a point placed by both values, on a numeric x axis: its x\n   * value and its highest shown value, and where they sit along x and up\n   * their value axis, as fractions of each. Null along categories, or where\n   * no shown series has a value.\n   */\n  point: (index: number) => { value: XYValue; place: XYValue } | null\n}\n\n/**\n * Where each kind of mark's layers stack on the plot, whatever order their\n * parts are written in: areas at the back, then bars, lines and points, so\n * a fill never covers a bar and a line or a point is never hidden by one.\n * Reference areas sit behind them all, and reference lines and labels\n * above.\n */\nconst markLayer = {\n  area: 'z-6',\n  bar: 'z-8',\n  line: 'z-10',\n  point: 'z-12',\n} as const satisfies Record<ChartMark, string>\n\n/** The id of the chart's own value axis, which a series reads unless it names another. */\nconst VALUE_AXIS = 'value'\n\n/**\n * The frame of a cartesian chart from its props: the x scale, a scale for\n * each value axis, each series' spans and where the tooltip sits. Throws\n * when a series names a mark the chart doesn't draw.\n */\nfunction cartesianModel(input: CartesianInput): CartesianModel {\n  const { config, hidden, kinds, stack, x, y } = input\n  const series = Object.keys(config)\n  const [own] = kinds\n  const kindOf = new Map(kinds.map((kind) => [kind.mark, kind]))\n  const markOf = (key: string): ChartMark => config[key]?.mark ?? own.mark\n  for (const key of series) {\n    if (!kindOf.has(markOf(key))) {\n      throw new Error(\n        `The series \\`${key}\\` is drawn as \\`${markOf(key)}\\` in the config, which this chart doesn't draw. Draw it in a chart that does, such as the Composed chart.`,\n      )\n    }\n  }\n  const axisOf = (key: string) => config[key]?.axis ?? VALUE_AXIS\n  const { rows } = input\n  // A series with rows of its own has values at its own times only, so it stacks with nothing.\n  const hasOwn = (key: string) => Object.hasOwn(input.own, key)\n  const stacks = (key: string) =>\n    (kindOf.get(markOf(key))?.stacks ?? false) && !hasOwn(key)\n  if (stack === 'expand') {\n    // Shares of a whole and raw values can't share one axis.\n    const stacked = new Set(series.filter(stacks).map(axisOf))\n    const raw = series.find((key) => !stacks(key) && stacked.has(axisOf(key)))\n    if (raw !== undefined) {\n      throw new Error(\n        hasOwn(raw)\n          ? `The series \\`${raw}\\` brings rows of its own, which stack with nothing, on the axis \\`${axisOf(raw)}\\` that the chart stacks as shares of 100%. Give it an \\`axis\\` of its own in the config.`\n          : `The series \\`${raw}\\` is drawn as \\`${markOf(raw)}\\`, which doesn't stack, on the axis \\`${axisOf(raw)}\\` that the chart stacks as shares of 100%. Give it an \\`axis\\` of its own in the config.`,\n      )\n    }\n  }\n  const stackOf = (key: string) =>\n    hasOwn(key)\n      ? `${axisOf(key)}\\u0000\\u0001${key}`\n      : `${axisOf(key)}\\u0000${config[key]?.stack ?? ''}`\n  if (Object.keys(input.own).length > 0 && x.kind !== 'time') {\n    throw new Error(\n      \"A series' own rows need an x of times: give the chart `indexType='time'`.\",\n    )\n  }\n  const joined = x.kind === 'time' ? joinStops(rows, input.own, x.key) : null\n  const count = joined ? joined.stops.length : rows.length\n  const rowOf = joined\n    ? joined.rowOf\n    : (_key: string, index: number) => rows[index] ?? null\n  const valueOf: SeriesValueOf = (key, index) => rowOf(key, index)?.[key]\n  const shown = series.filter((key) => !hidden.includes(key))\n  const axes = [...new Set([VALUE_AXIS, ...series.map(axisOf)])]\n\n  const spans: Record<string, readonly (Span | null)[]> = {}\n  const extents = new Map<string, Span[]>()\n  // Each kind of mark on each axis, and apart from them, its series with rows of their own,\n  // which stack with nothing.\n  const groups = axes.flatMap((axis) =>\n    kinds.flatMap((kind) =>\n      [false, true].map((alone) => ({\n        axis,\n        kind,\n        stack: alone ? ('none' as const) : stack,\n        series: series.filter(\n          (key) =>\n            axisOf(key) === axis && markOf(key) === kind.mark && hasOwn(key) === alone,\n        ),\n      })),\n    ),\n  )\n  for (const group of groups) {\n    if (group.series.length === 0) continue\n    const out = group.kind.spans({\n      count,\n      valueOf,\n      series: group.series,\n      shown: group.series.filter((key) => shown.includes(key)),\n      stack: group.stack,\n      stackOf,\n    })\n    Object.assign(spans, out.spans)\n    if (out.extent)\n      extents.set(group.axis, [...(extents.get(group.axis) ?? []), out.extent])\n  }\n\n  const optionsOf = (axis: string): ValueAxisOptions =>\n    axis === VALUE_AXIS ? y : (input.axes?.[axis] ?? {})\n  const fit = (axis: string): { scale: LinearScale; extent: Span } => {\n    const options = optionsOf(axis)\n    const reached = extents.get(axis) ?? []\n    let extent: Span = reached.length\n      ? [Math.min(...reached.map((e) => e[0])), Math.max(...reached.map((e) => e[1]))]\n      : [0, 0]\n    if (options.zero ?? true) extent = extentWith(extent, [0])\n    extent = extentWith(\n      extent,\n      input.references.filter((ref) => ref.axis === axis).map((ref) => ref.value),\n    )\n    if (axis === VALUE_AXIS)\n      extent = extentWithRoom(extent, input.room.px, input.room.length)\n    const scale = linearScale(extent, {\n      domain: options.domain,\n      tickCount: options.tickCount,\n      tickValues: options.tickValues,\n      nice: options.nice ?? stack !== 'expand',\n      allowDecimals: allowDecimalsOn(axis),\n    })\n    return { scale, extent }\n  }\n  const allowDecimalsOn = (axis: string) =>\n    optionsOf(axis).allowDecimals ??\n    (stack === 'expand' ||\n      !shown\n        .filter((key) => axisOf(key) === axis)\n        .every((key) => allWhole(input.own[key] ?? rows, [key])))\n  const ownAxis = fit(VALUE_AXIS)\n  const others = axes.filter((axis) => axis !== VALUE_AXIS)\n  const fitted = new Map(others.map((axis) => [axis, fit(axis)]))\n  const scales: Record<string, LinearScale> & { value: LinearScale } = {\n    ...Object.fromEntries(others.map((axis) => [axis, fitted.get(axis)!.scale])),\n    value: ownAxis.scale,\n  }\n  // Each other axis's ticks fall on the own axis's gridlines; once one has widened the own axis,\n  // every axis lines up again with it held, so they all share its gridlines.\n  // An axis lines up only with what shows: one whose series are all hidden, or any while the own\n  // axis shows nothing, keeps its own fit.\n  const showing = (axis: string) => shown.some((key) => axisOf(key) === axis)\n  const aligned = showing(VALUE_AXIS)\n    ? others.filter((axis) => (optionsOf(axis).align ?? true) && showing(axis))\n    : []\n  for (const hold of [false, true]) {\n    for (const axis of aligned) {\n      const second = fitted.get(axis)!\n      const out = alignScales(\n        {\n          scale: scales.value,\n          extent: ownAxis.extent,\n          // Shares of a whole always run to the whole, so the own axis never widens past it.\n          domain:\n            hold || stack === 'expand'\n              ? [scales.value.domain[0], scales.value.domain[1]]\n              : y.domain,\n        },\n        {\n          extent: second.extent,\n          domain: optionsOf(axis).domain,\n          allowDecimals: allowDecimalsOn(axis),\n        },\n      )\n      if (!out) continue\n      scales.value = out.primary\n      scales[axis] = out.second\n    }\n  }\n  const value = scales.value\n  const baselines: CartesianModel['baselines'] = {\n    ...Object.fromEntries(\n      Object.entries(scales).map(([axis, scale]) => [\n        axis,\n        baselineOf(scale, axis === VALUE_AXIS ? y.base : undefined),\n      ]),\n    ),\n    value: baselineOf(value, y.base),\n  }\n\n  const xValues = x.kind === 'number' ? input.rows.map((row) => numberOf(row[x.key])) : []\n  const bars = series.filter((key) => markOf(key) === 'bar')\n  const times = joined?.stops.map((stop) => stop.time) ?? []\n  const xScale =\n    x.kind === 'time' && joined\n      ? timeScale(times, {\n          timeZone: joined.instants ? x.timeZone : 'UTC',\n          firstDay: x.firstDay,\n          // The bars stand on the times their series have rows at, so a line's own rows\n          // between them never make them thinner.\n          bands:\n            bars.length > 0\n              ? {\n                  gaps: x.gaps ?? {},\n                  times: times.filter((_, at) =>\n                    bars.some((key) => joined.rowOf(key, at) !== null),\n                  ),\n                }\n              : null,\n          window: x.window,\n        })\n      : xScaleOf(input, xValues, bars.length > 0)\n\n  return {\n    x: xScale,\n    count,\n    timeStops: joined?.stops ?? null,\n    timesOf: joined?.timesOf ?? null,\n    rowOf,\n    bandOf: (index) => {\n      if (xScale.kind === 'time') return xScale.bandOf(times[index] ?? 0)\n      return xScale.kind === 'linear' ? NO_BAND : xScale.bandAt(index)\n    },\n    y: scales,\n    baselines,\n    markOf,\n    axisOf,\n    totals: (key) => axisOf(key) === VALUE_AXIS && stacks(key),\n    valueAxisOf: (key) => {\n      const axis = axisOf(key)\n      const scale = scales[axis]\n      const baseline = baselines[axis]\n      // A key the config doesn't name is read against the chart's own axis.\n      return scale !== undefined && baseline !== undefined\n        ? { scale, baseline }\n        : { scale: scales.value, baseline: baselines.value }\n    },\n    stackOf,\n    spans,\n    reach: (index) => {\n      let far: number | null = null\n      for (const group of groups) {\n        const scale = scales[group.axis]\n        const onIt = group.series.filter((key) => shown.includes(key))\n        if (!scale || onIt.length === 0) continue\n        const reach = group.kind.reach(spans, onIt, index, scale)\n        if (reach !== null) far = far === null ? reach : Math.max(far, reach)\n      }\n      return far\n    },\n    point: (index) => {\n      const x = xValues[index]\n      if (xScale.kind !== 'linear' || x === undefined || x === null) return null\n      let top: { value: number; place: number } | null = null\n      for (const key of shown) {\n        const span = spans[key]?.[index]\n        const scale = scales[axisOf(key)]\n        if (!span || !scale) continue\n        const place = scale.place(span[1])\n        if (!top || place > top.place) top = { value: span[1], place }\n      }\n      return (\n        top && {\n          value: { x, y: top.value },\n          place: { x: xScale.place(x), y: top.place },\n        }\n      )\n    },\n  }\n}\n\n/**\n * The x scale: along categories, a band for each when any series is a bar,\n * declared rather than shown, so hiding the bars never moves the rest, or\n * else points from edge to edge; along numbers, a range fitted to them.\n */\nfunction xScaleOf(\n  input: CartesianInput,\n  values: readonly (number | null)[],\n  hasBars: boolean,\n): ChartScale {\n  const { x } = input\n  if (x.kind === 'category')\n    return hasBars ? bandScale(x.keys, x.gaps) : pointScale(x.keys)\n  if (x.kind === 'time') throw new Error('An x of times has a scale of its own.')\n  const numbers = values.filter((value) => value !== null)\n  const tickCount = x.tickCount ?? 5\n  return linearScale(\n    extentWith(\n      numberExtent(numbers),\n      input.references.filter((ref) => ref.axis === 'x').map((ref) => ref.value),\n    ),\n    {\n      domain: x.domain,\n      tickCount,\n      allowDecimals: x.allowDecimals ?? !numbers.every(Number.isInteger),\n    },\n  )\n}\n\n/** The band of a row on an x of numbers, which places it by its value instead. */\nconst NO_BAND: Band = { start: 0, size: 0 }\n\n/**\n * A row's key along an x of times: a calendar value's own text, so a day\n * keeps the key it has along categories, as charts synced with one share\n * it, and an instant's ISO form, whatever form it is given in.\n */\nfunction timeKey(value: unknown) {\n  const read = readTime(value)\n  return read?.instant ? isoInstant(read.time) : String(value)\n}\n\n/** A place along an x of times where one dataset or more has a row. */\ninterface JoinedStop {\n  /** The time's key (`timeKey`), as the first dataset with a row there writes it, the chart's own first. */\n  key: string\n  /** That dataset's value under the chart's `index`. */\n  value: unknown\n  /** In ms. */\n  time: number\n  /** The chart's own row here, or null. */\n  datum: ChartDatum | null\n  /** The row here of each series with rows of its own that has one. */\n  own: Readonly<Record<string, ChartDatum>>\n}\n\ninterface JoinedStops {\n  /** In time order, each time once. */\n  stops: readonly JoinedStop[]\n  /** The row `series` is drawn from at stop `index`: its own, or the chart's for a series with none; null where it has none. */\n  rowOf: (series: string, index: number) => ChartDatum | null\n  /** Whether the times are instants rather than calendar values. */\n  instants: boolean\n  /** A dataset's times in ms, in its rows' order: the chart's own rows for null, else a series' own. */\n  timesOf: (series: string | null) => readonly number[]\n}\n\n/**\n * Every dataset's times joined into the stops, in time order: the chart's\n * own `rows`, then each series' `own`, joined by their time in ms, so\n * `2026-01` and `2026-01-01` are one stop. Throws, naming the row, on one\n * with no time under `index`, or out of order, or repeated, and on calendar\n * values and instants together, which are read on two clocks.\n */\nfunction joinStops(\n  rows: readonly ChartDatum[],\n  own: Readonly<Record<string, readonly ChartDatum[]>>,\n  index: string,\n): JoinedStops {\n  const datasets = [\n    { series: null, rows },\n    ...Object.entries(own).map(([series, rows]) => ({ series, rows })),\n  ]\n  const byTime = new Map<\n    number,\n    Omit<JoinedStop, 'datum' | 'own'> & {\n      datum: ChartDatum | null\n      own: Record<string, ChartDatum>\n    }\n  >()\n  let instants: { instant: boolean; series: string | null } | null = null\n  const timesBy = new Map<string | null, readonly number[]>()\n  for (const { series, rows } of datasets) {\n    const read = datasetTimes(rows, index, series)\n    timesBy.set(series, read.times)\n    if (read.instants !== null) {\n      if (instants && instants.instant !== read.instants) {\n        const way = (instant: boolean) => (instant ? 'instants' : 'calendar values')\n        throw new Error(\n          `${datasetName(instants.series)} holds ${way(instants.instant)} under \\`${index}\\`, and ${datasetName(series)} holds ${way(read.instants)}: give them all one way.`,\n        )\n      }\n      instants ??= { instant: read.instants, series }\n    }\n    for (const [at, time] of read.times.entries()) {\n      const row = rows[at]!\n      let stop = byTime.get(time)\n      if (!stop) {\n        stop = { key: timeKey(row[index]), value: row[index], time, datum: null, own: {} }\n        byTime.set(time, stop)\n      }\n      if (series === null) stop.datum = row\n      else stop.own[series] = row\n    }\n  }\n  const stops: readonly JoinedStop[] = [...byTime.values()].toSorted(\n    (a, b) => a.time - b.time,\n  )\n  return {\n    stops,\n    rowOf: (series, at) => {\n      const stop = stops[at]\n      if (!stop) return null\n      return Object.hasOwn(own, series) ? (stop.own[series] ?? null) : stop.datum\n    },\n    instants: instants?.instant ?? false,\n    timesOf: (series) => timesBy.get(series) ?? [],\n  }\n}\n\n/**\n * The row of a series' that the tooltip and what is read out give at a\n * stop at `time`, as its place among `times`, the series' rows' times in\n * order: the one exactly there, or else its nearest within half the smaller\n * of `gaps`, its own rows' usual gap and the chart's rows' (`usualGap`), so\n * two streams stamped apart read as one moment while a trend of two points\n * over a hundred days shows at its two points alone. A gap that isn't known\n * (null) isn't used; with neither, only a row exactly there. The earlier\n * row on a tie; null past that.\n */\nfunction nearestRow(\n  times: readonly number[],\n  time: number,\n  gaps: { own: number | null; chart: number | null },\n): number | null {\n  // The first row at `time` or after it.\n  let low = 0\n  let high = times.length\n  while (low < high) {\n    const middle = (low + high) >> 1\n    if (times[middle]! < time) low = middle + 1\n    else high = middle\n  }\n  if (times[low] === time) return low\n  const known = [gaps.own, gaps.chart].filter((gap) => gap !== null)\n  if (known.length === 0) return null\n  const reach = Math.min(...known) / 2\n  const before = low - 1\n  const near = [before, low].filter(\n    (at) => at >= 0 && at < times.length && Math.abs(times[at]! - time) <= reach,\n  )\n  if (near.length === 0) return null\n  // The earlier on a tie, as `before` comes first.\n  return near.reduce((best, at) =>\n    Math.abs(times[at]! - time) < Math.abs(times[best]! - time) ? at : best,\n  )\n}\n\n/** How an error names a dataset: the chart's own rows, or a series' own. */\nfunction datasetName(series: string | null) {\n  return series === null ? \"The chart's `data`\" : `The series \\`${series}\\`'s \\`data\\``\n}\n\n/**\n * The time of each of `rows` under `key`, read once, and whether they are\n * instants rather than calendar values, or null with no rows. Throws,\n * naming the row of `series`' data or the chart's, on one with no time, on\n * calendar values and instants together, and on times out of order or\n * repeated, which a line couldn't run through in order.\n */\nfunction datasetTimes(\n  rows: readonly ChartDatum[],\n  key: string,\n  series: string | null,\n): { times: readonly number[]; instants: boolean | null } {\n  const times: number[] = []\n  let instants: boolean | null = null\n  const name = (at: number) =>\n    series === null ? `Row ${at}` : `Row ${at} of the series \\`${series}\\`'s \\`data\\``\n  for (const [at, row] of rows.entries()) {\n    const read = readTime(row[key])\n    if (!read) {\n      throw new Error(\n        `${name(at)} has no time under \\`${key}\\`: give a \\`yyyy-mm-dd\\` date, a \\`yyyy-mm\\` month, a \\`yyyy-mm-ddTHH:mm\\` time, an ISO instant, a \\`Date\\` or milliseconds.`,\n      )\n    }\n    if (instants !== null && instants !== read.instant) {\n      throw new Error(\n        `${name(at)}'s time under \\`${key}\\` is ${read.instant ? 'an instant' : 'a calendar value'}, and the rows before it are ${instants ? 'instants' : 'calendar values'}: give them all one way.`,\n      )\n    }\n    instants = read.instant\n    const before = times.at(-1)\n    if (before !== undefined && read.time <= before) {\n      throw new Error(\n        `${name(at)}'s time under \\`${key}\\` ${read.time === before ? 'repeats the one before it' : 'comes before the one before it'}: give the rows in time order, each time once.`,\n      )\n    }\n    times.push(read.time)\n  }\n  return { times, instants }\n}\n\nexport {\n  type CartesianInput,\n  type CartesianModel,\n  cartesianModel,\n  type CartesianX,\n  type ChartReference,\n  type JoinedStop,\n  type JoinedStops,\n  joinStops,\n  markLayer,\n  type MarkKind,\n  nearestRow,\n  type SeriesSpans,\n  timeKey,\n  VALUE_AXIS,\n  type ValueAxisOptions,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-frame.ts"
    }
  ],
  "type": "registry:lib"
}