{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "text-diff",
  "title": "Text Diff",
  "description": "Word-level diff (Myers) that calls out changed numbers (30 → 14) and draws invisible changes like doubled spaces, line breaks and zero-width characters, in inline or split view, and stays fast on long documents with small changes.",
  "dependencies": [
    "lucide-react"
  ],
  "files": [
    {
      "path": "registry/default/text-diff/text-diff.tsx",
      "content": "// Bollard UI — text-diff · MIT licence · https://bollard-ui.vercel.app/components/text-diff\r\n\r\nimport * as React from \"react\"\r\nimport { EyeOff, Hash } from \"lucide-react\"\r\n\r\nimport { cn } from \"@/lib/utils\"\r\n\r\nexport type DiffPart = { type: \"equal\" | \"insert\" | \"delete\"; value: string }\r\n\r\n/** Whitespace, numbers (1,250.50 stays one token), words, then single symbols. */\r\nfunction tokenize(text: string) {\r\n  return text.match(/\\s+|\\p{N}+(?:[.,:]\\p{N}+)*|[\\p{L}\\p{N}_'-]+|[^\\s\\p{L}\\p{N}_]/gu) ?? []\r\n}\r\n\r\nconst isBlank = (text: string) => /^\\s+$/.test(text)\r\n\r\n/** Myers' shortest edit script over tokens, or null when it would need more than `budget` steps of memory. */\r\nfunction editScript(a: string[], b: string[], budget: number): DiffPart[] | null {\r\n  const n = a.length\r\n  const m = b.length\r\n  const offset = n + m + 1\r\n  const v = new Int32Array(2 * offset + 1)\r\n  const trace: Int32Array[] = []\r\n  let used = 0\r\n  for (let d = 0; d <= n + m; d++) {\r\n    // Only diagonals -d..d are live at this depth, so keep just that slice for the backtrack.\r\n    trace.push(v.slice(offset - d, offset + d + 1))\r\n    used += 2 * d + 1\r\n    if (used > budget) return null\r\n    for (let k = -d; k <= d; k += 2) {\r\n      let x = k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1]) ? v[offset + k + 1] : v[offset + k - 1] + 1\r\n      let y = x - k\r\n      while (x < n && y < m && a[x] === b[y]) {\r\n        x++\r\n        y++\r\n      }\r\n      v[offset + k] = x\r\n      if (x >= n && y >= m) return backtrack(a, b, trace, d, k)\r\n    }\r\n  }\r\n  return null\r\n}\r\n\r\nfunction backtrack(a: string[], b: string[], trace: Int32Array[], depth: number, endK: number) {\r\n  const ops: DiffPart[] = []\r\n  let x = a.length\r\n  let y = b.length\r\n  let k = endK\r\n  for (let d = depth; d > 0; d--) {\r\n    const prev = trace[d] // the V before step d, sliced to diagonals -d..d\r\n    const at = (diag: number) => prev[diag + d]\r\n    const down = k === -d || (k !== d && at(k - 1) < at(k + 1))\r\n    const prevK = down ? k + 1 : k - 1\r\n    const prevX = at(prevK)\r\n    const prevY = prevX - prevK\r\n    while (x > prevX && y > prevY) ops.push({ type: \"equal\", value: a[--x] }), y--\r\n    if (down) ops.push({ type: \"insert\", value: b[--y] })\r\n    else ops.push({ type: \"delete\", value: a[--x] })\r\n    k = prevK\r\n  }\r\n  while (x > 0 && y > 0) ops.push({ type: \"equal\", value: a[--x] }), y--\r\n  return ops.reverse()\r\n}\r\n\r\n/**\r\n * Word-level diff (Myers' algorithm on word tokens), cheap when the texts are mostly the\r\n * same however long they are. If two texts differ almost everywhere and are long enough to\r\n * stall the page (over `maxCost`), the changed part is shown as one removal plus one\r\n * addition instead. A lone space between two changes is folded into them, so a rewritten\r\n * phrase reads as one removal and one addition instead of word-by-word confetti. Within a\r\n * change, removals come before additions.\r\n */\r\nexport function diffWords(before: string, after: string, { maxCost = 4_000_000 }: { maxCost?: number } = {}): DiffPart[] {\r\n  const a = tokenize(before)\r\n  const b = tokenize(after)\r\n  let start = 0\r\n  while (start < a.length && start < b.length && a[start] === b[start]) start++\r\n  let endA = a.length\r\n  let endB = b.length\r\n  while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {\r\n    endA--\r\n    endB--\r\n  }\r\n  const midA = a.slice(start, endA)\r\n  const midB = b.slice(start, endB)\r\n  const middle = editScript(midA, midB, maxCost) ?? [\r\n    ...midA.map((value) => ({ type: \"delete\" as const, value })),\r\n    ...midB.map((value) => ({ type: \"insert\" as const, value })),\r\n  ]\r\n  const equal = (value: string) => ({ type: \"equal\" as const, value })\r\n  const ops: DiffPart[] = [...a.slice(0, start).map(equal), ...middle, ...a.slice(endA).map(equal)]\r\n\r\n  const parts: DiffPart[] = []\r\n  const push = (type: DiffPart[\"type\"], value: string) => {\r\n    if (!value) return\r\n    const last = parts[parts.length - 1]\r\n    if (last?.type === type) last.value += value\r\n    else parts.push({ type, value })\r\n  }\r\n  const changed = (op?: DiffPart) => op !== undefined && op.type !== \"equal\"\r\n  for (let k = 0; k < ops.length; ) {\r\n    if (!changed(ops[k])) {\r\n      push(\"equal\", ops[k++].value)\r\n      continue\r\n    }\r\n    let removed = \"\"\r\n    let added = \"\"\r\n    while (k < ops.length) {\r\n      const op = ops[k]\r\n      if (op.type === \"delete\") removed += op.value\r\n      else if (op.type === \"insert\") added += op.value\r\n      else if (isBlank(op.value) && changed(ops[k + 1])) {\r\n        removed += op.value\r\n        added += op.value\r\n      } else break\r\n      k++\r\n    }\r\n    push(\"delete\", removed)\r\n    push(\"insert\", added)\r\n  }\r\n  return parts\r\n}\r\n\r\n/** Characters that change text without being seen: zero-width marks, NBSP, BOM. */\r\nconst INVISIBLE = /[\\u00A0\\u200B-\\u200D\\u2060\\uFEFF]/\r\nconst MARKERS: Record<string, string> = { \" \": \"·\", \"\\t\": \"⇥\", \"\\n\": \"⏎\\n\", \"\\u00A0\": \"⍽\", \"\\u200B\": \"∅\", \"\\u200C\": \"∅\", \"\\u200D\": \"∅\", \"\\u2060\": \"∅\", \"\\uFEFF\": \"∅\" }\r\nconst NUMBER = /\\p{N}+(?:[.,:]\\p{N}+)*/gu\r\n\r\n/** True when a change would be invisible on screen: only whitespace, or a zero-width or no-break character. */\r\nexport function isInvisibleChange(value: string) {\r\n  return isBlank(value) || INVISIBLE.test(value)\r\n}\r\n\r\nexport interface DiffSummary {\r\n  /** Words added and removed. */\r\n  added: number\r\n  removed: number\r\n  /** Numbers that changed, paired by position within each change: { from: \"30\", to: \"60\" }. */\r\n  numbers: { from: string; to: string }[]\r\n  /** Changes you couldn't see without markers. */\r\n  invisible: number\r\n}\r\n\r\nconst words = (text: string) => text.match(/\\p{N}+(?:[.,:]\\p{N}+)*|[\\p{L}\\p{N}_'-]+/gu)?.length ?? 0\r\n\r\n/** Counts a diff and pulls out the changes that are easy to miss: numbers and invisible edits. */\r\nexport function summarizeDiff(parts: DiffPart[]): DiffSummary {\r\n  const summary: DiffSummary = { added: 0, removed: 0, numbers: [], invisible: 0 }\r\n  for (let k = 0; k < parts.length; k++) {\r\n    const part = parts[k]\r\n    if (part.type === \"equal\") continue\r\n    // A change is a removal, an addition, or a removal followed by its replacement.\r\n    const removed = part.type === \"delete\" ? part.value : \"\"\r\n    const added = part.type === \"insert\" ? part.value : parts[k + 1]?.type === \"insert\" ? parts[++k].value : \"\"\r\n    summary.added += words(added)\r\n    summary.removed += words(removed)\r\n    if (isInvisibleChange(removed) || isInvisibleChange(added)) summary.invisible++\r\n    const from = removed.match(NUMBER) ?? []\r\n    const to = added.match(NUMBER) ?? []\r\n    for (let n = 0; n < Math.max(from.length, to.length); n++) {\r\n      if (from[n] !== to[n]) summary.numbers.push({ from: from[n] ?? \"—\", to: to[n] ?? \"—\" })\r\n    }\r\n  }\r\n  return summary\r\n}\r\n\r\n/** Draws whitespace and zero-width characters so a change made of them can be seen. */\r\nfunction showInvisible(value: string) {\r\n  return isInvisibleChange(value) ? Array.from(value, (ch) => MARKERS[ch] ?? ch).join(\"\") : value\r\n}\r\n\r\nexport interface TextDiffProps extends React.ComponentProps<\"div\"> {\r\n  /** The original text. */\r\n  before: string\r\n  /** The changed text. */\r\n  after: string\r\n  /** `inline` interleaves changes; `split` shows before and after side by side. */\r\n  view?: \"inline\" | \"split\"\r\n  /** Show the word counts and the \"numbers changed\" / \"invisible change\" callouts. */\r\n  showStats?: boolean\r\n  /** Heading of the left column in split view. */\r\n  beforeLabel?: string\r\n  /** Heading of the right column in split view. */\r\n  afterLabel?: string\r\n  /** Templates: `{count}` is filled in. */\r\n  addedText?: string\r\n  /** Count label for removed words. */\r\n  removedText?: string\r\n  /** Lead-in before the changed numbers (\"30 → 14, 4417 → 4471\"). */\r\n  numbersText?: (count: number) => string\r\n  /** Count label for invisible-character changes. */\r\n  invisibleText?: (count: number) => string\r\n  /** Shown instead of the stats when the two texts are the same. */\r\n  identicalText?: string\r\n  /** Read before each change by screen readers. */\r\n  srAddedLabel?: string\r\n  /** Screen-reader prefix for removed text. */\r\n  srRemovedLabel?: string\r\n}\r\n\r\nconst fill = (template: string, count: number) => template.replace(\"{count}\", String(count))\r\n\r\nconst styles = {\r\n  insert: \"rounded-sm bg-emerald-500/15 text-emerald-800 no-underline dark:text-emerald-300\",\r\n  delete: \"rounded-sm bg-red-500/15 text-red-800 line-through decoration-red-500/60 dark:text-red-300\",\r\n  invisible: \"px-0.5 font-mono ring-1 ring-current/40\",\r\n}\r\n\r\n/**\r\n * Shows exactly what changed between two texts, word by word, so nobody\r\n * approves an edit they didn't see. Changed numbers are called out\r\n * (\"30 → 60\") and invisible edits (a doubled space, a line break, a\r\n * zero-width character) are drawn with markers instead of vanishing.\r\n */\r\nexport function TextDiff({\r\n  before,\r\n  after,\r\n  view = \"inline\",\r\n  showStats = true,\r\n  beforeLabel = \"Before\",\r\n  afterLabel = \"After\",\r\n  addedText = \"+{count} added\",\r\n  removedText = \"−{count} removed\",\r\n  numbersText = (count) => (count === 1 ? \"Number changed:\" : `${count} numbers changed:`),\r\n  invisibleText = (count) => (count === 1 ? \"1 invisible change\" : `${count} invisible changes`),\r\n  identicalText = \"No changes\",\r\n  srAddedLabel = \"added: \",\r\n  srRemovedLabel = \"removed: \",\r\n  className,\r\n  ...props\r\n}: TextDiffProps) {\r\n  const parts = React.useMemo(() => diffWords(before, after), [before, after])\r\n  const summary = React.useMemo(() => summarizeDiff(parts), [parts])\r\n  const identical = parts.every((part) => part.type === \"equal\")\r\n\r\n  const render = (skip: DiffPart[\"type\"] | null) =>\r\n    parts.map((part, index) => {\r\n      if (part.type === skip) return null\r\n      if (part.type === \"equal\") return <span key={index}>{part.value}</span>\r\n      const Tag = part.type === \"insert\" ? \"ins\" : \"del\"\r\n      const hidden = isInvisibleChange(part.value)\r\n      return (\r\n        <Tag key={index} title={hidden ? \"Invisible characters\" : undefined} className={cn(styles[part.type], hidden && styles.invisible, !skip && parts[index - 1]?.type === \"delete\" && \"ml-0.5\")}>\r\n          <span className=\"sr-only\">{part.type === \"insert\" ? srAddedLabel : srRemovedLabel}</span>\r\n          {showInvisible(part.value)}\r\n        </Tag>\r\n      )\r\n    })\r\n\r\n  const paragraph = \"px-4 py-3 leading-relaxed break-words whitespace-pre-wrap\"\r\n\r\n  return (\r\n    <div data-slot=\"text-diff\" className={cn(\"rounded-lg border bg-card text-sm text-card-foreground\", className)} {...props}>\r\n      {showStats && (\r\n        <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1.5 border-b px-4 py-2 text-xs font-medium\">\r\n          {identical ? (\r\n            <span className=\"text-muted-foreground\">{identicalText}</span>\r\n          ) : (\r\n            <>\r\n              <span className=\"text-emerald-700 dark:text-emerald-400\">{fill(addedText, summary.added)}</span>\r\n              <span className=\"text-red-700 dark:text-red-400\">{fill(removedText, summary.removed)}</span>\r\n            </>\r\n          )}\r\n          {summary.numbers.length > 0 && (\r\n            <span className=\"inline-flex flex-wrap items-center gap-1 rounded-md bg-amber-100 px-2 py-0.5 text-amber-900 dark:bg-amber-500/15 dark:text-amber-200\">\r\n              <Hash aria-hidden className=\"size-3\" />\r\n              {numbersText(summary.numbers.length)}{\" \"}\r\n              <span className=\"font-mono\">{summary.numbers.map((change) => `${change.from} → ${change.to}`).join(\", \")}</span>\r\n            </span>\r\n          )}\r\n          {summary.invisible > 0 && (\r\n            <span className=\"inline-flex flex-wrap items-center gap-1 rounded-md bg-amber-100 px-2 py-0.5 text-amber-900 dark:bg-amber-500/15 dark:text-amber-200\">\r\n              <EyeOff aria-hidden className=\"size-3\" />\r\n              {invisibleText(summary.invisible)}\r\n            </span>\r\n          )}\r\n        </div>\r\n      )}\r\n      {view === \"inline\" ? (\r\n        <p className={paragraph}>{render(null)}</p>\r\n      ) : (\r\n        <div className=\"grid divide-y sm:grid-cols-2 sm:divide-x sm:divide-y-0\">\r\n          <p className={paragraph}>\r\n            <span className=\"mb-1 block text-xs font-medium text-muted-foreground\">{beforeLabel}</span>\r\n            {render(\"insert\")}\r\n          </p>\r\n          <p className={paragraph}>\r\n            <span className=\"mb-1 block text-xs font-medium text-muted-foreground\">{afterLabel}</span>\r\n            {render(\"delete\")}\r\n          </p>\r\n        </div>\r\n      )}\r\n    </div>\r\n  )\r\n}\r\n",
      "type": "registry:ui",
      "target": "@ui/text-diff.tsx"
    }
  ],
  "meta": {
    "stops": "Approved an edit I didn't see",
    "mistakes": [
      "hidden change in text",
      "zero width characters",
      "number changed in contract",
      "compare two texts",
      "diff checker"
    ],
    "aliases": [
      "diff",
      "text compare",
      "track changes",
      "review",
      "contract",
      "redline",
      "word diff",
      "diffchecker"
    ],
    "flows": [
      "devtools",
      "forms"
    ],
    "fields": [
      "text"
    ],
    "summary": "Shows a word-level diff that makes changed numbers and invisible whitespace changes visible, so an edit can't slip through unseen.",
    "catches": [
      "Changed numbers, kept whole (1,250.50 is one token) and called out",
      "Whitespace, line-break and zero-width character changes, drawn visibly",
      "Identical texts, said plainly",
      "Counts of words added and removed"
    ],
    "limits": [
      "Word-level, not semantic: reworded sentences show as remove + add",
      "Very large diffs fall back to a coarser result past the memory budget"
    ],
    "a11y": [
      "Added and removed runs carry sr-only labels (srAddedLabel/srRemovedLabel)",
      "Invisible characters have a title tooltip",
      "Icons are aria-hidden"
    ],
    "usage": "import { TextDiff } from \"@/components/ui/text-diff\"",
    "runtimeDependencies": [
      "lucide-react"
    ],
    "zeroRuntimeDependencies": false
  },
  "docs": "https://bollard-ui.vercel.app/components/text-diff",
  "categories": [
    "Reading without mistakes"
  ],
  "type": "registry:ui"
}
