Skip to content
Shaken UI
Sign in

Diff Viewer

Save

What an agent changed in a file, diffed locally from old and new text or read from a unified diff, in unified or split layout with word highlights, folded unchanged lines, and optional per hunk Accept and Reject.

Category
AI elements
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Diff Viewer preview

Round prorated invoices once

+14 lines added,−2 lines removed
Diff layout
+9 lines added,−0 lines removed
@@ -6,4 +6,13 @@
const result = prorate({ lines: [{ id: "seat", amount: 30 }], daysUsed: 10, daysInPeriod: 30 });
expect(result.total).toBe(10);
});
Added:
Added: it("rounds half cents once, after the sum", () => {
Added: const lines = [
Added: { id: "seat", amount: 12.335 },
Added: { id: "storage", amount: 0.005 },
Added: ];
Added: const result = prorate({ lines, daysUsed: 30, daysInPeriod: 30 });
Added: expect(result.total).toBe(12.34);
Added: });
});
+4 lines added,−2 lines removed
@@ -1,6 +1,8 @@
Removed: /** Rounds to cents. */
Added: /** Rounds to cents, half away from zero, so 0.005 becomes 0.01. */
export function round(amount: number) {
Removed: return Math.round(amount * 100) / 100;
Added: const cents = Math.abs(amount) * 100;
Added: const rounded = Math.round(cents + Number.EPSILON) / 100;
Added: return Math.sign(amount) * rounded;
}
export const ZERO = 0;
+1 lines added,−0 lines removed

Accept or reject a hunk to see the callback.

Installation

npx @shakenui/cli add diff-viewer

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add diff-viewer --dry-run

Usage

diff-viewer-example.tsx
"use client";

import { DiffViewer } from "@/components/shaken/agent/diff-viewer";

const before = `type InvoiceLine = { description: string; amount: number };

const round = (value: number) => Math.round(value * 100) / 100;

export interface ProrationInput {
  lines: InvoiceLine[];
  daysUsed: number;
  daysInPeriod: number;
}

/**
 * Prorates each line for the days used in the period.
 */
export function prorate({ lines, daysUsed, daysInPeriod }: ProrationInput) {
  const share = daysUsed / daysInPeriod;
  const prorated = lines.map((line) => ({
    ...line,
    amount: round(line.amount * share),
  }));
  const total = prorated.reduce((sum, line) => sum + line.amount, 0);
  return { lines: prorated, total };
}

export function describe(total: number, currency: string) {
  return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(total);
}
`;

const after = `type InvoiceLine = { description: string; amount: number };

const round = (value: number) => Math.round(value * 100) / 100;

export interface ProrationInput {
  lines: InvoiceLine[];
  daysUsed: number;
  daysInPeriod: number;
}

/**
 * Prorates each line for the days used in the period. Rounds once, after the sum,
 * so half cents on separate lines cannot both round down.
 */
export function prorate({ lines, daysUsed, daysInPeriod }: ProrationInput) {
  const share = daysUsed / daysInPeriod;
  const prorated = lines.map((line) => ({
    ...line,
    amount: line.amount * share,
  }));
  const total = round(prorated.reduce((sum, line) => sum + line.amount, 0));
  return { lines: prorated.map((line) => ({ ...line, amount: round(line.amount) })), total };
}

export function describe(total: number, currency: string) {
  return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(total);
}
`;

export default function DiffViewerExample() {
  return <DiffViewer path="src/billing/proration.ts" oldText={before} newText={after} context={2} hunkActions className="w-full max-w-3xl" />;
}

API

PropTypeDefaultDescription
pathstring—File path for the header. Read from the patch when unset.
oldText / newTextstring—The file before and after. Diffed in the browser with a Myers line diff and a word diff inside changed line pairs. Use "" for a new or deleted file.
patchstring—A unified diff for the file, used instead of oldText and newText.
oldPathstring—Previous path, shown as old → new for a rename.
view / defaultView / onViewChange"unified" | "split""unified"Layout. Split falls back to unified below 560px of width.
viewTogglebooleantrueShows the Unified and Split switch in the header.
contextnumber3Unchanged lines kept around each change; the rest fold into Show N lines rows.
onDecisionChange(hunk, decision: "accepted" | "rejected" | null) => void—Shows Accept and Reject on each hunk. null means Undo.
decisionsRecord<number, "accepted" | "rejected">—Controlled hunk decisions by hunk index.
hunkActionsbooleanonDecisionChange is setShows hunk actions with local state.
defaultCollapsedbooleanfalseStarts with the file body folded under its header.
wrapbooleanfalseSoft wraps long lines in the unified layout instead of scrolling them.
DiffViewerList{ files?: DiffFile[]; patch?: string; title?; onDecisionChange?(path, hunk, decision) }—Several files with a summary line, total counts, and one shared layout switch. Accepts a multi file git diff.
diffLines / parsePatchfunctions—The diff and the unified diff parser on their own.

Accessibility

  • Each file is a labeled region (Changes to path). The header is a button with aria-expanded that folds the body.
  • Added and removed lines carry visually hidden Added and Removed prefixes; the + and − signs and line numbers are hidden from screen readers, and color is never the only signal.
  • Addition and deletion counts are read as lines added and lines removed; the five block bar is decorative.
  • Show N lines rows, Accept, Reject, and Undo are native buttons; the layout switch is a radio group.
  • Accepting or rejecting a hunk folds its lines (aria-hidden and invisible) and leaves a summary row with Undo, so the decision stays reachable.
  • With reduced motion the fold reveal, hunk fold, and header chevron change instantly.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/agent/diff-viewer.tsxdiff-viewer
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/diff-viewer/0.1.0.json.

agent/diff-viewer.tsxShow
agent/diff-viewer.tsx
"use client";

import { type ComponentProps, type ReactNode, useEffect, useId, useMemo, useRef, useState } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";

/*
 * Diff viewer: what an agent changed in a file.
 *
 * Give it the old and new text and it computes a line diff locally (Myers, O((N+M)D)), then a
 * word diff inside each changed line pair. Or give it a unified diff string. Unchanged stretches
 * fold into "Show N lines" rows that open with a height reveal; an accepted or rejected hunk
 * folds itself away into a one line summary you can undo.
 */

// ---------------------------------------------------------------------------
// Diffing

export type DiffLineKind = "context" | "add" | "del";

export interface DiffPart {
  text: string;
  /** True when this run differs from the paired line. */
  changed: boolean;
}

export interface DiffLine {
  kind: DiffLineKind;
  text: string;
  oldNumber?: number;
  newNumber?: number;
  /** Word level runs, present on changed lines that pair with a similar line. */
  parts?: DiffPart[];
}

type Op = "equal" | "insert" | "delete";

/** Myers' greedy shortest edit script. Snapshots only the live diagonal window to keep memory linear in D. */
function myers<T>(a: T[], b: T[]): Op[] {
  // Trim the common prefix and suffix; most agent edits touch a small middle.
  let start = 0;
  while (start < a.length && start < b.length && a[start] === b[start]) start++;
  let endA = a.length;
  let endB = b.length;
  while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
    endA--;
    endB--;
  }
  const head: Op[] = Array.from({ length: start }, () => "equal");
  const tail: Op[] = Array.from({ length: a.length - endA }, () => "equal");
  const x0 = a.slice(start, endA);
  const y0 = b.slice(start, endB);
  const n = x0.length;
  const m = y0.length;
  if (n === 0) return [...head, ...Array.from({ length: m }, (): Op => "insert"), ...tail];
  if (m === 0) return [...head, ...Array.from({ length: n }, (): Op => "delete"), ...tail];

  const max = n + m;
  const off = max + 1;
  const v = new Int32Array(2 * max + 3);
  const trace: Int32Array[] = [];
  let found = -1;
  outer: for (let d = 0; d <= max; d++) {
    trace.push(v.slice(off - d - 1, off + d + 2));
    for (let k = -d; k <= d; k += 2) {
      let x = k === -d || (k !== d && v[off + k - 1]! < v[off + k + 1]!) ? v[off + k + 1]! : v[off + k - 1]! + 1;
      let y = x - k;
      while (x < n && y < m && x0[x] === y0[y]) {
        x++;
        y++;
      }
      v[off + k] = x;
      if (x >= n && y >= m) {
        found = d;
        break outer;
      }
    }
  }

  const ops: Op[] = [];
  let x = n;
  let y = m;
  for (let d = found; d >= 0; d--) {
    const snap = trace[d]!;
    const at = (k: number) => snap[k + d + 1]!;
    const k = x - y;
    const prevK = k === -d || (k !== d && at(k - 1) < at(k + 1)) ? k + 1 : k - 1;
    const prevX = d === 0 ? 0 : at(prevK);
    const prevY = prevX - prevK;
    while (x > prevX && y > prevY) {
      ops.push("equal");
      x--;
      y--;
    }
    if (d > 0) {
      ops.push(x === prevX ? "insert" : "delete");
      x = prevX;
      y = prevY;
    }
  }
  ops.reverse();
  return [...head, ...ops, ...tail];
}

function splitLines(text: string): string[] {
  if (text === "") return [];
  const lines = text.replace(/\r\n?/g, "\n").split("\n");
  if (lines[lines.length - 1] === "") lines.pop();
  return lines;
}

const tokenPattern = /\s+|[\p{L}\p{N}_]+|[^\s\p{L}\p{N}_]/gu;

/** Word level runs for a removed and an added line. Returns nothing when the lines share too little to be worth marking. */
function diffWords(before: string, after: string): [DiffPart[], DiffPart[]] | null {
  const a = before.match(tokenPattern) ?? [];
  const b = after.match(tokenPattern) ?? [];
  const ops = myers(a, b);
  const left: DiffPart[] = [];
  const right: DiffPart[] = [];
  const push = (into: DiffPart[], text: string, changed: boolean) => {
    const last = into[into.length - 1];
    if (last && last.changed === changed) last.text += text;
    else into.push({ text, changed });
  };
  let i = 0;
  let j = 0;
  let shared = 0;
  for (const op of ops) {
    if (op === "equal") {
      shared += a[i]!.trim() ? a[i]!.length : 0;
      push(left, a[i++]!, false);
      push(right, b[j++]!, false);
    } else if (op === "delete") push(left, a[i++]!, true);
    else push(right, b[j++]!, true);
  }
  // A line that was mostly rewritten reads better as a plain removed and added pair.
  const longest = Math.max(before.trim().length, after.trim().length);
  if (longest === 0) return null;
  const ratio = shared / longest;
  const runs = left.filter((part) => part.changed).length + right.filter((part) => part.changed).length;
  // Few changed runs (an appended clause, a wrapped call) highlight well; scattered edits turn to confetti.
  if (ratio < 0.4 || (ratio < 0.75 && runs > 4)) return null;
  return [left, right];
}

/** Puts every removed line of a change run before its added lines and pairs them for word highlights. */
function pairRun(dels: DiffLine[], adds: DiffLine[]) {
  for (let i = 0; i < Math.min(dels.length, adds.length); i++) {
    const words = diffWords(dels[i]!.text, adds[i]!.text);
    if (words) {
      dels[i]!.parts = words[0];
      adds[i]!.parts = words[1];
    }
  }
}

/** Every line of the new file plus the removed ones, in reading order, with line numbers and word runs. */
export function diffLines(oldText: string, newText: string): DiffLine[] {
  const a = splitLines(oldText);
  const b = splitLines(newText);
  const ops = myers(a, b);
  const out: DiffLine[] = [];
  let i = 0;
  let j = 0;
  let dels: DiffLine[] = [];
  let adds: DiffLine[] = [];
  const flush = () => {
    pairRun(dels, adds);
    out.push(...dels, ...adds);
    dels = [];
    adds = [];
  };
  for (const op of ops) {
    if (op === "equal") {
      flush();
      out.push({ kind: "context", text: b[j]!, oldNumber: ++i, newNumber: ++j });
    } else if (op === "delete") dels.push({ kind: "del", text: a[i]!, oldNumber: ++i });
    else adds.push({ kind: "add", text: b[j]!, newNumber: ++j });
  }
  flush();
  return out;
}

// ---------------------------------------------------------------------------
// Unified diff parsing

export interface PatchHunk {
  header: string;
  oldStart: number;
  newStart: number;
  lines: DiffLine[];
}

export interface PatchFile {
  oldPath?: string;
  newPath?: string;
  hunks: PatchHunk[];
}

const hunkHeader = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/;

/** Parses a unified diff (git or plain) into files and hunks. Hunk line counts decide where each hunk ends. */
export function parsePatch(patch: string): PatchFile[] {
  const files: PatchFile[] = [];
  let file: PatchFile | null = null;
  let hunk: PatchHunk | null = null;
  let oldNo = 0;
  let newNo = 0;
  let oldLeft = 0;
  let newLeft = 0;
  let dels: DiffLine[] = [];
  let adds: DiffLine[] = [];
  const flush = () => {
    if (hunk) {
      pairRun(dels, adds);
      hunk.lines.push(...dels, ...adds);
    }
    dels = [];
    adds = [];
  };
  const startFile = () => {
    file = { hunks: [] };
    files.push(file);
    return file;
  };
  const clean = (path: string) => {
    const value = path.trim().split("\t")[0]!;
    return value === "/dev/null" ? undefined : value.replace(/^[ab]\//, "");
  };

  for (const raw of patch.replace(/\r\n?/g, "\n").split("\n")) {
    if (hunk && (oldLeft > 0 || newLeft > 0)) {
      const sign = raw.charAt(0);
      const text = raw.slice(1);
      if (sign === "+") {
        adds.push({ kind: "add", text, newNumber: newNo++ });
        newLeft--;
      } else if (sign === "-") {
        dels.push({ kind: "del", text, oldNumber: oldNo++ });
        oldLeft--;
      } else if (sign === " " || raw === "") {
        flush();
        hunk.lines.push({ kind: "context", text, oldNumber: oldNo++, newNumber: newNo++ });
        oldLeft--;
        newLeft--;
      }
      // "\ No newline at end of file" carries no line.
      if (oldLeft <= 0 && newLeft <= 0) {
        flush();
        hunk = null;
      }
      continue;
    }
    if (raw.startsWith("diff --git ")) {
      const current = startFile();
      const match = /^diff --git a\/(.+) b\/(.+)$/.exec(raw);
      if (match) {
        current.oldPath = match[1];
        current.newPath = match[2];
      }
    } else if (raw.startsWith("--- ")) {
      const current: PatchFile = file && (file as PatchFile).hunks.length === 0 ? file : startFile();
      current.oldPath = clean(raw.slice(4));
    } else if (raw.startsWith("+++ ")) {
      (file ?? startFile()).newPath = clean(raw.slice(4));
    } else {
      const header = hunkHeader.exec(raw);
      if (!header) continue;
      oldNo = Number(header[1]);
      newNo = Number(header[3]);
      oldLeft = header[2] === undefined ? 1 : Number(header[2]);
      newLeft = header[4] === undefined ? 1 : Number(header[4]);
      hunk = { header: raw, oldStart: oldNo, newStart: newNo, lines: [] };
      (file ?? startFile()).hunks.push(hunk);
      if (oldLeft <= 0 && newLeft <= 0) hunk = null;
    }
  }
  flush();
  return files;
}

// ---------------------------------------------------------------------------
// Segments: hunks with folded unchanged stretches between them

type Segment =
  | { type: "hunk"; index: number; header: string; lines: DiffLine[] }
  | { type: "gap"; key: string; lines: DiffLine[] | null; count: number; edge: "start" | "middle" | "end" };

function headerFor(lines: DiffLine[]): string {
  const oldLines = lines.filter((line) => line.kind !== "add");
  const newLines = lines.filter((line) => line.kind !== "del");
  const oldStart = oldLines[0]?.oldNumber ?? (lines.find((line) => line.oldNumber)?.oldNumber ?? 1) - 1;
  const newStart = newLines[0]?.newNumber ?? (lines.find((line) => line.newNumber)?.newNumber ?? 1) - 1;
  return `@@ -${oldStart},${oldLines.length} +${newStart},${newLines.length} @@`;
}

function segmentsFromLines(lines: DiffLine[], context: number): Segment[] {
  const ranges: [number, number][] = [];
  lines.forEach((line, index) => {
    if (line.kind === "context") return;
    const from = Math.max(0, index - context);
    const to = Math.min(lines.length - 1, index + context);
    const last = ranges[ranges.length - 1];
    // Folding fewer than four lines saves nothing, so close gaps merge into one hunk.
    if (last && from <= last[1] + 4) last[1] = Math.max(last[1], to);
    else ranges.push([from, to]);
  });
  const out: Segment[] = [];
  let cursor = 0;
  ranges.forEach(([from, to], index) => {
    if (from > cursor) out.push({ type: "gap", key: `g${cursor}`, lines: lines.slice(cursor, from), count: from - cursor, edge: cursor === 0 ? "start" : "middle" });
    const slice = lines.slice(from, to + 1);
    out.push({ type: "hunk", index, header: headerFor(slice), lines: slice });
    cursor = to + 1;
  });
  if (cursor < lines.length && ranges.length > 0) out.push({ type: "gap", key: `g${cursor}`, lines: lines.slice(cursor), count: lines.length - cursor, edge: "end" });
  return out;
}

function segmentsFromPatch(file: PatchFile): Segment[] {
  const out: Segment[] = [];
  let nextNew = 1;
  file.hunks.forEach((hunk, index) => {
    const hidden = hunk.newStart - nextNew;
    if (hidden > 0 && index > 0) out.push({ type: "gap", key: `p${index}`, lines: null, count: hidden, edge: "middle" });
    out.push({ type: "hunk", index, header: hunk.header, lines: hunk.lines });
    const newLines = hunk.lines.filter((line) => line.kind !== "del").length;
    nextNew = hunk.newStart + newLines;
  });
  return out;
}

function countLines(lines: DiffLine[]) {
  let additions = 0;
  let deletions = 0;
  for (const line of lines) {
    if (line.kind === "add") additions++;
    else if (line.kind === "del") deletions++;
  }
  return { additions, deletions };
}

// ---------------------------------------------------------------------------
// Component

export type DiffView = "unified" | "split";
export type HunkDecision = "accepted" | "rejected";

export interface DiffViewerProps extends Omit<ComponentProps<"section">, "children"> {
  /** File path shown in the header, for example `src/billing/proration.ts`. */
  path?: string;
  /** Previous path when the file was renamed. */
  oldPath?: string;
  /** The file before the change. Pair with `newText`; use `""` for a new file. */
  oldText?: string;
  /** The file after the change. */
  newText?: string;
  /** A unified diff for this file, used instead of `oldText` and `newText`. Paths come from it when `path` is unset. */
  patch?: string;
  /** Controlled layout. */
  view?: DiffView;
  /** Initial layout when uncontrolled. Split falls back to unified below 560px of width. */
  defaultView?: DiffView;
  onViewChange?: (view: DiffView) => void;
  /** Shows the Unified and Split switch in the header. */
  viewToggle?: boolean;
  /** Unchanged lines kept around each change. */
  context?: number;
  /** Controlled hunk decisions, keyed by hunk index. */
  decisions?: Record<number, HunkDecision | undefined>;
  /** Called when a hunk is accepted, rejected, or undone (`null`). Shows the Accept and Reject actions. */
  onDecisionChange?: (hunk: number, decision: HunkDecision | null) => void;
  /** Shows hunk actions even without `onDecisionChange`, with local state. */
  hunkActions?: boolean;
  /** Starts with the file body collapsed. */
  defaultCollapsed?: boolean;
  /** Soft wraps long lines in the unified layout instead of scrolling. Split always wraps. */
  wrap?: boolean;
}

/** One file's changes with a header, line numbers, folded unchanged lines, and optional per hunk Accept and Reject. */
export function DiffViewer({
  path,
  oldPath,
  oldText,
  newText,
  patch,
  view: viewProp,
  defaultView = "unified",
  onViewChange,
  viewToggle = true,
  context = 3,
  decisions: decisionsProp,
  onDecisionChange,
  hunkActions,
  defaultCollapsed = false,
  wrap = false,
  className,
  ...props
}: DiffViewerProps) {
  const parsed = useMemo(() => {
    if (patch != null) {
      const file = parsePatch(patch)[0] ?? { hunks: [] };
      const lines = file.hunks.flatMap((hunk) => hunk.lines);
      return {
        segments: segmentsFromPatch(file),
        ...countLines(lines),
        path: path ?? file.newPath ?? file.oldPath ?? "",
        oldPath: oldPath ?? (file.oldPath !== file.newPath ? file.oldPath : undefined),
        status: !file.oldPath && file.newPath ? "added" : file.oldPath && !file.newPath ? "deleted" : undefined,
      };
    }
    const lines = diffLines(oldText ?? "", newText ?? "");
    return {
      segments: segmentsFromLines(lines, context),
      ...countLines(lines),
      path: path ?? "",
      oldPath,
      status: !oldText && newText ? "added" : oldText && !newText ? "deleted" : undefined,
    };
  }, [patch, oldText, newText, context, path, oldPath]);

  const [localView, setLocalView] = useState<DiffView>(defaultView);
  const requested = viewProp ?? localView;
  const ref = useRef<HTMLElement>(null);
  const narrow = useNarrow(ref, 560);
  const view: DiffView = narrow ? "unified" : requested;

  const [localDecisions, setLocalDecisions] = useState<Record<number, HunkDecision | undefined>>({});
  const decisions = decisionsProp ?? localDecisions;
  const showActions = hunkActions ?? onDecisionChange !== undefined;
  const decide = (index: number, decision: HunkDecision | null) => {
    if (decisionsProp === undefined) setLocalDecisions((current) => ({ ...current, [index]: decision ?? undefined }));
    onDecisionChange?.(index, decision);
  };

  const [collapsed, setCollapsed] = useState(defaultCollapsed);
  const bodyId = useId();
  const hunks = parsed.segments.filter((segment) => segment.type === "hunk").length;
  const reviewed = Object.values(decisions).filter(Boolean).length;

  return (
    <section
      ref={ref}
      aria-label={parsed.path ? `Changes to ${parsed.path}` : "Changes"}
      className={cx(
        "overflow-hidden rounded-xl border border-zinc-950/10 bg-white text-left text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
        "dark:border-white/10 dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
        className,
      )}
      {...props}
    >
      <header className="flex min-h-11 items-center gap-2 py-1.5 pr-2 pl-1.5">
        <button
          type="button"
          aria-expanded={!collapsed}
          aria-controls={bodyId}
          onClick={() => setCollapsed((value) => !value)}
          className={cx(
            "group flex min-w-0 flex-1 cursor-pointer items-center gap-1.5 rounded-lg py-1 pr-2 pl-1 text-left",
            "transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] motion-reduce:transition-none dark:hover:bg-white/[0.06]",
            "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
          )}
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 16 16"
            fill="none"
            className={`size-4 shrink-0 text-zinc-400 transition-[rotate] duration-200 ${ease} group-aria-expanded:rotate-90 motion-reduce:transition-none dark:text-zinc-500`}
          >
            <path d="m6.25 4.5 3.5 3.5-3.5 3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          <FilePath path={parsed.path} oldPath={parsed.oldPath} />
          {parsed.status ? (
            <span className="shrink-0 rounded-md border border-zinc-950/10 px-1.5 text-[11px] leading-[18px] text-zinc-500 dark:border-white/10">
              {parsed.status === "added" ? "New" : "Deleted"}
            </span>
          ) : null}
        </button>
        {showActions && hunks > 0 ? (
          <span className="hidden shrink-0 font-mono text-[11px] text-zinc-500 tabular-nums sm:inline">
            {reviewed}/{hunks} reviewed
          </span>
        ) : null}
        <DiffStat additions={parsed.additions} deletions={parsed.deletions} />
        {viewToggle && !narrow ? <ViewSwitch value={view} onChange={(next) => (viewProp === undefined ? setLocalView(next) : null, onViewChange?.(next))} /> : null}
      </header>

      <div
        id={bodyId}
        className={cx(
          "grid transition-[grid-template-rows,visibility] motion-reduce:transition-none",
          ease,
          collapsed ? "invisible grid-rows-[0fr] duration-180" : "visible grid-rows-[1fr] duration-220",
        )}
      >
        <div className="min-h-0 overflow-hidden">
          <div className="border-t border-zinc-950/[0.07] font-mono text-xs leading-5 dark:border-white/[0.08]">
            {parsed.segments.length === 0 ? (
              <p className="px-4 py-3 font-sans text-sm text-zinc-500">No changes</p>
            ) : (
              parsed.segments.map((segment) =>
                segment.type === "gap" ? (
                  <Gap key={segment.key} segment={segment} view={view} wrap={wrap} />
                ) : (
                  <Hunk
                    key={`h${segment.index}`}
                    segment={segment}
                    view={view}
                    wrap={wrap}
                    actions={showActions}
                    decision={decisions[segment.index]}
                    onDecide={(decision) => decide(segment.index, decision)}
                  />
                ),
              )
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function FilePath({ path, oldPath }: { path: string; oldPath?: string }) {
  const split = (value: string) => {
    const at = value.lastIndexOf("/");
    return at < 0 ? ["", value] : [value.slice(0, at + 1), value.slice(at + 1)];
  };
  const [dir, name] = split(path);
  return (
    <span className="flex min-w-0 items-baseline font-mono text-[13px] leading-6">
      {oldPath ? (
        <>
          <span className="min-w-0 truncate text-zinc-500">{oldPath}</span>
          <span aria-label="renamed to" className="shrink-0 px-1.5 text-zinc-400 dark:text-zinc-600">
            →
          </span>
        </>
      ) : null}
      {/* The folder gives way first; the file name only truncates once the folder is gone. */}
      <span className="min-w-0 shrink-[100] truncate text-zinc-500">{dir}</span>
      <span className="min-w-0 truncate font-medium">{name}</span>
    </span>
  );
}

/** Counts plus a five block bar of the add and remove share. */
function DiffStat({ additions, deletions }: { additions: number; deletions: number }) {
  const total = additions + deletions;
  const green = total === 0 ? 0 : Math.round((additions / total) * 5);
  const red = total === 0 ? 0 : Math.min(5 - green, Math.max(deletions > 0 ? 1 : 0, Math.round((deletions / total) * 5)));
  return (
    <span className="flex shrink-0 items-center gap-2 font-mono text-xs tabular-nums">
      <span className="text-emerald-600 dark:text-emerald-400">
        +{additions}
        <span className="sr-only"> lines added,</span>
      </span>
      <span className="text-red-600 dark:text-red-400">
        −{deletions}
        <span className="sr-only"> lines removed</span>
      </span>
      <span aria-hidden="true" className="hidden gap-0.5 min-[420px]:flex">
        {Array.from({ length: 5 }, (_, index) => (
          <span
            key={index}
            className={cx(
              "size-2 rounded-[2px]",
              index < green ? "bg-emerald-500" : index < green + red ? "bg-red-500" : "bg-zinc-950/10 dark:bg-white/15",
            )}
          />
        ))}
      </span>
    </span>
  );
}

function ViewSwitch({ value, onChange }: { value: DiffView; onChange: (view: DiffView) => void }) {
  const name = useId();
  return (
    <fieldset className="flex shrink-0 rounded-lg border border-zinc-950/10 p-0.5 dark:border-white/10">
      <legend className="sr-only">Diff layout</legend>
      {(["unified", "split"] as const).map((option) => (
        <label key={option} className="relative">
          <input type="radio" name={name} value={option} checked={value === option} onChange={() => onChange(option)} className="peer sr-only" />
          <span
            className={cx(
              "block cursor-pointer rounded-md px-2 py-0.5 text-xs font-medium text-zinc-500 capitalize select-none",
              "transition-colors duration-150 ease-out hover:text-zinc-950 motion-reduce:transition-none dark:hover:text-white",
              "peer-checked:bg-zinc-950/[0.06] peer-checked:text-zinc-950 dark:peer-checked:bg-white/[0.09] dark:peer-checked:text-white",
              "peer-focus-visible:outline-2 peer-focus-visible:outline-solid peer-focus-visible:outline-offset-1 peer-focus-visible:outline-sky-500",
            )}
          >
            {option}
          </span>
        </label>
      ))}
    </fieldset>
  );
}

const rowTone: Record<DiffLineKind, string> = {
  context: "",
  add: "bg-emerald-500/[0.08] dark:bg-emerald-400/[0.09]",
  del: "bg-red-500/[0.08] dark:bg-red-400/[0.09]",
};
const numberTone: Record<DiffLineKind, string> = {
  context: "text-zinc-400 dark:text-zinc-600",
  add: "text-emerald-700/70 dark:text-emerald-400/60",
  del: "text-red-700/70 dark:text-red-400/60",
};
const markTone: Record<Exclude<DiffLineKind, "context">, string> = {
  add: "bg-emerald-500/20 dark:bg-emerald-400/25",
  del: "bg-red-500/20 dark:bg-red-400/25",
};
const signs: Record<DiffLineKind, { glyph: string; label: string; tone: string }> = {
  context: { glyph: " ", label: "", tone: "" },
  add: { glyph: "+", label: "Added", tone: "text-emerald-600 dark:text-emerald-400" },
  del: { glyph: "−", label: "Removed", tone: "text-red-600 dark:text-red-400" },
};

function Content({ line }: { line: DiffLine }) {
  if (!line.parts || line.kind === "context") return <>{line.text || " "}</>;
  const tone = markTone[line.kind];
  return (
    <>
      {line.parts.map((part, index) =>
        part.changed ? (
          <mark key={index} className={cx("rounded-[3px] text-inherit", tone)}>
            {part.text}
          </mark>
        ) : (
          <span key={index}>{part.text}</span>
        ),
      )}
    </>
  );
}

function Sign({ kind }: { kind: DiffLineKind }) {
  const sign = signs[kind];
  return (
    <span className={cx("w-5 shrink-0 text-center select-none", sign.tone)}>
      <span aria-hidden="true">{sign.glyph}</span>
      {sign.label ? <span className="sr-only">{sign.label}: </span> : null}
    </span>
  );
}

function Num({ value, kind, width }: { value?: number; kind: DiffLineKind; width: number }) {
  return (
    <span aria-hidden="true" style={{ minWidth: `${width + 2}ch` }} className={cx("shrink-0 px-2 text-right tabular-nums select-none", numberTone[kind])}>
      {value ?? ""}
    </span>
  );
}

function digits(lines: DiffLine[]) {
  let max = 0;
  for (const line of lines) max = Math.max(max, line.oldNumber ?? 0, line.newNumber ?? 0);
  return String(max).length;
}

/** The lines of a hunk or an opened fold, in the chosen layout. */
function Lines({ lines, view, wrap, width }: { lines: DiffLine[]; view: DiffView; wrap: boolean; width: number }) {
  const text = "text-zinc-800 dark:text-zinc-200";
  if (view === "unified") {
    return (
      <div className={cx(!wrap && "overflow-x-auto")}>
        <div className={cx(!wrap && "w-max min-w-full")}>
          {lines.map((line, index) => (
            <div key={index} className={cx("flex", rowTone[line.kind])}>
              <Num value={line.oldNumber} kind={line.kind} width={width} />
              <Num value={line.newNumber} kind={line.kind} width={width} />
              <Sign kind={line.kind} />
              <span className={cx("min-w-0 flex-1 pr-4", text, wrap ? "whitespace-pre-wrap wrap-anywhere" : "whitespace-pre")}>
                <Content line={line} />
              </span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // Split: removed lines on the left, added on the right, paired row by row within each change run.
  const rows: [DiffLine | null, DiffLine | null][] = [];
  for (let i = 0; i < lines.length; ) {
    const line = lines[i]!;
    if (line.kind === "context") {
      rows.push([line, line]);
      i++;
      continue;
    }
    const dels: DiffLine[] = [];
    const adds: DiffLine[] = [];
    while (i < lines.length && lines[i]!.kind === "del") dels.push(lines[i++]!);
    while (i < lines.length && lines[i]!.kind === "add") adds.push(lines[i++]!);
    for (let r = 0; r < Math.max(dels.length, adds.length); r++) rows.push([dels[r] ?? null, adds[r] ?? null]);
  }
  const empty =
    "bg-[repeating-linear-gradient(135deg,transparent_0_5px,rgb(9_9_11/0.035)_5px_6px)] dark:bg-[repeating-linear-gradient(135deg,transparent_0_5px,rgb(255_255_255/0.05)_5px_6px)]";
  const side = (line: DiffLine | null, which: "old" | "new") =>
    line ? (
      <div className={cx("flex min-w-0", rowTone[line.kind])}>
        <Num value={which === "old" ? line.oldNumber : line.newNumber} kind={line.kind} width={width} />
        <Sign kind={line.kind} />
        <span className={cx("min-w-0 flex-1 pr-3 whitespace-pre-wrap wrap-anywhere", text)}>
          <Content line={line} />
        </span>
      </div>
    ) : (
      <div aria-hidden="true" className={empty} />
    );
  return (
    <div>
      {rows.map(([left, right], index) => (
        <div key={index} className="grid grid-cols-2 divide-x divide-zinc-950/[0.07] dark:divide-white/[0.08]">
          {side(left, "old")}
          {side(right, "new")}
        </div>
      ))}
    </div>
  );
}

function Gap({ segment, view, wrap }: { segment: Extract<Segment, { type: "gap" }>; view: DiffView; wrap: boolean }) {
  const [open, setOpen] = useState(false);
  const label = `${segment.count} unchanged ${segment.count === 1 ? "line" : "lines"}`;
  if (open && segment.lines) {
    return (
      <div
        className={cx(
          "grid grid-rows-[1fr] opacity-100 transition-[grid-template-rows,opacity] duration-300 motion-reduce:transition-none",
          ease,
          "starting:grid-rows-[0fr] starting:opacity-0",
        )}
      >
        <div className="min-h-0 overflow-hidden">
          <Lines lines={segment.lines} view={view} wrap={wrap} width={digits(segment.lines)} />
        </div>
      </div>
    );
  }
  const base = "flex h-8 w-full items-center gap-2 border-y border-zinc-950/[0.07] bg-zinc-950/[0.02] px-3 font-sans text-xs text-zinc-500 first:border-t-0 last:border-b-0 dark:border-white/[0.08] dark:bg-white/[0.025]";
  if (!segment.lines) return <div className={base}>{label}</div>;
  return (
    <button
      type="button"
      onClick={() => setOpen(true)}
      className={cx(
        base,
        "group cursor-pointer text-left transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] hover:text-zinc-950 motion-reduce:transition-none",
        "dark:hover:bg-white/[0.06] dark:hover:text-white",
        "focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
      )}
    >
      <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4 shrink-0">
        {segment.edge === "start" ? (
          <path d="M5 6.5 8 3.5l3 3M8 3.5v9" />
        ) : segment.edge === "end" ? (
          <path d="M5 9.5l3 3 3-3M8 12.5v-9" />
        ) : (
          <path d="M5 5.5 8 2.75l3 2.75M5 10.5l3 2.75 3-2.75" />
        )}
      </svg>
      Show {label}
    </button>
  );
}

function Hunk({
  segment,
  view,
  wrap,
  actions,
  decision,
  onDecide,
}: {
  segment: Extract<Segment, { type: "hunk" }>;
  view: DiffView;
  wrap: boolean;
  actions: boolean;
  decision?: HunkDecision;
  onDecide: (decision: HunkDecision | null) => void;
}) {
  const decided = decision !== undefined;
  const changed = segment.lines.filter((line) => line.kind !== "context").length;
  const [, at, rest] = /^(@@[^@]*@@)(.*)$/.exec(segment.header) ?? [null, segment.header, ""];

  return (
    <div data-decision={decision} className="border-t border-zinc-950/[0.07] first:border-t-0 dark:border-white/[0.08]">
      <div className="flex min-h-9 items-center gap-2 px-3 py-1">
        <span className="min-w-0 flex-1 truncate text-zinc-500">
          {at}
          {rest ? <span className="font-sans text-zinc-500"> {rest.trim()}</span> : null}
        </span>
        {actions ? (
          decided ? (
            <span key={decision} className={cx("flex shrink-0 items-center gap-2 font-sans transition-[opacity,translate] duration-200 motion-reduce:transition-none", ease, "starting:translate-y-0.5 starting:opacity-0")}>
              <span className={cx("flex items-center gap-1.5 text-xs font-medium", decision === "accepted" ? "text-emerald-600 dark:text-emerald-400" : "text-zinc-500")}>
                <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4">
                  <circle cx="8" cy="8" r="6.25" />
                  {decision === "accepted" ? <path d="m5.5 8.25 1.75 1.75 3.25-3.75" /> : <path d="m6 6 4 4M10 6l-4 4" />}
                </svg>
                <span>
                  {decision === "accepted" ? "Accepted" : "Rejected"}
                  <span className="font-normal text-zinc-500 tabular-nums max-[400px]:hidden">
                    , {changed} {changed === 1 ? "line" : "lines"}
                  </span>
                </span>
              </span>
              <HunkButton onClick={() => onDecide(null)}>Undo</HunkButton>
            </span>
          ) : (
            <span className="flex shrink-0 items-center gap-1 font-sans">
              <HunkButton onClick={() => onDecide("rejected")} aria-label={`Reject hunk ${segment.header}`}>
                Reject
              </HunkButton>
              <HunkButton primary onClick={() => onDecide("accepted")} aria-label={`Accept hunk ${segment.header}`}>
                <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="-ml-0.5 size-3.5">
                  <path d="m3.75 8.5 2.75 2.75 5.75-6.5" />
                </svg>
                Accept
              </HunkButton>
            </span>
          )
        ) : null}
      </div>
      {/* Deciding folds the hunk away; undo reopens it. */}
      <div
        aria-hidden={decided || undefined}
        className={cx(
          "grid transition-[grid-template-rows,opacity,visibility] motion-reduce:transition-none",
          ease,
          decided ? "invisible grid-rows-[0fr] opacity-0 duration-260" : "visible grid-rows-[1fr] opacity-100 duration-220",
        )}
      >
        <div className="min-h-0 overflow-hidden">
          <Lines lines={segment.lines} view={view} wrap={wrap} width={digits(segment.lines)} />
        </div>
      </div>
    </div>
  );
}

function HunkButton({ primary = false, className, ...props }: ComponentProps<"button"> & { primary?: boolean }) {
  return (
    <button
      type="button"
      className={cx(
        "inline-flex h-6 cursor-pointer items-center gap-1 rounded-md px-2 text-xs font-medium whitespace-nowrap select-none",
        "transition-[background-color,border-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none",
        "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
        primary
          ? "border border-zinc-950/12 bg-white text-zinc-950 hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] dark:border-white/15 dark:bg-black dark:text-white dark:hover:border-white/25 dark:hover:bg-white/[0.06]"
          : "text-zinc-600 hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white",
        className,
      )}
      {...props}
    />
  );
}

/** True while the element is narrower than `px`. Starts false so server and first client render agree. */
function useNarrow(ref: { current: HTMLElement | null }, px: number) {
  const [narrow, setNarrow] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el || typeof ResizeObserver === "undefined") return;
    const observer = new ResizeObserver(([entry]) => entry && setNarrow(entry.contentRect.width < px));
    observer.observe(el);
    return () => observer.disconnect();
  }, [ref, px]);
  return narrow;
}

// ---------------------------------------------------------------------------
// Multi file list

export interface DiffFile {
  /** Stable key. Defaults to the path. */
  id?: string;
  path?: string;
  oldPath?: string;
  oldText?: string;
  newText?: string;
  /** A unified diff for this file. */
  patch?: string;
}

export interface DiffViewerListProps extends Omit<ComponentProps<"div">, "children" | "title"> {
  /** The changed files. Pass either this or `patch`. */
  files?: DiffFile[];
  /** A multi file unified diff, such as the output of `git diff`. */
  patch?: string;
  view?: DiffView;
  defaultView?: DiffView;
  onViewChange?: (view: DiffView) => void;
  context?: number;
  /** Called with the file path when a hunk is accepted, rejected, or undone. Shows hunk actions. */
  onDecisionChange?: (path: string, hunk: number, decision: HunkDecision | null) => void;
  hunkActions?: boolean;
  /** Paths that start collapsed. */
  defaultCollapsed?: string[];
  /** Heading slot, for example a commit message. Defaults to the number of files changed. */
  title?: ReactNode;
}

/** Several files' changes with a summary line and one shared Unified and Split switch. */
export function DiffViewerList({
  files: filesProp,
  patch,
  view: viewProp,
  defaultView = "unified",
  onViewChange,
  context,
  onDecisionChange,
  hunkActions,
  defaultCollapsed = [],
  title,
  className,
  ...props
}: DiffViewerListProps) {
  const files = useMemo<DiffFile[]>(() => {
    if (filesProp) return filesProp;
    if (!patch) return [];
    // Re-split the patch per file so each viewer parses only its own part.
    const chunks = patch.split(/^(?=diff --git )/m).filter((chunk) => chunk.trim());
    return chunks.map((chunk) => ({ patch: chunk }));
  }, [filesProp, patch]);

  const totals = useMemo(() => {
    let additions = 0;
    let deletions = 0;
    for (const file of files) {
      const lines = file.patch != null ? parsePatch(file.patch).flatMap((item) => item.hunks.flatMap((hunk) => hunk.lines)) : diffLines(file.oldText ?? "", file.newText ?? "");
      const counts = countLines(lines);
      additions += counts.additions;
      deletions += counts.deletions;
    }
    return { additions, deletions };
  }, [files]);

  const [localView, setLocalView] = useState<DiffView>(defaultView);
  const view = viewProp ?? localView;
  const ref = useRef<HTMLDivElement>(null);
  const narrow = useNarrow(ref, 560);

  return (
    <div ref={ref} className={cx("flex w-full flex-col gap-3", className)} {...props}>
      <div className="flex min-h-8 items-center gap-3">
        <h3 className="min-w-0 flex-1 truncate text-sm font-medium text-zinc-950 dark:text-white">
          {title ?? `${files.length} ${files.length === 1 ? "file" : "files"} changed`}
        </h3>
        <DiffStat {...totals} />
        {!narrow ? <ViewSwitch value={view} onChange={(next) => (viewProp === undefined ? setLocalView(next) : null, onViewChange?.(next))} /> : null}
      </div>
      {files.map((file, index) => {
        const key = file.id ?? file.path ?? `file-${index}`;
        const resolvedPath = file.path ?? (file.patch ? (parsePatch(file.patch)[0]?.newPath ?? parsePatch(file.patch)[0]?.oldPath) : undefined) ?? key;
        return (
          <DiffViewer
            key={key}
            {...file}
            view={view}
            viewToggle={false}
            context={context}
            hunkActions={hunkActions}
            onDecisionChange={onDecisionChange ? (hunk, decision) => onDecisionChange(resolvedPath, hunk, decision) : undefined}
            defaultCollapsed={defaultCollapsed.includes(resolvedPath)}
          />
        );
      })}
    </div>
  );
}