For the complete documentation index, see llms.txt. Markdown variants are available by appending .md to any URL or sending an Accept: text/markdown header. An agent skill is available at /.well-known/agent-skills/site-skill.md.
18

Diff

Unified or before/after text diff with line numbers, word-level highlights, and +/- stats.

src/auth/session.ts+11−5
@@ -12,8 +12,13 @@ export interface Session {  userId: string;  createdAt: number;+  /** When the session stops being accepted, in ms since the epoch. */+  expiresAt: number;} -export const createSession = (userId: string): Session => ({-  userId,-  createdAt: Date.now(),-});+const TTL = 1000 * 60 * 60 * 24 * 7;+ +export const createSession = (userId: string, now = Date.now()): Session => ({+  userId,+  createdAt: now,+  expiresAt: now + TTL,+});@@ -31,3 +36,4 @@ export const readSession = (token: string) => {  const session = store.get(token);-  return session ?? null;+  if (!session || session.expiresAt < Date.now()) return null;+  return session;};
"use client";

import {

Installation

$ pnpm dlx shadcn@latest add https://motif.sweetretry.com/r/diff.json

Usage

import {
  Diff,
  DiffContent,
  DiffFile,
  DiffHeader,
  DiffStat,
} from "@/components/ui/motif/diff";
 
export function FileChange({ patch }) {
  return (
    <Diff patch={patch}>
      <DiffHeader>
        <DiffFile />
        <DiffStat />
      </DiffHeader>
      <DiffContent />
    </Diff>
  );
}
PartRole
DiffRoot frame accepting either patch or before/after
DiffHeaderOptional header row; renders nothing when empty
DiffFileDisplays path from patch +++ header or file prop
DiffStatDisplays +N −M counts, omitting zero sides
DiffContentRenders diff lines with gutter numbers, markers, and inline word highlights
useDiffReturns parsed lines, counts, and path for custom subcomponents
parsePatchStandalone patch parser returning lines, counts, and path
compareTextsStandalone before/after diff helper using jsdiff

Inputs

Pass either patch or before/after, never both.

<Diff patch={call.patch}>…</Diff>
 
<Diff before={call.old_string} after={call.new_string} firstLine={call.line}>
  …
</Diff>
  • firstLine sets the starting line number for before/after diffs (pass 1 for full files; omit to hide the gutter). Unchanged stretches over 3 lines fold into a marker row.
  • patch accepts full git diff headers (diff --git, index, ---/+++, @@) or bare +/-/space lines; \ No newline at end of file is stripped.
  • Gutter +/- markers are non-selectable so copied text contains only code.

Word Highlights & Composition

Paired removal/addition lines sharing at least 50% of their text highlight changed words at a stronger tint.

README.md+1−1
## Install -Run the command below in the root of your project and the component will be copied into your components folder.+Run the command below in the root of your app and the component will be copied into `components/ui`. Every component is yours to edit after it is installed.
"use client";

import {

Inside a Tool Call row that already names the file, render <DiffContent /> alone:

doneedit_filecomponents/thread.tsx
"use client";

import {
<ToolCallContent>
  <Diff after={call.new_string} before={call.old_string}>
    <DiffContent />
  </Diff>
</ToolCallContent>

For a file summary list, render <DiffHeader /> without <DiffContent />:

src/auth/session.ts+11−5
components/thread.tsx+4−1
"use client";

import {

Styling & Accessibility

  • Uses success and destructive tokens (10% line tint, 25% word highlight); installing adds success CSS variables to :root, .dark, and @theme.
  • Renders inside <pre> with +/- markers exposed to screen readers, line numbers hidden, and DiffStat labeled "N added, M removed".

Component source

index.tsx
"use client";

import { createContext, useContext, useMemo } from "react";
import type { ComponentProps, CSSProperties } from "react";

import { cn } from "@/lib/utils";

import { compareTexts, parsePatch } from "./read";
import type { DiffState } from "./read";

/* -- One file's change ---------------------------------------------------------
 * A diff is what an edit amounts to, and the reader reads it to decide whether to let
 * it stand. So it is drawn the way a reviewer reads one: what went in, in `success`;
 * what came out, in `destructive`; the lines around them as they were.
 *
 * The root takes the change in either of the two shapes agent tools hand it over in:
 * a patch, the unified text `git diff` writes, or the text before and after, the
 * `old_string` and `new_string` of an edit tool. Either is read once into the same
 * lines. The parts read those lines and know nothing of each other: a tool row that
 * already names the file draws the lines alone, a list of changed files draws the
 * header alone, and a review pane draws both.
 *
 * A file header (`--- a/...`, `+++ b/...`) is read for the path and is not drawn as a
 * removal and an addition, which is what it looks like to anything counting first
 * characters. Lines are numbered only when the input says where they are: a hunk header
 * with numbers, or `firstLine` beside a before and after. A snippet's own count is not
 * the file's, and no gutter is better than a column of wrong numbers.
 *
 * A line that was edited rather than replaced, a removal and an addition that share
 * most of their text, also marks the words that changed. Prose is where this earns its
 * keep: a paragraph is one line, and without it a single changed word turns the whole
 * paragraph red and then green.
 * --------------------------------------------------------------------------- */

export { compareTexts, parsePatch } from "./read";
export type { DiffLine, DiffLineKind, DiffSegment, DiffState } from "./read";

export type DiffSource =
  | {
      after?: never;
      before?: never;
      firstLine?: never;
      /** Unified diff text. A bare run of `+`, `-` and ` ` lines is enough. */
      patch: string;
    }
  | {
      /** The text after the change. */
      after: string;
      /** The text before the change. */
      before: string;
      /** The line `before` starts at in its file. Without it the lines are not
       *  numbered. Pass `1` when `before` is the whole file. */
      firstLine?: number;
      patch?: never;
    };

export type DiffProps = ComponentProps<"div"> &
  DiffSource & {
    /** The path to show. Defaults to the one in the patch's `+++` line. */
    file?: string;
  };

export type DiffHeaderProps = ComponentProps<"div">;
export type DiffFileProps = ComponentProps<"span">;
export type DiffStatProps = Omit<ComponentProps<"span">, "children">;
export type DiffContentProps = Omit<ComponentProps<"pre">, "children">;

const DiffContext = createContext<DiffState | null>(null);

export const useDiff = () => {
  const context = useContext(DiffContext);
  if (!context) {
    throw new Error("Diff parts must be used within a Diff.");
  }

  return context;
};

/** The frame. A recessed block inside whatever holds it, so it draws a border and no
 *  fill: a fill reads as sunk in one theme and raised in the other. */
export const Diff = ({
  after,
  before,
  className,
  file,
  firstLine,
  patch,
  ...props
}: DiffProps) => {
  const read = useMemo(
    () =>
      patch === undefined
        ? compareTexts(before ?? "", after ?? "", firstLine)
        : parsePatch(patch),
    [after, before, firstLine, patch]
  );
  const value = useMemo(
    () => ({ ...read, file: file ?? read.file }),
    [read, file]
  );

  return (
    <DiffContext.Provider value={value}>
      <div
        className={cn(
          "flex flex-col overflow-hidden rounded-md border border-border",
          className
        )}
        data-slot="diff"
        {...props}
      />
    </DiffContext.Provider>
  );
};

/** The row above the lines. Draws nothing while it holds nothing. */
export const DiffHeader = ({ className, ...props }: DiffHeaderProps) => (
  <div
    className={cn(
      "flex min-w-0 items-center gap-2 border-b border-border px-3 py-1.5 text-xs empty:hidden",
      className
    )}
    data-slot="diff-header"
    {...props}
  />
);

/** The path. Children replace it; with neither a path nor children, nothing is drawn. */
export const DiffFile = ({ children, className, ...props }: DiffFileProps) => {
  const { file } = useDiff();
  const shown = children ?? file;

  if (!shown) {
    return null;
  }

  return (
    <span
      className={cn("min-w-0 flex-1 truncate font-mono", className)}
      data-slot="diff-file"
      title={typeof shown === "string" ? shown : undefined}
      {...props}
    >
      {shown}
    </span>
  );
};

/** `+4 −1`. A side with nothing on it is left out, so a pure addition says only `+4`. */
export const DiffStat = ({ className, ...props }: DiffStatProps) => {
  const { added, removed } = useDiff();

  if (!(added || removed)) {
    return null;
  }

  return (
    <span
      aria-label={`${added} added, ${removed} removed`}
      className={cn("flex shrink-0 gap-1.5 font-mono tabular-nums", className)}
      data-slot="diff-stat"
      {...props}
    >
      {added ? <span className="text-success">+{added}</span> : null}
      {removed ? <span className="text-destructive">−{removed}</span> : null}
    </span>
  );
};

/**
 * The lines. Each is a row of three: its number, its marker, its text. The marker is
 * not selectable, so what a reader copies out of an added line is the line. The words
 * an edited line changed sit on a stronger tint of the line's own colour. Long lines
 * wrap rather than scroll sideways: in a chat column a horizontal scroll hides the end
 * of every line at once.
 */
export const DiffContent = ({
  className,
  style,
  ...props
}: DiffContentProps) => {
  const { lines } = useDiff();
  let widest = 0;
  for (const line of lines) {
    widest = Math.max(widest, line.number ?? 0);
  }
  const gutter = widest ? `${String(widest).length}ch` : "0px";

  if (lines.length === 0) {
    return null;
  }

  return (
    <pre
      className={cn(
        "max-h-64 overflow-auto py-2 font-mono text-xs leading-normal",
        className
      )}
      data-slot="diff-content"
      style={{ "--diff-gutter": gutter, ...style } as CSSProperties}
      {...props}
    >
      {lines.map((line, index) => (
        <span
          className={cn(
            "grid grid-cols-[var(--diff-gutter)_1ch_minmax(0,1fr)] gap-x-2 px-3",
            line.kind === "added" && "bg-success/10 text-success",
            line.kind === "removed" && "bg-destructive/10 text-destructive",
            line.kind === "hunk" && "text-muted-foreground"
          )}
          data-kind={line.kind}
          // Lines of a patch repeat, and they never move: the index is their identity.
          // oxlint-disable-next-line react/no-array-index-key
          key={index}
        >
          <span
            aria-hidden
            className="text-right text-muted-foreground/70 select-none"
          >
            {line.kind === "hunk" ? null : line.number}
          </span>
          <span aria-hidden={line.kind === "hunk"} className="select-none">
            {line.kind === "added" ? "+" : null}
            {line.kind === "removed" ? "-" : null}
          </span>
          <span className="break-words whitespace-pre-wrap">
            {line.segments
              ? line.segments.map((segment, at) => (
                  <span
                    className={cn(
                      segment.changed && "rounded-[2px]",
                      segment.changed &&
                        line.kind === "added" &&
                        "bg-success/25",
                      segment.changed &&
                        line.kind === "removed" &&
                        "bg-destructive/25"
                    )}
                    data-changed={segment.changed || undefined}
                    // A line's segments are fixed once it is read.
                    // oxlint-disable-next-line react/no-array-index-key
                    key={at}
                  >
                    {segment.text}
                  </span>
                ))
              : line.text || " "}
          </span>
        </span>
      ))}
    </pre>
  );
};
read.ts
import { diffWordsWithSpace, structuredPatch } from "diff";

export type DiffLineKind = "added" | "context" | "hunk" | "removed";

/** A run of a line's text, and whether it is the part that changed. */
export interface DiffSegment {
  changed: boolean;
  text: string;
}

export interface DiffLine {
  kind: DiffLineKind;
  /** The line's number in the file it now belongs to: the new file for an added or
   *  unchanged line, the old one for a removed line. Absent when the input does not
   *  say where the lines are. */
  number?: number;
  /** The line split where its words changed. Absent on a line that was not edited
   *  in place, which is drawn whole. */
  segments?: DiffSegment[];
  /** The line without its marker, so a copied selection is code, not patch. */
  text: string;
}

/** What a part reads from the root. Exported with `useDiff` so a caller can draw a part
 *  of their own, an "apply" button that only shows on a small change, from the same
 *  counts the shipped parts use. */
export interface DiffState {
  added: number;
  /** The path the patch names, or the one passed to the root. */
  file?: string;
  lines: DiffLine[];
  removed: number;
}

const HUNK = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
/** Lines `git diff` writes before the first hunk, none of which are the change. */
const META =
  /^(diff |index |--- |\+\+\+ |new file|deleted file|similarity |rename |old mode|new mode)/;
/** How much of a pair of lines has to survive for it to read as one line edited. Below
 *  it, marking the changed words would mark nearly all of them. */
const SAME_ENOUGH = 0.5;
/** Unchanged lines kept around each change when the root works the diff out itself. */
const CONTEXT = 3;

/** The path a `---` or `+++` line names. `/dev/null`, the side of a new or deleted
 *  file that does not exist, names none. */
const pathOf = (header: string) => {
  const [path] = header.slice(4).split("\t");
  const trimmed = path.trim();

  return trimmed === "/dev/null" ? null : trimmed.replace(/^[ab]\//, "");
};

const next = (line: number | undefined) =>
  line === undefined ? undefined : line + 1;

/** Marks the changed words of one removed line and the added line that replaced it,
 *  when they share enough to be one line edited. */
const markWords = (before: DiffLine, after: DiffLine) => {
  const parts = diffWordsWithSpace(before.text, after.text);
  let same = 0;
  for (const part of parts) {
    if (!(part.added || part.removed)) {
      same += part.value.length;
    }
  }

  const longest = Math.max(before.text.length, after.text.length, 1);
  if (same / longest < SAME_ENOUGH) {
    return;
  }

  before.segments = parts
    .filter((part) => !part.added)
    .map((part) => ({ changed: part.removed, text: part.value }));
  after.segments = parts
    .filter((part) => !part.removed)
    .map((part) => ({ changed: part.added, text: part.value }));
};

/** Pairs each run of removals with the run of additions right after it, line by line in
 *  order, the way a reviewer lines them up, and marks the words of each pair. */
const pairWords = (lines: DiffLine[]) => {
  let at = 0;
  while (at < lines.length) {
    if (lines[at].kind !== "removed") {
      at += 1;
      continue;
    }

    let added = at;
    while (added < lines.length && lines[added].kind === "removed") {
      added += 1;
    }
    let end = added;
    while (end < lines.length && lines[end].kind === "added") {
      end += 1;
    }

    const pairs = Math.min(added - at, end - added);
    for (let index = 0; index < pairs; index += 1) {
      markWords(lines[at + index], lines[added + index]);
    }
    at = end;
  }
};

/** Reads the body of a patch, one row at a time, into lines and counts. Both inputs end
 *  up here, so a patch and a before and after with the same change draw the same. */
const createReader = () => {
  const lines: DiffLine[] = [];
  let added = 0;
  let removed = 0;
  let oldLine: number | undefined;
  let newLine: number | undefined;

  return {
    done: () => {
      pairWords(lines);
      return { added, lines, removed };
    },
    /** Starts a hunk. `text` is the row to draw for it, `null` for none. */
    hunk: (text: string | null, oldStart?: number, newStart?: number) => {
      oldLine = oldStart;
      newLine = newStart;
      if (text !== null) {
        lines.push({ kind: "hunk", text });
      }
    },
    row: (row: string) => {
      if (row.startsWith("\\")) {
        // "\ No newline at end of file" is about the bytes, not the code.
        return;
      }

      const [marker] = row;
      if (marker === "+") {
        added += 1;
        lines.push({ kind: "added", number: newLine, text: row.slice(1) });
        newLine = next(newLine);
      } else if (marker === "-") {
        removed += 1;
        lines.push({ kind: "removed", number: oldLine, text: row.slice(1) });
        oldLine = next(oldLine);
      } else {
        lines.push({
          kind: "context",
          number: newLine,
          text: marker === " " ? row.slice(1) : row,
        });
        oldLine = next(oldLine);
        newLine = next(newLine);
      }
    },
  };
};

/** Reads unified diff text into lines and counts. Exported for a caller that needs the
 *  numbers without the drawing, a file list that sums several patches. */
export const parsePatch = (patch: string): DiffState => {
  const reader = createReader();
  let file: string | null = null;
  let fromFile: string | null = null;
  let inBody = false;

  const rows = patch.split("\n");
  if (rows.at(-1) === "") {
    rows.pop();
  }

  for (const row of rows) {
    if (!inBody && META.test(row)) {
      if (row.startsWith("+++ ")) {
        file = pathOf(row);
      } else if (row.startsWith("--- ")) {
        fromFile = pathOf(row);
      }
      continue;
    }

    inBody = true;
    if (row.startsWith("@@")) {
      const numbers = HUNK.exec(row);
      reader.hunk(
        row,
        numbers ? Number(numbers[1]) : undefined,
        numbers ? Number(numbers[2]) : undefined
      );
    } else {
      reader.row(row);
    }
  }

  return { ...reader.done(), file: file ?? fromFile ?? undefined };
};

/** Works out the change from the text before and after it, into the same lines a patch
 *  reads into. Unchanged stretches longer than a few lines fold to a marker row, so a
 *  one-line edit in a long file is a few lines to read. Exported beside `parsePatch`. */
export const compareTexts = (
  before: string,
  after: string,
  firstLine?: number
): DiffState => {
  const reader = createReader();
  const { hunks } = structuredPatch(
    "",
    "",
    before,
    after,
    undefined,
    undefined,
    {
      context: CONTEXT,
    }
  );
  const shift = firstLine === undefined ? undefined : firstLine - 1;

  for (const [index, hunk] of hunks.entries()) {
    const oldStart = shift === undefined ? undefined : hunk.oldStart + shift;
    const newStart = shift === undefined ? undefined : hunk.newStart + shift;
    // A marker row says lines were left out. Above a first hunk that starts at the top,
    // nothing was.
    const folded = index > 0 || hunk.oldStart > 1;
    let text: string | null = null;
    if (folded) {
      text =
        oldStart === undefined
          ? "\u22EF"
          : `@@ -${oldStart},${hunk.oldLines} +${newStart},${hunk.newLines} @@`;
    }

    reader.hunk(text, oldStart, newStart);
    for (const row of hunk.lines) {
      reader.row(row);
    }
  }

  return reader.done();
};