{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "line-path",
  "title": "Line path",
  "description": "The geometry of a line through a series’ points: the path d3-shape draws, smooth, straight, in steps or as a bump chart’s S-curves, any point along it, and how one line moves into another, with a baseline under each point for a fill. Line chart, Area chart, Bump chart and Sparkline share it.",
  "dependencies": [
    "d3-shape"
  ],
  "devDependencies": [
    "@types/d3-shape"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/lib/line-path.ts",
      "content": "import {\n  curveBumpX,\n  curveLinear,\n  curveMonotoneX,\n  curveStep,\n  line as linePath,\n} from 'd3-shape'\n\n/*\n * The geometry of a line through a series' points: the path d3-shape draws,\n * any point along it, and how one line moves into another. Points that stay\n * glide to their new place, points that arrive grow out of the old line and\n * points that leave fold into the new one, so a new range reads as the same\n * line stretching rather than a new one. A point may carry a baseline too,\n * which moves with it, for a fill under the line. Every function here is\n * pure: the Line chart, the Area chart, the Bump chart and the Sparkline\n * only draw what it returns.\n */\n\n/** How a line runs between its points: a smooth curve that never overshoots them, straight, or in steps. */\ntype LineCurve = 'monotone' | 'linear' | 'step'\n\n/**\n * Every way a line can run between its points: a line's own `LineCurve`, or\n * `bump`, an S that leaves each point level and meets the next level, as a\n * bump chart draws a rank changing from one period to the next.\n */\ntype PathCurve = LineCurve | 'bump'\n\n/** A point of a line: where it sits, as fractions of the plot from its reading start and its top. */\ninterface LinePoint {\n  /** The category's key, or null for a point that only pads a line while it changes. */\n  key: string | null\n  x: number\n  y: number\n  /** Where a fill under the point ends, as a fraction of the plot from its top; none for a bare line. */\n  base?: number\n  /** Whether the line passes through it; a missing value leaves a gap. */\n  defined: boolean\n}\n\n/** A point in step between two others, `progress` of the way, which may pass 1 when the feel overshoots. */\ninterface AlignedPoint {\n  key: string | null\n  from: LinePoint\n  to: LinePoint\n}\n\n/** Where to look up a point between two of a line's: its place in the line's order, fractional between points. */\ntype LineSampler = (place: number) => LinePoint\n\n/**\n * The slope d3's monotone curve gives each point, so the line never\n * overshoots a value: the Fritsch-Carlson slopes inside each run of points\n * with values, and each run's ends sloped toward their neighbour. `of`\n * reads the height to slope, the point's `y` unless told otherwise.\n */\nfunction monotoneSlopes(\n  points: readonly LinePoint[],\n  of: (point: LinePoint) => number = (point) => point.y,\n): number[] {\n  const slopes = points.map(() => 0)\n  const sign = (value: number) => (value < 0 ? -1 : 1)\n  let start = 0\n  while (start < points.length) {\n    while (start < points.length && !points[start]!.defined) start += 1\n    let end = start\n    while (end + 1 < points.length && points[end + 1]!.defined) end += 1\n    const run = points.slice(start, end + 1)\n    if (run.length >= 3) {\n      for (let at = 1; at < run.length - 1; at += 1) {\n        const [p0, p1, p2] = [run[at - 1]!, run[at]!, run[at + 1]!]\n        const h0 = p1.x - p0.x\n        const h1 = p2.x - p1.x\n        const s0 = h0 === 0 ? 0 : (of(p1) - of(p0)) / h0\n        const s1 = h1 === 0 ? 0 : (of(p2) - of(p1)) / h1\n        const mean = h0 + h1 === 0 ? 0 : (s0 * h1 + s1 * h0) / (h0 + h1)\n        slopes[start + at] =\n          (sign(s0) + sign(s1)) *\n            Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(mean)) || 0\n      }\n      const end2 = (from: LinePoint, to: LinePoint, inner: number) => {\n        const h = to.x - from.x\n        return h === 0 ? inner : ((3 * (of(to) - of(from))) / h - inner) / 2\n      }\n      slopes[start] = end2(run[0]!, run[1]!, slopes[start + 1]!)\n      slopes[end] = end2(run.at(-2)!, run.at(-1)!, slopes[end - 1]!)\n    } else if (run.length === 2) {\n      const h = run[1]!.x - run[0]!.x\n      const slope = h === 0 ? 0 : (of(run[1]!) - of(run[0]!)) / h\n      slopes[start] = slope\n      slopes[end] = slope\n    }\n    start = end + 1\n  }\n  return slopes\n}\n\n/**\n * The height `share` of the way from `low` to `high` as `curve` draws it:\n * a straight line, a step halfway, or the cubic d3's monotone curve draws,\n * whose x runs evenly, with each end's slope.\n */\nfunction heightBetween(\n  low: number,\n  high: number,\n  slopes: readonly [number, number],\n  width: number,\n  share: number,\n  curve: PathCurve,\n) {\n  if (curve === 'step') return share < 0.5 ? low : high\n  if (curve === 'linear') return low + (high - low) * share\n  if (curve === 'bump') return bumpHeight(low, high, share)\n  const third = width / 3\n  const b = low + third * slopes[0]\n  const c = high - third * slopes[1]\n  const u = 1 - share\n  return (\n    u * u * u * low +\n    3 * u * u * share * b +\n    3 * u * share * share * c +\n    share ** 3 * high\n  )\n}\n\n/**\n * The height `share` of the way across from `low` to `high` on the S d3's\n * bump curve draws: a cubic whose two middle points sit halfway across, at\n * the heights of its ends. Its x doesn't run evenly, so the cubic's own\n * place for `share` is found first, by Newton's method: x grows at a rate\n * of at least 0.75 everywhere, so a few steps land on it.\n */\nfunction bumpHeight(low: number, high: number, share: number) {\n  // Across the cubic, x is 1.5t - 1.5t² + t³ for its place t.\n  let t = Math.min(1, Math.max(0, share))\n  for (let step = 0; step < 6; step += 1) {\n    const x = 1.5 * t - 1.5 * t * t + t * t * t\n    t -= (x - share) / (1.5 - 3 * t + 3 * t * t)\n    t = Math.min(1, Math.max(0, t))\n  }\n  const u = 1 - t\n  return low * u * u * (1 + 2 * t) + high * t * t * (3 - 2 * t)\n}\n\n/**\n * Looks up any point along `points` as `curve` draws them, by its place in\n * their order: 2.5 is halfway along the curve between the third and the\n * fourth point. A point sampled on the curve stays on it, so a line drawn\n * through samples looks like the line through `points`. Its baseline, if\n * the points have one, is sampled on its own curve the same way.\n */\nfunction sampleLine(points: readonly LinePoint[], curve: PathCurve): LineSampler {\n  const slopes = curve === 'monotone' ? monotoneSlopes(points) : []\n  const based = points.some((point) => point.base !== undefined)\n  const baseOf = (point: LinePoint) => point.base ?? 1\n  const baseSlopes = based && curve === 'monotone' ? monotoneSlopes(points, baseOf) : []\n  return (place) => {\n    const last = points.length - 1\n    if (last <= 0) return { ...(points[0] ?? { x: 0, y: 0, defined: false }), key: null }\n    const at = Math.min(last, Math.max(0, place))\n    const below = Math.min(last - 1, Math.floor(at))\n    const low = points[below]!\n    const high = points[below + 1]!\n    const share = at - below\n    const x = low.x + (high.x - low.x) * share\n    const defined = share < 0.5 ? low.defined : high.defined\n    const joined = low.defined && high.defined\n    const along = (from: number, to: number, own: readonly number[]) =>\n      joined\n        ? heightBetween(\n            from,\n            to,\n            [own[below] ?? 0, own[below + 1] ?? 0],\n            high.x - low.x,\n            share,\n            curve,\n          )\n        : from + (to - from) * share\n    const point: LinePoint = {\n      key: null,\n      x,\n      y: along(low.y, high.y, slopes),\n      defined,\n    }\n    if (based) point.base = along(baseOf(low), baseOf(high), baseSlopes)\n    return point\n  }\n}\n\n/**\n * Pairs a stretch of the old line, from place `from[0]` to `from[1]` in its\n * order, with a stretch of the new one: every point of either gets a\n * partner at the same share of the way along the other, on its curve, so\n * arriving points grow out of the old line and leaving ones fold into the\n * new one. A stretch of one point stays on it, which sits at its `single`\n * end: 1 before the first point the lines share, 0 after the last.\n */\nfunction pairStretch(\n  from: readonly [number, number],\n  to: readonly [number, number],\n  sampleFrom: LineSampler,\n  sampleTo: LineSampler,\n  toPoints: readonly LinePoint[],\n  single: 0 | 1 = 0,\n): AlignedPoint[] {\n  const shares = ([start, end]: readonly [number, number]) =>\n    Array.from({ length: end - start + 1 }, (_, at) =>\n      end === start ? single : at / (end - start),\n    )\n  const toShares = shares(to)\n  const all = [...new Set([...toShares, ...shares(from)])].toSorted((a, b) => a - b)\n  return all.map((share) => {\n    const own = toShares.findIndex((s) => Math.abs(s - share) < 1e-9)\n    const target =\n      own === -1 ? sampleTo(to[0] + share * (to[1] - to[0])) : toPoints[to[0] + own]!\n    return {\n      key: own === -1 ? null : target.key,\n      from: sampleFrom(from[0] + share * (from[1] - from[0])),\n      to: target,\n    }\n  })\n}\n\n/**\n * The points a line moves through from `from` to `to`, both drawn with\n * `curve`. Points in both, matched by key, glide straight to their new\n * place; between two of them, and before the first and after the last, what\n * arrives grows out of the old line and what leaves folds into the new one.\n * With nothing in common, or the order changed, the whole line pairs by\n * order.\n */\nfunction alignLines(\n  from: readonly LinePoint[],\n  to: readonly LinePoint[],\n  curve: PathCurve,\n): AlignedPoint[] {\n  if (to.length === 0) return []\n  if (from.length === 0)\n    return to.map((point) => ({ key: point.key, from: point, to: point }))\n  const sampleFrom = sampleLine(from, curve)\n  const sampleTo = sampleLine(to, curve)\n  const pair = (\n    fromSpan: readonly [number, number],\n    toSpan: readonly [number, number],\n    single: 0 | 1 = 0,\n  ) => pairStretch(fromSpan, toSpan, sampleFrom, sampleTo, to, single)\n  const fromAt = new Map<string, number>()\n  from.forEach((point, at) => {\n    if (point.key !== null) fromAt.set(point.key, at)\n  })\n  const anchors: [number, number][] = []\n  to.forEach((point, at) => {\n    const was = point.key === null ? undefined : fromAt.get(point.key)\n    if (was !== undefined) anchors.push([was, at])\n  })\n  const ordered = anchors.every((pair, at) => at === 0 || pair[0] > anchors[at - 1]![0])\n  if (anchors.length === 0 || !ordered)\n    return pair([0, from.length - 1], [0, to.length - 1])\n  const [firstFrom, firstTo] = anchors[0]!\n  const out = pair([0, firstFrom], [0, firstTo], 1)\n  for (let at = 1; at < anchors.length; at += 1) {\n    const [fromStart, toStart] = anchors[at - 1]!\n    const [fromEnd, toEnd] = anchors[at]!\n    // Each stretch starts on the anchor the last one ended on, which is there already.\n    out.push(...pair([fromStart, fromEnd], [toStart, toEnd]).slice(1))\n  }\n  const [lastFrom, lastTo] = anchors.at(-1)!\n  out.push(...pair([lastFrom, from.length - 1], [lastTo, to.length - 1]).slice(1))\n  return out\n}\n\n/**\n * A live line's move, its new points rising out of the hold: a point that\n * arrives past the newest one `from` drew starts at its own place along,\n * at that point's value, where the hold carried it, so the line's end\n * only moves up or down as each row lands.\n */\nfunction holdArrivals(\n  aligned: readonly AlignedPoint[],\n  from: readonly LinePoint[],\n): AlignedPoint[] {\n  const held = from.findLast((point) => point.defined)\n  if (!held) return [...aligned]\n  const drawn = new Set(from.map((point) => point.key))\n  return aligned.map((point) => {\n    if (point.to.x <= held.x || (point.key !== null && drawn.has(point.key))) return point\n    const start: LinePoint = { ...point.to, y: held.y }\n    if (point.to.base !== undefined) start.base = held.base ?? point.to.base\n    return { ...point, from: start }\n  })\n}\n\n/** The line `progress` of the way through `aligned`, its baselines with it. */\nfunction pointsAt(aligned: readonly AlignedPoint[], progress: number): LinePoint[] {\n  return aligned.map(({ key, from, to }) => {\n    const point: LinePoint = {\n      key,\n      x: from.x + (to.x - from.x) * progress,\n      y: from.y + (to.y - from.y) * progress,\n      defined: progress < 0.5 ? from.defined : to.defined,\n    }\n    if (from.base !== undefined || to.base !== undefined) {\n      const was = from.base ?? 1\n      point.base = was + ((to.base ?? 1) - was) * progress\n    }\n    return point\n  })\n}\n\nconst curves = {\n  monotone: curveMonotoneX,\n  linear: curveLinear,\n  step: curveStep,\n  bump: curveBumpX,\n} as const\n\n/** A line through `points` in px for a plot `width` by `height`, with a gap at each missing value. */\nfunction pathThrough(\n  points: readonly LinePoint[],\n  curve: PathCurve,\n  width: number,\n  height: number,\n): string {\n  return (\n    linePath<LinePoint>()\n      .defined((point) => point.defined)\n      .x((point) => point.x * width)\n      .y((point) => point.y * height)\n      .curve(curves[curve])(points) ?? ''\n  )\n}\n\n/** Straight lines across each gap a missing value leaves, from the point before it to the point after. */\nfunction bridgesThrough(points: readonly LinePoint[], width: number, height: number) {\n  const out: string[] = []\n  let before: LinePoint | null = null\n  let gap = false\n  for (const point of points) {\n    if (!point.defined) {\n      gap = before !== null\n      continue\n    }\n    if (gap && before) {\n      out.push(\n        `M${before.x * width},${before.y * height}L${point.x * width},${point.y * height}`,\n      )\n    }\n    before = point\n    gap = false\n  }\n  return out.join('')\n}\n\n/**\n * A dot for each point with no neighbour to join, such as a value between\n * two missing ones, which a line alone would leave unseen: a zero-length\n * stroke whose round caps make the dot.\n */\nfunction lonePointsThrough(points: readonly LinePoint[], width: number, height: number) {\n  return points\n    .filter(\n      (point, at) =>\n        point.defined && !points[at - 1]?.defined && !points[at + 1]?.defined,\n    )\n    .map((point) => `M${point.x * width},${point.y * height}h0`)\n    .join('')\n}\n\n/**\n * How high the line through `points` is where it crosses `x`, both as\n * fractions of the plot, as `curve` draws it; null where it isn't drawn.\n * Across a gap, the point on the nearer side counts, if it has a value, so\n * a line's last point can be found past it as its dot can.\n */\nfunction heightAt(\n  points: readonly LinePoint[],\n  curve: PathCurve,\n  x: number,\n): number | null {\n  const after = points.findIndex((point) => point.x >= x)\n  if (after === -1 || after === 0) {\n    const end = after === 0 ? points[0] : points.at(-1)\n    return end?.defined ? end.y : null\n  }\n  const low = points[after - 1]!\n  const high = points[after]!\n  const share = high.x === low.x ? 1 : (x - low.x) / (high.x - low.x)\n  if (low.defined && high.defined) return sampleLine(points, curve)(after - 1 + share).y\n  const nearer = share < 0.5 ? low : high\n  return nearer.defined ? nearer.y : null\n}\n\nexport {\n  type AlignedPoint,\n  alignLines,\n  bridgesThrough,\n  curves,\n  heightAt,\n  holdArrivals,\n  type LineCurve,\n  type LinePoint,\n  type LineSampler,\n  lonePointsThrough,\n  monotoneSlopes,\n  pathThrough,\n  type PathCurve,\n  pointsAt,\n  sampleLine,\n}\n",
      "type": "registry:lib",
      "target": "@lib/line-path.ts"
    }
  ],
  "type": "registry:lib"
}