{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "diff-math",
  "title": "Diff maths",
  "description": "The changes between a before and an after, by line for code and by word for prose, each with an id that holds while after still arrives, and the text once each change is accepted or rejected.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/syntax.json"
  ],
  "files": [
    {
      "path": "registry/lib/diff-math.ts",
      "content": "import { codeLines } from '@/registry/lib/syntax'\n\n/*\n * The changes between a before and an after, by line for code and by word\n * for prose, on one diff of tokens: Myers' O(ND) with the common ends\n * trimmed, and for lines a patience pass first, so code lines up on the\n * lines that appear once on each side rather than on its braces. A change\n * is a run of removed and added tokens between unchanged ones, named by\n * where it starts in before, so its id holds while after still grows.\n *\n * While after is not complete, before past what after has reached stays as\n * it is (`pending`): the last change keeps only as much of before as after\n * has put something in place of, so a rewrite stopped half-way never marks\n * the rest as removed.\n */\n\n/** What a run of tokens did between before and after. */\ntype DiffOp = 'same' | 'added' | 'removed'\n\n/** Text that one side kept, gained or lost. */\ninterface DiffSpan {\n  op: DiffOp\n  text: string\n}\n\n/** What a person decided about one change. */\ntype Resolution = 'accepted' | 'rejected'\n\n/** Decisions by change id. */\ntype Resolved = Readonly<Record<string, Resolution>>\n\n/** A run of `length` tokens from before's `a` and after's `b`; one side's start is where the run sits in it. */\ninterface Run {\n  op: DiffOp\n  a: number\n  b: number\n  length: number\n}\n\n/** Past this many edits, the rest is one change: a removal and an addition. */\nconst MAX_EDITS = 4000\n\n/** Below this share of a line kept, a pair of lines reads as a whole new line, with no word marks. */\nconst PAIR_SIMILARITY = 0.5\n\n/** Pairs of lines tried in one change, past which lines pair in order. */\nconst MAX_PAIRINGS = 2500\n\nfunction pushRun(runs: Run[], op: DiffOp, a: number, b: number, length: number) {\n  if (length <= 0) return\n  const last = runs.at(-1)\n  const follows =\n    last?.op === op &&\n    (op === 'added' || last.a + last.length === a) &&\n    (op === 'removed' || last.b + last.length === b)\n  if (last && follows) last.length += length\n  else runs.push({ op, a, b, length })\n}\n\n/** Myers' shortest edit script between `a[aLo, aHi)` and `b[bLo, bHi)`, whose ends already differ. */\nfunction myers(\n  a: readonly string[],\n  b: readonly string[],\n  aLo: number,\n  aHi: number,\n  bLo: number,\n  bHi: number,\n  runs: Run[],\n) {\n  const n = aHi - aLo\n  const m = bHi - bLo\n  const max = Math.min(n + m, MAX_EDITS)\n  const offset = max + 1\n  const v = new Int32Array(2 * max + 3)\n  // Each step's furthest x on diagonals -d..d, kept to walk back along.\n  const trace: Int32Array[] = []\n  let found = -1\n  for (let d = 0; d <= max && found < 0; d++) {\n    for (let k = -d; k <= d; k += 2) {\n      let x =\n        k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1])\n          ? v[offset + k + 1]\n          : v[offset + k - 1] + 1\n      let y = x - k\n      while (x < n && y < m && a[aLo + x] === b[bLo + y]) {\n        x++\n        y++\n      }\n      v[offset + k] = x\n      if (x >= n && y >= m) found = d\n    }\n    trace.push(v.slice(offset - d, offset + d + 1))\n  }\n  if (found < 0) {\n    pushRun(runs, 'removed', aLo, bLo, n)\n    pushRun(runs, 'added', aHi, bLo, m)\n    return\n  }\n\n  const steps: Run[] = []\n  let x = n\n  let y = m\n  for (let d = found; d > 0; d--) {\n    const k = x - y\n    const previous = trace[d - 1]\n    const at = (diagonal: number) => previous[diagonal + d - 1]\n    const down = k === -d || (k !== d && at(k - 1) < at(k + 1))\n    const prevK = down ? k + 1 : k - 1\n    const prevX = at(prevK)\n    const prevY = prevX - prevK\n    const snakeX = down ? prevX : prevX + 1\n    const snakeY = down ? prevY + 1 : prevY\n    steps.push({\n      op: 'same',\n      a: aLo + snakeX,\n      b: bLo + snakeY,\n      length: x - snakeX,\n    })\n    steps.push(\n      down\n        ? { op: 'added', a: aLo + prevX, b: bLo + prevY, length: 1 }\n        : { op: 'removed', a: aLo + prevX, b: bLo + prevY, length: 1 },\n    )\n    x = prevX\n    y = prevY\n  }\n  steps.push({ op: 'same', a: aLo, b: bLo, length: x })\n  for (const step of steps.reverse()) pushRun(runs, step.op, step.a, step.b, step.length)\n}\n\n/** The tokens of `range` that appear exactly once there, by token. */\nfunction uniqueIn(\n  tokens: readonly string[],\n  lo: number,\n  hi: number,\n): Map<string, number> {\n  const seen = new Map<string, number>()\n  const twice = new Set<string>()\n  for (let index = lo; index < hi; index++) {\n    const token = tokens[index]\n    if (seen.has(token)) twice.add(token)\n    else seen.set(token, index)\n  }\n  for (const token of twice) seen.delete(token)\n  return seen\n}\n\n/** The longest run of anchors in order on both sides: patience sorting on their places in b. */\nfunction longestInOrder(pairs: readonly (readonly [number, number])[]) {\n  const tails: number[] = []\n  const back = new Int32Array(pairs.length).fill(-1)\n  for (let index = 0; index < pairs.length; index++) {\n    const value = pairs[index][1]\n    let lo = 0\n    let hi = tails.length\n    while (lo < hi) {\n      const mid = (lo + hi) >> 1\n      if (pairs[tails[mid]][1] < value) lo = mid + 1\n      else hi = mid\n    }\n    if (lo > 0) back[index] = tails[lo - 1]\n    tails[lo] = index\n  }\n  const chain: (readonly [number, number])[] = []\n  for (let index = tails.at(-1) ?? -1; index >= 0; index = back[index])\n    chain.push(pairs[index])\n  return chain.reverse()\n}\n\nfunction diffRange(\n  a: readonly string[],\n  b: readonly string[],\n  aLo: number,\n  aHi: number,\n  bLo: number,\n  bHi: number,\n  anchors: boolean,\n  runs: Run[],\n) {\n  let start = 0\n  while (aLo + start < aHi && bLo + start < bHi && a[aLo + start] === b[bLo + start])\n    start++\n  pushRun(runs, 'same', aLo, bLo, start)\n  aLo += start\n  bLo += start\n  let end = 0\n  while (aHi - end > aLo && bHi - end > bLo && a[aHi - end - 1] === b[bHi - end - 1])\n    end++\n  aHi -= end\n  bHi -= end\n\n  if (aLo === aHi) pushRun(runs, 'added', aLo, bLo, bHi - bLo)\n  else if (bLo === bHi) pushRun(runs, 'removed', aLo, bLo, aHi - aLo)\n  else {\n    const chain = anchors ? anchorsIn(a, b, aLo, aHi, bLo, bHi) : []\n    if (chain.length === 0 && !shareAny(a, b, aLo, aHi, bLo, bHi)) {\n      pushRun(runs, 'removed', aLo, bLo, aHi - aLo)\n      pushRun(runs, 'added', aHi, bLo, bHi - bLo)\n    } else if (chain.length === 0) myers(a, b, aLo, aHi, bLo, bHi, runs)\n    else {\n      let fromA = aLo\n      let fromB = bLo\n      for (const [atA, atB] of chain) {\n        diffRange(a, b, fromA, atA, fromB, atB, true, runs)\n        pushRun(runs, 'same', atA, atB, 1)\n        fromA = atA + 1\n        fromB = atB + 1\n      }\n      diffRange(a, b, fromA, aHi, fromB, bHi, true, runs)\n    }\n  }\n  pushRun(runs, 'same', aHi, bHi, end)\n}\n\n/** Whether the two ranges have any token in common, so a search for what they keep can find something. */\nfunction shareAny(\n  a: readonly string[],\n  b: readonly string[],\n  aLo: number,\n  aHi: number,\n  bLo: number,\n  bHi: number,\n) {\n  const inA = new Set(a.slice(aLo, aHi))\n  for (let index = bLo; index < bHi; index++) if (inA.has(b[index])) return true\n  return false\n}\n\n/** Tokens unique on both sides of the range, matched, in the longest order both agree on. */\nfunction anchorsIn(\n  a: readonly string[],\n  b: readonly string[],\n  aLo: number,\n  aHi: number,\n  bLo: number,\n  bHi: number,\n) {\n  const inB = uniqueIn(b, bLo, bHi)\n  const pairs: [number, number][] = []\n  for (const [token, atA] of uniqueIn(a, aLo, aHi)) {\n    const atB = inB.get(token)\n    if (atB !== undefined) pairs.push([atA, atB])\n  }\n  pairs.sort((one, other) => one[0] - other[0])\n  return longestInOrder(pairs)\n}\n\n/**\n * The runs that turn tokens `a` into `b`. `anchors` lines them up on tokens\n * found once on each side first (patience), which suits lines of code.\n */\nfunction diffTokens(\n  a: readonly string[],\n  b: readonly string[],\n  { anchors = false }: { anchors?: boolean } = {},\n): Run[] {\n  const runs: Run[] = []\n  diffRange(a, b, 0, a.length, 0, b.length, anchors, runs)\n  return runs\n}\n\n/** A change's runs as one: the removed and added tokens between two unchanged ones. */\ninterface Hunk {\n  /** Where it starts in before and in after, by token. */\n  a: number\n  b: number\n  removed: number\n  added: number\n}\n\n/** Runs as unchanged stretches and changes, in order. */\ntype Piece =\n  | { kind: 'same'; a: number; b: number; length: number }\n  | ({ kind: 'change' } & Hunk)\n\nfunction piecesOf(runs: readonly Run[]): Piece[] {\n  const pieces: Piece[] = []\n  for (const run of runs) {\n    if (run.op === 'same') {\n      pieces.push({ kind: 'same', a: run.a, b: run.b, length: run.length })\n      continue\n    }\n    let last = pieces.at(-1)\n    if (last?.kind !== 'change') {\n      last = { kind: 'change', a: run.a, b: run.b, removed: 0, added: 0 }\n      pieces.push(last)\n    }\n    if (run.op === 'removed') last.removed += run.length\n    else last.added += run.length\n  }\n  return pieces\n}\n\n/**\n * While after is still arriving, the last change, when nothing after it is\n * unchanged, keeps only as much of before as after has replaced; the rest of\n * before is pending. A short match where after ends, such as one word or a\n * closing brace, may be the start of a longer rewrite, so it isn't taken as\n * kept until more arrives: `trusted` says which are. Returns how many of\n * before's tokens are pending, from its end.\n */\nfunction holdTail(\n  pieces: Piece[],\n  complete: boolean,\n  trusted: (piece: Piece & { kind: 'same' }) => boolean,\n): number {\n  if (complete) return 0\n  let last = pieces.at(-1)\n  const match = pieces.at(-2)\n  const earlier = pieces.at(-3)\n  if (\n    last?.kind === 'change' &&\n    last.added === 0 &&\n    match?.kind === 'same' &&\n    earlier?.kind === 'change' &&\n    !trusted(match)\n  ) {\n    earlier.removed += match.length + last.removed\n    earlier.added += match.length\n    pieces.length -= 2\n    last = earlier\n  }\n  if (last?.kind !== 'change') return 0\n  const kept = Math.min(last.removed, last.added)\n  const pending = last.removed - kept\n  if (last.added === 0) pieces.pop()\n  else last.removed = kept\n  return pending\n}\n\n/**\n * The changes after may still rewrite while it arrives: from its end back,\n * each change up to the first kept stretch `trusted` takes as kept, since a\n * shorter one can still turn into part of a change, or join two. Empty\n * once after is complete.\n */\nfunction growingOf(\n  pieces: readonly Piece[],\n  complete: boolean,\n  trusted: (piece: Piece & { kind: 'same' }) => boolean,\n): Piece[] {\n  if (complete) return []\n  const growing: Piece[] = []\n  for (let index = pieces.length - 1; index >= 0; index--) {\n    const piece = pieces[index]\n    if (piece.kind === 'same' && trusted(piece)) break\n    if (piece.kind === 'change') growing.push(piece)\n  }\n  return growing\n}\n\n/** Whether text holds a letter or a digit, as a word or a line of code does and white space or a brace doesn't. */\nconst meaningful = (text: string) => /[\\p{L}\\p{N}]/u.test(text)\n\n/** One line of a code diff: its number on its own side, from 1, and, when paired with its partner, the words it kept and changed. */\ninterface DiffLine {\n  number: number\n  text: string\n  /** Words this side kept (`same`) and lost or gained; absent when the whole line is the change. */\n  words?: DiffSpan[]\n}\n\n/** A run of changed lines: before's removed ones, then after's added ones. */\ninterface CodeChange {\n  /** From the line before starts it on, so it holds while after grows. */\n  id: string\n  /** The line it starts on in before, from 1; for lines only added, the line they go before. */\n  beforeLine: number\n  /** The line it starts on in after, from 1. */\n  afterLine: number\n  removed: DiffLine[]\n  added: DiffLine[]\n}\n\ntype CodeDiffRow =\n  | { kind: 'same'; before: number; after: number; text: string }\n  | { kind: 'change'; change: CodeChange }\n  /** A line of before that after hasn't reached yet. */\n  | { kind: 'pending'; before: number; text: string }\n\ninterface CodeDiff {\n  rows: CodeDiffRow[]\n  changes: CodeChange[]\n  /** The changes after may still rewrite while it arrives, which can't be decided yet. */\n  growing: string[]\n  /** How before ends its lines, `\\r\\n` or `\\n`, and whether each side ends with one, for `resolveCode`. */\n  eol: string\n  ends: { before: boolean; after: boolean }\n}\n\nlet wordSegmenter: Intl.Segmenter | null = null\n\n/**\n * `text` as tokens: each word, each run of white space and each other mark\n * on its own, from `Intl.Segmenter`, so Chinese and Japanese split by word.\n */\nfunction wordsOf(text: string): string[] {\n  wordSegmenter ??= new Intl.Segmenter(undefined, { granularity: 'word' })\n  const tokens: string[] = []\n  for (const { segment } of wordSegmenter.segment(text)) tokens.push(segment)\n  return tokens\n}\n\n/** The words of a pair of lines, each side's own, and how much of them both kept, from 0 to 1. */\nfunction pairWords(before: string, after: string) {\n  const a = wordsOf(before)\n  const b = wordsOf(after)\n  const removed: DiffSpan[] = []\n  const added: DiffSpan[] = []\n  let kept = 0\n  const push = (spans: DiffSpan[], op: DiffOp, text: string) => {\n    const last = spans.at(-1)\n    if (last?.op === op) last.text += text\n    else spans.push({ op, text })\n  }\n  for (const run of diffTokens(a, b)) {\n    if (run.op === 'same') {\n      const text = a.slice(run.a, run.a + run.length).join('')\n      // White space alone doesn't make two lines alike.\n      kept += text.trim().length\n      push(removed, 'same', text)\n      push(added, 'same', text)\n    } else if (run.op === 'removed') {\n      push(removed, 'removed', a.slice(run.a, run.a + run.length).join(''))\n    } else push(added, 'added', b.slice(run.b, run.b + run.length).join(''))\n  }\n  const size = Math.max(before.trim().length, after.trim().length)\n  return { removed, added, similarity: size === 0 ? 1 : kept / size }\n}\n\n/**\n * A change's lines, with each removed line paired, in order, to the first\n * added line still free that keeps most of it, and the words of each pair\n * marked. A change too large to try every pair pairs its lines by place.\n */\nfunction pairLines(removed: DiffLine[], added: DiffLine[]) {\n  const mark = (line: DiffLine, partner: DiffLine) => {\n    const pair = pairWords(line.text, partner.text)\n    if (pair.similarity < PAIR_SIMILARITY) return false\n    line.words = pair.removed\n    partner.words = pair.added\n    return true\n  }\n  if (removed.length * added.length > MAX_PAIRINGS) {\n    for (let index = 0; index < Math.min(removed.length, added.length); index++) {\n      mark(removed[index], added[index])\n    }\n    return\n  }\n  let from = 0\n  for (const line of removed) {\n    for (let index = from; index < added.length; index++) {\n      if (!mark(line, added[index])) continue\n      from = index + 1\n      break\n    }\n    if (from >= added.length) return\n  }\n}\n\n/** The changes between two texts by line, each pair of changed lines marked by word. */\nfunction diffCode(\n  before: string,\n  after: string,\n  { complete = true }: { complete?: boolean } = {},\n): CodeDiff {\n  const a = before === '' ? [] : codeLines(before)\n  const b = after === '' ? [] : codeLines(after)\n  const pieces = piecesOf(diffTokens(a, b, { anchors: true }))\n  // A kept line with a word in it is taken as kept; a brace or a blank line may be the start of a rewrite.\n  const trusted = (piece: Piece & { kind: 'same' }) =>\n    a.slice(piece.a, piece.a + piece.length).some(meaningful)\n  const pending = holdTail(pieces, complete, trusted)\n  const growing = new Set(growingOf(pieces, complete, trusted))\n  const rows: CodeDiffRow[] = []\n  const changes: CodeChange[] = []\n  const growingIds: string[] = []\n  for (const piece of pieces) {\n    if (piece.kind === 'same') {\n      for (let index = 0; index < piece.length; index++) {\n        rows.push({\n          kind: 'same',\n          before: piece.a + index + 1,\n          after: piece.b + index + 1,\n          text: a[piece.a + index],\n        })\n      }\n      continue\n    }\n    const change: CodeChange = {\n      id: `line-${piece.a + 1}`,\n      beforeLine: piece.a + 1,\n      afterLine: piece.b + 1,\n      removed: a\n        .slice(piece.a, piece.a + piece.removed)\n        .map((text, index) => ({ number: piece.a + index + 1, text })),\n      added: b\n        .slice(piece.b, piece.b + piece.added)\n        .map((text, index) => ({ number: piece.b + index + 1, text })),\n    }\n    pairLines(change.removed, change.added)\n    if (growing.has(piece)) growingIds.push(change.id)\n    changes.push(change)\n    rows.push({ kind: 'change', change })\n  }\n  for (let index = a.length - pending; index < a.length; index++) {\n    rows.push({ kind: 'pending', before: index + 1, text: a[index] })\n  }\n  const eol = /\\r\\n/.test(before || after) ? '\\r\\n' : '\\n'\n  const ends = { before: /\\n$/.test(before), after: /\\n$/.test(after) }\n  return { rows, changes, growing: growingIds, eol, ends }\n}\n\n/** A run of changed words in prose: what before had there, and what after puts in its place. */\ninterface TextChange {\n  /** From the character before starts it at, so it holds while after grows. */\n  id: string\n  removed: string\n  added: string\n}\n\ntype TextDiffPart =\n  | { kind: 'same'; text: string }\n  | { kind: 'change'; change: TextChange }\n  /** Before that after hasn't reached yet. */\n  | { kind: 'pending'; text: string }\n\ninterface TextDiff {\n  parts: TextDiffPart[]\n  changes: TextChange[]\n  /** The changes after may still rewrite while it arrives, which can't be decided yet. */\n  growing: string[]\n}\n\n/**\n * The changes between two texts by word. Two changes with only white space\n * between them are one, so \"the quick\" to \"a slow\" is one change, not two.\n */\nfunction diffText(\n  before: string,\n  after: string,\n  { complete = true }: { complete?: boolean } = {},\n): TextDiff {\n  const a = wordsOf(before)\n  const b = wordsOf(after)\n  const pieces = piecesOf(diffTokens(a, b))\n  // White space kept between two changes joins them, and so does one word\n  // next to a change that only adds or only removes: \"getting in touch\" to\n  // \"writing in\" reads as one rewritten phrase, not a word at a time.\n  const onlyOneSide = (piece: Piece & { kind: 'change' }) =>\n    piece.removed === 0 || piece.added === 0\n  for (let index = pieces.length - 2; index > 0; index--) {\n    const piece = pieces[index]\n    const previous = pieces[index - 1]\n    const next = pieces[index + 1]\n    if (piece.kind !== 'same' || previous?.kind !== 'change' || next?.kind !== 'change')\n      continue\n    const words = a.slice(piece.a, piece.a + piece.length).filter(meaningful).length\n    if (words > 1 || (words === 1 && !onlyOneSide(previous) && !onlyOneSide(next)))\n      continue\n    previous.removed += piece.length + next.removed\n    previous.added += piece.length + next.added\n    pieces.splice(index, 2)\n  }\n  // Two words or more where after ends are taken as kept.\n  const trusted = (piece: Piece & { kind: 'same' }) =>\n    a.slice(piece.a, piece.a + piece.length).filter(meaningful).length >= 2\n  const pending = holdTail(pieces, complete, trusted)\n  const growing = new Set(growingOf(pieces, complete, trusted))\n  // Where each token starts in before, for the changes' ids.\n  const starts: number[] = []\n  let offset = 0\n  for (const token of a) {\n    starts.push(offset)\n    offset += token.length\n  }\n  starts.push(offset)\n\n  const parts: TextDiffPart[] = []\n  const changes: TextChange[] = []\n  const growingIds: string[] = []\n  for (const piece of pieces) {\n    if (piece.kind === 'same') {\n      parts.push({\n        kind: 'same',\n        text: a.slice(piece.a, piece.a + piece.length).join(''),\n      })\n      continue\n    }\n    const change: TextChange = {\n      id: `at-${starts[piece.a]}`,\n      removed: a.slice(piece.a, piece.a + piece.removed).join(''),\n      added: b.slice(piece.b, piece.b + piece.added).join(''),\n    }\n    changes.push(change)\n    if (growing.has(piece)) growingIds.push(change.id)\n    parts.push({ kind: 'change', change })\n  }\n  if (pending > 0)\n    parts.push({ kind: 'pending', text: a.slice(a.length - pending).join('') })\n  return { parts, changes, growing: growingIds }\n}\n\n/** What a change leaves: after's text once accepted, before's once rejected, and `rest`'s for one not decided. */\nfunction keeps(id: string, resolved: Resolved, rest: Resolution) {\n  return (resolved[id] ?? rest) === 'accepted'\n}\n\n/**\n * The code once each change is decided: its added lines where accepted, its\n * removed ones where rejected, and undecided ones as `rest` says. Lines after\n * hasn't reached stay as before has them. Lines end as before's do, and the\n * last one with a line ending where the side its line came from has one.\n */\nfunction resolveCode(diff: CodeDiff, resolved: Resolved, rest: Resolution): string {\n  const lines: string[] = []\n  for (const row of diff.rows) {\n    if (row.kind !== 'change') lines.push(row.text)\n    else {\n      const side = keeps(row.change.id, resolved, rest)\n        ? row.change.added\n        : row.change.removed\n      for (const line of side) lines.push(line.text)\n    }\n  }\n  const last = diff.rows.at(-1)\n  // A final line ending is no change of its own, so with no change at the end, before's stays.\n  const fromAfter = last?.kind === 'change' && keeps(last.change.id, resolved, rest)\n  const ends = fromAfter ? diff.ends.after : diff.ends.before\n  return lines.join(diff.eol) + (ends && lines.length > 0 ? diff.eol : '')\n}\n\n/** The prose once each change is decided, as `resolveCode` does for code. */\nfunction resolveText(diff: TextDiff, resolved: Resolved, rest: Resolution): string {\n  return diff.parts\n    .map((part) =>\n      part.kind !== 'change'\n        ? part.text\n        : keeps(part.change.id, resolved, rest)\n          ? part.change.added\n          : part.change.removed,\n    )\n    .join('')\n}\n\nexport { diffCode, diffText, diffTokens, resolveCode, resolveText, wordsOf }\nexport type {\n  CodeChange,\n  CodeDiff,\n  CodeDiffRow,\n  DiffLine,\n  DiffOp,\n  DiffSpan,\n  Resolution,\n  Resolved,\n  Run,\n  TextChange,\n  TextDiff,\n  TextDiffPart,\n}\n",
      "type": "registry:lib",
      "target": "@lib/diff-math.ts"
    }
  ],
  "type": "registry:lib"
}