# Integrate `DiffReview` from Motion Garden

You are helping me add the **DiffReview** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** DiffReview
- **Category:** Power-User Systems
- **Summary:** A review surface for a patch an agent has proposed. Accept or reject each hunk, fold long runs of unchanged lines away, and flip between unified and split. Switching views does not redraw the diff: every line is a shared element that flies from the stream into its column and back, so you never lose the line you were reading.
- **Reference:** https://motion-garden.netlify.app/components/diff-review
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add motion clsx tailwind-merge
```

## Design tokens this source uses

Some classes in the source are Motion Garden theme tokens, not stock Tailwind (`text-ink`, `bg-panel`, `font-display` and the like). Without them, parts of the component render unstyled. Add this to my global CSS, after the Tailwind import:

```css
@theme {
  --font-display: "Space Mono", ui-monospace, "SFMono-Regular", monospace;
}

@theme inline {
  --color-panel: var(--sg-panel);
  --color-raised: var(--sg-raised);
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
  --color-ink-dim: var(--sg-ink-dim);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-panel: #ffffff;
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
}

.dark {
  --sg-panel: #101215;
  --sg-raised: #191d21;
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
  --sg-ink-dim: #bcc2c8;
  --sg-ink-mute: #6c737c;
  --sg-accent: #a855f7;
}
```

The values are Motion Garden's own light and dark themes. If my project already has tokens for these roles, point the `--sg-*` variables at mine instead and tell me which you mapped. `.dark` assumes class-based dark mode — adapt the selector to how my project switches themes.

`font-display` expects Space Mono, and this CSS only names it. Load the font (with `next/font/google`, for example) or put my own display face first in the stack; until then it falls back to the system monospace.

## Files to create

2 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/diff-review/diff-review.tsx`

```tsx
"use client";

import { useEffect, useId, useMemo, useRef, useState } from "react";
import { LayoutGroup, motion, type Transition } from "motion/react";
import { cn } from "@/lib/utils";

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

export interface DiffLine {
  id: string;
  kind: DiffLineKind;
  text: string;
  oldNo?: number;
  newNo?: number;
}

export interface DiffHunk {
  id: string;
  file: string;
  header?: string;
  lines: DiffLine[];
}

export type HunkVerdict = "pending" | "accepted" | "rejected";

export interface DiffReviewProps {
  hunks?: DiffHunk[];
  onAccept?: (hunk: DiffHunk) => void;
  onReject?: (hunk: DiffHunk) => void;
  defaultView?: "unified" | "split";
  morphDuration?: number;
  stiffness?: number;
  damping?: number;
  stagger?: number;
  density?: "comfortable" | "compact";
  showLineNumbers?: boolean;
  contextLines?: number;
  collapseDecided?: boolean;
  addColor?: string;
  delColor?: string;
  accentColor?: string;
  reducedMotion?: boolean;
  className?: string;
}

const ROW = { comfortable: 24, compact: 20 } as const;

const STAGGER_CAP = 12;

const EASE = [0.22, 1, 0.36, 1] as const;

type Segment =
  | { kind: "lines"; key: string; lines: DiffLine[] }
  | { kind: "fold"; key: string; lines: DiffLine[] };

function foldContext(lines: DiffLine[], contextLines: number): Segment[] {
  const out: Segment[] = [];
  const push = (run: DiffLine[]) => {
    if (run.length > 0) out.push({ kind: "lines", key: run[0].id, lines: run });
  };

  let i = 0;
  while (i < lines.length) {
    const start = i;
    const context = lines[i].kind === "context";
    while (i < lines.length && (lines[i].kind === "context") === context) i++;
    const run = lines.slice(start, i);

    if (!context) {
      push(run);
      continue;
    }

    const leading = start === 0 && i < lines.length;
    const trailing = i === lines.length && start > 0;
    const head = leading ? 0 : contextLines;
    const tail = trailing ? 0 : contextLines;
    const hiddenCount = run.length - head - tail;
    if (hiddenCount <= 1) {
      push(run);
      continue;
    }

    push(run.slice(0, head));
    out.push({
      kind: "fold",
      key: `fold:${run[head].id}`,
      lines: run.slice(head, run.length - tail),
    });
    push(run.slice(run.length - tail));
  }
  return out;
}

function pairRows(lines: DiffLine[]) {
  const rows: Array<{ key: string; left: DiffLine | null; right: DiffLine | null }> =
    [];
  let i = 0;
  while (i < lines.length) {
    if (lines[i].kind === "context") {
      rows.push({ key: lines[i].id, left: lines[i], right: lines[i] });
      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++]);
    const span = Math.max(dels.length, adds.length);
    for (let k = 0; k < span; k++) {
      const left = dels[k] ?? null;
      const right = adds[k] ?? null;
      rows.push({ key: (left ?? right)!.id, left, right });
    }
  }
  return rows;
}

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

const SIGN: Record<DiffLineKind, string> = { add: "+", del: "−", context: " " };
const SPOKEN: Record<DiffLineKind, string> = {
  add: "Added, ",
  del: "Removed, ",
  context: "",
};

interface CellProps {
  line: DiffLine | null;
  number: "old" | "new" | "both";
  travels: boolean;
  uid: string;
  compact: boolean;
  showLineNumbers: boolean;
  addColor: string;
  delColor: string;
  spring: Transition;
  reveal: Transition | false;
}

function LineCell({
  line,
  number,
  travels,
  uid,
  compact,
  showLineNumbers,
  addColor,
  delColor,
  spring,
  reveal,
}: CellProps) {
  const height = compact ? ROW.compact : ROW.comfortable;

  if (!line) {
    return (
      <div
        style={{ height }}
        aria-hidden
        className="bg-[repeating-linear-gradient(135deg,var(--sg-hairline)_0px,var(--sg-hairline)_1px,transparent_1px,transparent_6px)] opacity-40"
      />
    );
  }

  const tint = line.kind === "add" ? addColor : line.kind === "del" ? delColor : null;
  const gutter = compact ? "w-8" : "w-10";

  return (
    <div
      className="relative flex items-center"
      style={{ height, backgroundColor: tint ? `${tint}1a` : undefined }}
      aria-hidden={travels ? undefined : true}
      data-line={travels ? line.id : undefined}
    >
      {showLineNumbers ? (
        <span
          className={cn(
            "shrink-0 border-r border-hairline pr-1.5 text-right font-mono tabular-nums text-ink-mute/70 select-none",
            gutter,
            compact ? "text-[10px]" : "text-[11px]",
          )}
        >
          {number === "old"
            ? (line.oldNo ?? "")
            : number === "new"
              ? (line.newNo ?? "")
              : (line.newNo ?? line.oldNo ?? "")}
        </span>
      ) : null}

      <span
        className={cn(
          "shrink-0 px-1.5 text-center font-mono select-none",
          compact ? "text-[11px]" : "text-[12px]",
        )}
        style={{ color: tint ?? "var(--sg-ink-mute)" }}
        aria-hidden
      >
        {SIGN[line.kind]}
      </span>

      {travels ? (
        <span className="sr-only">{SPOKEN[line.kind]}</span>
      ) : null}

      {travels ? (
        <motion.span
          layoutId={`${uid}/${line.id}`}
          initial={reveal ? { opacity: 0, x: -6 } : false}
          animate={{ opacity: 1, x: 0 }}
          transition={reveal ? { ...reveal, layout: spring } : { layout: spring }}
          className={cn(
            "inline-block pr-4 pl-1 font-mono whitespace-pre text-ink",
            compact ? "text-[11px]" : "text-[12px]",
          )}
        >
          {line.text || " "}
        </motion.span>
      ) : (
        <span
          className={cn(
            "inline-block pr-4 pl-1 font-mono whitespace-pre text-ink/70",
            compact ? "text-[11px]" : "text-[12px]",
          )}
        >
          {line.text || " "}
        </span>
      )}
    </div>
  );
}

export default function DiffReview({
  hunks = [],
  onAccept,
  onReject,
  defaultView = "unified",
  morphDuration = 380,
  stiffness = 420,
  damping = 38,
  stagger = 14,
  density = "comfortable",
  showLineNumbers = true,
  contextLines = 3,
  collapseDecided = true,
  addColor = "#4ade80",
  delColor = "#f87171",
  accentColor = "#a855f7",
  reducedMotion = false,
  className,
}: DiffReviewProps) {
  const uid = useId().replace(/:/g, "");
  const [view, setView] = useState<"unified" | "split">(defaultView);
  const [verdicts, setVerdicts] = useState<Record<string, HunkVerdict>>({});
  const [unfolded, setUnfolded] = useState<Record<string, boolean>>({});

  const [lastDefault, setLastDefault] = useState(defaultView);
  if (defaultView !== lastDefault) {
    setLastDefault(defaultView);
    setView(defaultView);
  }

  const seen = useRef(new Set<string>());
  const rootRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    for (const node of root.querySelectorAll<HTMLElement>("[data-line]")) {
      if (node.dataset.line) seen.current.add(node.dataset.line);
    }
  });

  const compact = density === "compact";
  const spring = reducedMotion
    ? ({ duration: 0 } as const)
    : ({ type: "spring", stiffness, damping } as const);
  const ease = reducedMotion
    ? ({ duration: 0 } as const)
    : ({ duration: morphDuration / 1000, ease: EASE } as const);

  const segments = useMemo(
    () =>
      hunks.map((hunk) => ({
        hunk,
        stats: tally(hunk.lines),
        segments: foldContext(hunk.lines, contextLines),
      })),
    [hunks, contextLines],
  );

  const totals = useMemo(() => {
    let add = 0;
    let del = 0;
    for (const entry of segments) {
      add += entry.stats.add;
      del += entry.stats.del;
    }
    return { add, del };
  }, [segments]);

  const decided = hunks.filter((h) => (verdicts[h.id] ?? "pending") !== "pending").length;

  const rule = (hunk: DiffHunk, verdict: HunkVerdict) => {
    setVerdicts((prev) => {
      if ((prev[hunk.id] ?? "pending") === verdict) return prev;
      return { ...prev, [hunk.id]: verdict };
    });
    if (verdict === "accepted") onAccept?.(hunk);
    if (verdict === "rejected") onReject?.(hunk);
  };

  const revealFor = (id: string, index: number): Transition | false => {
    if (reducedMotion || seen.current.has(id)) return false;
    return {
      duration: (morphDuration / 1000) * 0.5,
      delay: (Math.min(index, STAGGER_CAP) * stagger) / 1000,
      ease: EASE,
    };
  };

  return (
    <div
      ref={rootRef}
      className={cn(
        "w-full overflow-hidden rounded-lg border border-hairline bg-panel",
        className,
      )}
    >
      <div className="flex flex-wrap items-center justify-between gap-3 border-b border-hairline px-3 py-2.5">
        <div className="flex items-center gap-3">
          <span className="font-display text-[10px] tracking-[0.24em] text-ink-mute uppercase">
            Proposed patch
          </span>
          <span className="font-mono text-[11px] tabular-nums" style={{ color: addColor }}>
            +{totals.add}
          </span>
          <span className="font-mono text-[11px] tabular-nums" style={{ color: delColor }}>
            &minus;{totals.del}
          </span>
        </div>

        <div className="flex items-center gap-3">
          <span
            className="font-mono text-[11px] tabular-nums"
            style={{ color: decided === hunks.length ? accentColor : "var(--sg-ink-mute)" }}
            aria-live="polite"
          >
            {decided}/{hunks.length} reviewed
          </span>
          <div
            className="flex overflow-hidden rounded-md border border-hairline"
            role="group"
            aria-label="Diff layout"
          >
            {(["unified", "split"] as const).map((mode) => {
              const active = view === mode;
              return (
                <button
                  key={mode}
                  type="button"
                  aria-pressed={active}
                  onClick={() => setView(mode)}
                  className={cn(
                    "px-2.5 py-1 font-display text-[10px] tracking-[0.16em] uppercase transition-colors outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",
                    active ? "text-on-accent" : "text-ink-mute hover:bg-raised hover:text-ink",
                  )}
                  style={active ? { backgroundColor: accentColor } : undefined}
                >
                  {mode}
                </button>
              );
            })}
          </div>
        </div>
      </div>

      <LayoutGroup id={uid}>
        <div className="divide-y divide-hairline">
          {segments.map(({ hunk, stats, segments: parts }) => {
            const verdict = verdicts[hunk.id] ?? "pending";
            const open = !(collapseDecided && verdict !== "pending");
            const edge =
              verdict === "accepted"
                ? addColor
                : verdict === "rejected"
                  ? delColor
                  : null;

            return (
              <section key={hunk.id} aria-label={`${hunk.file} ${hunk.header ?? ""}`}>
                <div
                  className="flex flex-wrap items-center justify-between gap-2 px-3 py-2"
                  style={{
                    borderLeft: `2px solid ${edge ?? "transparent"}`,
                    backgroundColor: edge ? `${edge}0f` : undefined,
                  }}
                >
                  <div className="flex min-w-0 items-baseline gap-2">
                    <span className="truncate font-mono text-[12px] text-ink">
                      {hunk.file}
                    </span>
                    {hunk.header ? (
                      <span className="truncate font-mono text-[11px] text-ink-mute">
                        {hunk.header}
                      </span>
                    ) : null}
                    <span
                      className="font-mono text-[10px] tabular-nums"
                      style={{ color: addColor }}
                    >
                      +{stats.add}
                    </span>
                    <span
                      className="font-mono text-[10px] tabular-nums"
                      style={{ color: delColor }}
                    >
                      &minus;{stats.del}
                    </span>
                  </div>

                  <div className="flex shrink-0 items-center gap-2">
                    {verdict === "pending" ? (
                      <>
                        <button
                          type="button"
                          onClick={() => rule(hunk, "rejected")}
                          className="rounded-md border border-hairline px-2.5 py-1 font-display text-[10px] tracking-[0.16em] text-ink-dim uppercase transition-colors outline-none hover:bg-raised hover:text-ink focus-visible:ring-2 focus-visible:ring-accent"
                        >
                          Reject
                        </button>
                        <button
                          type="button"
                          onClick={() => rule(hunk, "accepted")}
                          className="rounded-md px-2.5 py-1 font-display text-[10px] tracking-[0.16em] text-on-accent uppercase transition-opacity outline-none hover:opacity-90 focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-panel"
                          style={{ backgroundColor: accentColor }}
                        >
                          Accept
                        </button>
                      </>
                    ) : (
                      <>
                        <span
                          className="font-display text-[10px] tracking-[0.16em] uppercase"
                          style={{ color: edge ?? undefined }}
                        >
                          {verdict}
                        </span>
                        <button
                          type="button"
                          onClick={() => rule(hunk, "pending")}
                          className="rounded-md border border-hairline px-2.5 py-1 font-display text-[10px] tracking-[0.16em] text-ink-dim uppercase transition-colors outline-none hover:bg-raised hover:text-ink focus-visible:ring-2 focus-visible:ring-accent"
                        >
                          Undo
                        </button>
                      </>
                    )}
                  </div>
                </div>

                <motion.div
                  initial={false}
                  animate={{ height: open ? "auto" : 0, opacity: open ? 1 : 0 }}
                  transition={ease}
                  className="overflow-hidden"
                  inert={!open}
                >
                  {view === "unified" ? (
                    <div className="overflow-x-auto">
                      <div className="w-max min-w-full">
                        {parts.map((part) =>
                          part.kind === "fold" && !unfolded[part.key] ? (
                            <FoldRow
                              key={part.key}
                              count={part.lines.length}
                              compact={compact}
                              accentColor={accentColor}
                              onExpand={() =>
                                setUnfolded((prev) => ({ ...prev, [part.key]: true }))
                              }
                            />
                          ) : (
                            part.lines.map((line, i) => (
                              <LineCell
                                key={line.id}
                                line={line}
                                number="both"
                                travels
                                uid={uid}
                                compact={compact}
                                showLineNumbers={showLineNumbers}
                                addColor={addColor}
                                delColor={delColor}
                                spring={spring}
                                reveal={revealFor(line.id, i)}
                              />
                            ))
                          ),
                        )}
                      </div>
                    </div>
                  ) : (
                    <div className="grid grid-cols-2 divide-x divide-hairline">
                      {(["old", "new"] as const).map((side) => (
                        <div key={side} className="min-w-0 overflow-x-auto">
                          <div className="w-max min-w-full">
                            {parts.map((part) => {
                              if (part.kind === "fold" && !unfolded[part.key]) {
                                return (
                                  <FoldRow
                                    key={part.key}
                                    count={part.lines.length}
                                    compact={compact}
                                    accentColor={accentColor}
                                    onExpand={
                                      side === "old"
                                        ? () =>
                                            setUnfolded((prev) => ({
                                              ...prev,
                                              [part.key]: true,
                                            }))
                                        : undefined
                                    }
                                  />
                                );
                              }
                              return pairRows(part.lines).map((row, i) => {
                                const line = side === "old" ? row.left : row.right;
                                const travels =
                                  line !== null &&
                                  (line.kind !== "context" || side === "old");
                                return (
                                  <LineCell
                                    key={`${side}:${row.key}`}
                                    line={line}
                                    number={side}
                                    travels={travels}
                                    uid={uid}
                                    compact={compact}
                                    showLineNumbers={showLineNumbers}
                                    addColor={addColor}
                                    delColor={delColor}
                                    spring={spring}
                                    reveal={
                                      line && travels ? revealFor(line.id, i) : false
                                    }
                                  />
                                );
                              });
                            })}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </motion.div>
              </section>
            );
          })}
        </div>
      </LayoutGroup>
    </div>
  );
}

function FoldRow({
  count,
  compact,
  accentColor,
  onExpand,
}: {
  count: number;
  compact: boolean;
  accentColor: string;
  onExpand?: () => void;
}) {
  const height = compact ? ROW.compact : ROW.comfortable;
  const label = `Show ${count} unchanged line${count === 1 ? "" : "s"}`;

  if (!onExpand) {
    return (
      <div
        style={{ height }}
        aria-hidden
        className="flex items-center bg-raised/40 px-3 font-mono text-[11px] text-ink-mute/60 select-none"
      >
        {"⋯"}
      </div>
    );
  }

  return (
    <button
      type="button"
      onClick={onExpand}
      style={{ height, color: accentColor }}
      className="flex w-full items-center gap-2 bg-raised/40 px-3 font-mono text-[11px] transition-colors outline-none hover:bg-raised focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset"
    >
      <span aria-hidden>{"⋯"}</span>
      {label}
    </button>
  );
}
```

### 2. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `defaultView` | `"unified" | "split"` | `"unified"` | Starting layout. One interleaved stream, or the old file beside the new one. The toolbar toggle overrides it live. |
| `morphDuration` | `number` | `380` | Hunk fold, verdict change and the first reveal of a line. The flight between views is a spring and ignores this — stiffness and damping own that one. Range 120–1200 ms. |
| `stiffness` | `number` | `420` | How hard a line is pulled toward its slot in the other view. Range 80–800. |
| `damping` | `number` | `38` | How fast that flight settles. Low values let a line overshoot its column before landing. Range 8–80. |
| `stagger` | `number` | `14` | Delay added per line as a hunk first appears. Capped at twelve lines in, so expanding a long fold never leaves the last row waiting in plain sight. Range 0–80 ms. |
| `density` | `"comfortable" | "compact"` | `"comfortable"` | Row height and type size throughout. |
| `showLineNumbers` | `boolean` | `true` | Old and new line numbers in the gutter. Split view shows one per side; unified shows the surviving number. |
| `contextLines` | `number` | `3` | Unchanged lines kept on the side of a run that faces a change. The rest fold behind an expander — except a fold that would hide a single line, which costs a row to save a row. Range 0–10. |
| `collapseDecided` | `boolean` | `true` | Fold a hunk's body away once it has a verdict, leaving the header and an Undo. Off keeps every hunk open so you can re-read what you just ruled on. |
| `addColor` | `string (hex)` | `"#4ade80"` | Added lines, their gutter sign, and an accepted hunk's edge. |
| `delColor` | `string (hex)` | `"#f87171"` | Removed lines, their gutter sign, and a rejected hunk's edge. |
| `accentColor` | `string (hex)` | `"#a855f7"` | Active view toggle, fold expanders, focus rings and the reviewed counter once every hunk has been ruled on. |

## Usage

```tsx
import DiffReview from "@/components/registry/diff-review/diff-review";

<DiffReview
  defaultView="unified"
  morphDuration={380}
  stiffness={420}
  damping={38}
  stagger={14}
  density="comfortable"
  showLineNumbers={true}
  contextLines={3}
  collapseDecided={true}
  addColor="#4ade80"
  delColor="#f87171"
  accentColor="#a855f7"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Add the design tokens to my global CSS, or map them to tokens I already have.
4. Wire the component into the place I point you at, with sensible props for that context.
5. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
