# Animated Diff Viewer for UI SDK (/docs/components/diff-viewer)

Review the changes an agent proposes to a file: a line diff computed in-house (or read from a patch), unified or side by side, changed words marked, long unchanged runs folded, and Accept or Reject on every hunk.

<ComponentPreview slug="diff-viewer" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport * as React from \&#x22;react\&#x22;\n\nimport {\n  DiffViewer,\n  DiffViewerActions,\n  DiffViewerContent,\n  DiffViewerCopyButton,\n  DiffViewerHeader,\n  DiffViewerStats,\n  DiffViewerTitle,\n  DiffViewerViewSwitch,\n} from \&#x22;@/components/keyframery/diff-viewer\&#x22;\n\nconst before = `import type { Request } from \&#x22;./http\&#x22;\nimport { redis } from \&#x22;./redis\&#x22;\n\n/** Requests allowed per window, by plan. */\nconst LIMITS = {\n  free: 60,\n  pro: 600,\n  team: 3000,\n} as const\n\ntype Plan = keyof typeof LIMITS\n\nexport type RateLimitResult = {\n  ok: boolean\n  remaining: number\n}\n\nfunction keyFor(req: Request) {\n  return \\`ratelimit:\\${req.user?.id ?? req.ip}\\`\n}\n\n/** The caller's plan. Signed-out traffic counts as free. */\nexport function planFor(req: Request): Plan {\n  const plan = req.user?.plan\n  if (plan === \&#x22;pro\&#x22; || plan === \&#x22;team\&#x22;) return plan\n  return \&#x22;free\&#x22;\n}\n\nexport function isOverLimit(result: RateLimitResult) {\n  return !result.ok\n}\n\n/**\n * Counts this request against the caller's window.\n * Windows are fixed: they reset on the minute.\n */\nexport async function rateLimit(req: Request, plan: Plan): Promise<RateLimitResult> {\n  const key = keyFor(req)\n  const limit = LIMITS[plan]\n  const count = await redis.incr(key)\n  if (count === 1) await redis.expire(key, 60)\n  return { ok: count <= limit, remaining: limit - count }\n}\n\nexport function headers(result: RateLimitResult) {\n  return {\n    \&#x22;X-RateLimit-Remaining\&#x22;: String(result.remaining),\n  }\n}\n\nexport function isExempt(req: Request) {\n  return req.headers.get(\&#x22;x-internal-token\&#x22;) === process.env.INTERNAL_TOKEN\n}\n\nexport async function reset(req: Request) {\n  await redis.del(keyFor(req))\n}\n\nexport function describe(plan: Plan) {\n  return \\`\\${LIMITS[plan]} requests per minute\\`\n}\n\nexport function remainingLabel(result: RateLimitResult) {\n  if (result.remaining <= 0) return \&#x22;Limit reached\&#x22;\n  return \\`\\${result.remaining} left\\`\n}\n`\n\nconst after = `import type { Request } from \&#x22;./http\&#x22;\nimport { redis } from \&#x22;./redis\&#x22;\n\n/** Requests allowed per window, by plan. */\nconst LIMITS = {\n  free: 60,\n  pro: 600,\n  team: 3000,\n} as const\n\ntype Plan = keyof typeof LIMITS\n\nconst WINDOW_MS = 60_000\n\nexport type RateLimitResult = {\n  ok: boolean\n  remaining: number\n  retryAfter: number\n}\n\nfunction keyFor(req: Request) {\n  return \\`ratelimit:\\${req.user?.id ?? req.ip}\\`\n}\n\n/** The caller's plan. Signed-out traffic counts as free. */\nexport function planFor(req: Request): Plan {\n  const plan = req.user?.plan\n  if (plan === \&#x22;pro\&#x22; || plan === \&#x22;team\&#x22;) return plan\n  return \&#x22;free\&#x22;\n}\n\nexport function isOverLimit(result: RateLimitResult) {\n  return !result.ok\n}\n\n/**\n * Counts this request against the caller's window.\n * The window slides: it covers the last 60 seconds, not the clock minute.\n */\nexport async function rateLimit(req: Request, plan: Plan): Promise<RateLimitResult> {\n  const key = keyFor(req)\n  const limit = LIMITS[plan]\n  const now = Date.now()\n  await redis.zremrangebyscore(key, 0, now - WINDOW_MS)\n  const count = (await redis.zcard(key)) + 1\n  if (count <= limit) await redis.zadd(key, now, \\`\\${now}:\\${crypto.randomUUID()}\\`)\n  await redis.pexpire(key, WINDOW_MS)\n  const oldest = Number((await redis.zrange(key, 0, 0, \&#x22;WITHSCORES\&#x22;))[1] ?? now)\n  return { ok: count <= limit, remaining: Math.max(0, limit - count), retryAfter: Math.ceil((oldest + WINDOW_MS - now) / 1000) }\n}\n\nexport function headers(result: RateLimitResult) {\n  return {\n    \&#x22;X-RateLimit-Remaining\&#x22;: String(result.remaining),\n    ...(result.ok ? {} : { \&#x22;Retry-After\&#x22;: String(result.retryAfter) }),\n  }\n}\n\nexport function isExempt(req: Request) {\n  return req.headers.get(\&#x22;x-internal-token\&#x22;) === process.env.INTERNAL_TOKEN\n}\n\nexport async function reset(req: Request) {\n  await redis.del(keyFor(req))\n}\n\nexport function describe(plan: Plan) {\n  return \\`\\${LIMITS[plan]} requests per minute\\`\n}\n\nexport function remainingLabel(result: RateLimitResult) {\n  if (result.ok) return \\`\\${result.remaining} left\\`\n  return \\`Limit reached, try again in \\${result.retryAfter}s\\`\n}\n`\n\nexport default function DiffViewerDemo({\n  view = \&#x22;unified\&#x22;,\n  review = true,\n  wordDiff = true,\n  lineNumbers = true,\n  context = 3,\n  themeAdded = \&#x22;\&#x22;,\n  themeRemoved = \&#x22;\&#x22;,\n  themeFace = \&#x22;\&#x22;,\n  themeRadius = 14,\n  themeFont = 12.5,\n  themeMaxHeight = 420,\n}: {\n  view?: \&#x22;unified\&#x22; | \&#x22;split\&#x22;\n  review?: boolean\n  wordDiff?: boolean\n  lineNumbers?: boolean\n  context?: number\n  themeAdded?: string\n  themeRemoved?: string\n  themeFace?: string\n  themeRadius?: number\n  themeFont?: number\n  themeMaxHeight?: number\n}) {\n  /* Restarting the review mounts a fresh viewer: folds closed, decisions cleared. */\n  const [run, setRun] = React.useState(0)\n  const [shown, setShown] = React.useState(view)\n  const [decided, setDecided] = React.useState(0)\n  React.useEffect(() => setShown(view), [view])\n\n  const theme = {\n    ...(themeAdded ? { \&#x22;--diff-viewer-added\&#x22;: themeAdded } : null),\n    ...(themeRemoved ? { \&#x22;--diff-viewer-removed\&#x22;: themeRemoved } : null),\n    ...(themeFace ? { \&#x22;--diff-viewer-face\&#x22;: themeFace } : null),\n    ...(themeRadius !== 14 ? { \&#x22;--diff-viewer-radius\&#x22;: `${themeRadius}px` } : null),\n    ...(themeFont !== 12.5 ? { \&#x22;--diff-viewer-font\&#x22;: `${themeFont}px` } : null),\n    \&#x22;--diff-viewer-max-height\&#x22;: `${themeMaxHeight}px`,\n  } as React.CSSProperties\n\n  const count = () => setDecided((n) => n + 1)\n\n  return (\n    <div style={theme} className=\&#x22;w-full max-w-[860px]\&#x22;>\n      <div className=\&#x22;mb-3 flex items-end justify-between gap-3 px-0.5\&#x22;>\n        <div className=\&#x22;min-w-0\&#x22;>\n          <div className=\&#x22;text-[15px] font-semibold tracking-tight\&#x22;>Use a sliding window for rate limits</div>\n          <p className=\&#x22;mt-1 text-[12px] text-muted-foreground\&#x22;>\n            Proposed by the agent · {decided === 0 ? \&#x22;awaiting review\&#x22; : `${decided} of 3 reviewed`}\n          </p>\n        </div>\n        <button\n          type=\&#x22;button\&#x22;\n          data-action=\&#x22;restart\&#x22;\n          onClick={() => {\n            setRun((n) => n + 1)\n            setDecided(0)\n            setShown(view)\n          }}\n          className=\&#x22;h-7 shrink-0 cursor-pointer rounded-[8px] px-2.5 text-[12px] leading-none font-medium text-muted-foreground outline-none transition-colors duration-[calc(150ms*var(--kf-speed,1))] hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none\&#x22;\n        >\n          Start over\n        </button>\n      </div>\n\n      <DiffViewer\n        key={run}\n        before={before}\n        after={after}\n        filename=\&#x22;src/lib/rate-limit.ts\&#x22;\n        view={shown}\n        onViewChange={setShown}\n        review={review}\n        wordDiff={wordDiff}\n        lineNumbers={lineNumbers}\n        context={context}\n        onAccept={count}\n        onReject={count}\n        onUndo={() => setDecided((n) => Math.max(0, n - 1))}\n      >\n        <DiffViewerHeader>\n          <DiffViewerTitle />\n          <DiffViewerStats />\n          <DiffViewerActions>\n            <DiffViewerViewSwitch />\n            <DiffViewerCopyButton />\n          </DiffViewerActions>\n        </DiffViewerHeader>\n        <DiffViewerContent />\n      </DiffViewer>\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;view&#x22;:[4074,4083],&#x22;review&#x22;:[4096,4100],&#x22;wordDiff&#x22;:[4115,4119],&#x22;lineNumbers&#x22;:[4137,4141],&#x22;context&#x22;:[4155,4156],&#x22;themeAdded&#x22;:[4173,4175],&#x22;themeRemoved&#x22;:[4194,4196],&#x22;themeFace&#x22;:[4212,4214],&#x22;themeRadius&#x22;:[4232,4234],&#x22;themeFont&#x22;:[4250,4254],&#x22;themeMaxHeight&#x22;:[4275,4278]},&#x22;root&#x22;:[5346,7127],&#x22;importOffset&#x22;:261}" />

## Installation [#installation]

**React**

**CLI**

```bash
npx shadcn@latest add @keyframery/diff-viewer
```

This adds `components/keyframery/diff-viewer.tsx` and its primitive to your project, and installs UI SDK, along with [code-block](/docs/components/code-block), which it builds on. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.17 @ui-sdk/react@0.1.0-beta.17 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation/manual#add-the-motion-tokens) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "subtle" | "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"subtle"` (the default), `"calm"`, `"springy"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Add what it builds on**

Install [code-block](/docs/components/code-block) the same way first.

**Copy the component**

**components/keyframery/diff-viewer.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/diff-viewer"

/* Theming variables (set on a part or ancestor; absent values preserve the theme):
   --diff-viewer-face: Sheet; default: bg-card.
   --diff-viewer-ink: Code text; default: text-card-foreground.
   --diff-viewer-added: Added lines and words; default: oklch(0.62 0.16 150).
   --diff-viewer-removed: Removed lines and words; default: var(--destructive).
   --diff-viewer-radius: Sheet corners; default: rounded-[14px].
   --diff-viewer-font: Code size; default: text-[12.5px].
   --diff-viewer-max-height: Body height before it scrolls; default: none.
*/

/* Styled diff viewer: the animated primitive plus the Keyframery look. A quiet sheet with the file
   and its counts on top, the code on a slightly sunk ground, added and removed lines tinted from two
   variables (green and the theme's destructive by default), changed words a stronger tint of the
   same, and slim rows above each hunk for its fold, its range and the review buttons. */

import * as React from "react"

import {
  DiffViewer as DiffViewerRoot,
  DiffViewerActions as DiffViewerActionsPrimitive,
  DiffViewerContent as DiffViewerContentPrimitive,
  DiffViewerCopyButton as DiffViewerCopyButtonPrimitive,
  DiffViewerHeader as DiffViewerHeaderPrimitive,
  DiffViewerStats as DiffViewerStatsPrimitive,
  DiffViewerTitle as DiffViewerTitlePrimitive,
  DiffViewerViewSwitch as DiffViewerViewSwitchPrimitive,
} from "@/components/keyframery/primitives/diff-viewer"
import { Speed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/* UI SDK accepts a class name or a function of state; keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* The two diff colours, once: --diff-add and --diff-del. */
const colors = "[--diff-add:var(--diff-viewer-added,oklch(0.62_0.16_150))] [--diff-del:var(--diff-viewer-removed,var(--destructive))]"

/* Token colours, as the code block has them. */
const tokens = cn(
  "[&_[data-token=keyword]]:text-ring [&_[data-token=tag]]:text-ring",
  "[&_[data-token=string]]:text-[color-mix(in_oklab,var(--destructive)_72%,var(--foreground))]",
  "[&_[data-token=number]]:text-[color-mix(in_oklab,var(--destructive)_55%,var(--ring))]",
  "[&_[data-token=comment]]:text-muted-foreground [&_[data-token=comment]]:italic",
  "[&_[data-token=function]]:font-medium [&_[data-token=function]]:text-foreground",
  "[&_[data-token=type]]:text-[color-mix(in_oklab,var(--ring)_55%,var(--foreground))]",
  "[&_[data-token=property]]:text-[color-mix(in_oklab,var(--ring)_40%,var(--foreground))]",
  "[&_[data-token=attribute]]:text-[color-mix(in_oklab,var(--ring)_55%,var(--foreground))]",
  "[&_[data-token=variable]]:text-[color-mix(in_oklab,var(--destructive)_55%,var(--ring))]",
  "[&_[data-token=punctuation]]:text-muted-foreground",
)

function DiffViewer({
  speed,
  className,
  lineNumbers = true,
  children,
  ...props
}: React.ComponentProps<typeof DiffViewerRoot> &
  SpeedProps & {
    /** Shows the old and new line numbers. */
    lineNumbers?: boolean
  }) {
  return (
    <Speed speed={speed}>
      <DiffViewerRoot
        data-numbers={lineNumbers ? undefined : "off"}
        className={withClass(
          cn(
            colors,
            "@container/diff-viewer flex w-full min-w-0 flex-col overflow-hidden rounded-[var(--diff-viewer-radius,14px)] bg-[var(--diff-viewer-face,var(--card))] text-[13px] text-[color:var(--diff-viewer-ink,var(--card-foreground))]",
            "shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.12)]",
            "dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08),0_8px_24px_-12px_rgb(0_0_0/0.7)]",
            "has-[>[data-slot=diff-viewer-content]:focus-visible]:ring-2 has-[>[data-slot=diff-viewer-content]:focus-visible]:ring-ring",
          ),
          className,
        )}
        {...props}
      >
        {children ?? (
          <>
            <DiffViewerHeader>
              <DiffViewerTitle />
              <DiffViewerStats />
              <DiffViewerActions>
                <DiffViewerViewSwitch />
                <DiffViewerCopyButton />
              </DiffViewerActions>
            </DiffViewerHeader>
            <DiffViewerContent />
          </>
        )}
      </DiffViewerRoot>
    </Speed>
  )
}

function DiffViewerHeader({ className, ...props }: React.ComponentProps<typeof DiffViewerHeaderPrimitive>) {
  return (
    <DiffViewerHeaderPrimitive
      className={withClass("flex h-11 min-w-0 shrink-0 items-center gap-2.5 border-b border-border/70 ps-3.5 pe-2 text-muted-foreground", className)}
      {...props}
    />
  )
}

function FileIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
      <path d="M9 2.75H5A1.25 1.25 0 0 0 3.75 4v8c0 .69.56 1.25 1.25 1.25h6c.69 0 1.25-.56 1.25-1.25V6L9 2.75Z" />
      <path d="M9 2.75V6h3.25" />
    </svg>
  )
}

/* The file name: its folder quiet, its name in full ink. With no children it reads `filename`. */
function DiffViewerTitle({ className, children, ...props }: React.ComponentProps<typeof DiffViewerTitlePrimitive>) {
  return (
    <DiffViewerTitlePrimitive
      className={withClass(
        "flex min-w-0 items-center gap-1.5 text-[12.5px] leading-none font-medium text-foreground [&_svg]:size-3.5 [&_svg]:shrink-0 [&_svg]:text-muted-foreground",
        className,
      )}
      {...props}
    >
      {children ??
        ((state) => {
          const cut = state.filename.lastIndexOf("/") + 1
          return (
            <>
              <FileIcon />
              <span className="min-w-0 truncate">
                <span className="text-muted-foreground @max-[28rem]/diff-viewer:hidden">{state.filename.slice(0, cut)}</span>
                {state.filename.slice(cut)}
              </span>
            </>
          )
        })}
    </DiffViewerTitlePrimitive>
  )
}

function DiffViewerStats({ className, ...props }: React.ComponentProps<typeof DiffViewerStatsPrimitive>) {
  return (
    <DiffViewerStatsPrimitive
      className={withClass(
        cn(
          "shrink-0 gap-1.5 font-mono text-[11.5px] leading-none font-medium",
          "*:data-[slot=diff-viewer-additions]:text-[color:color-mix(in_oklab,var(--diff-add)_88%,var(--foreground))]",
          "*:data-[slot=diff-viewer-deletions]:text-[color:color-mix(in_oklab,var(--diff-del)_88%,var(--foreground))]",
        ),
        className,
      )}
      {...props}
    />
  )
}

function DiffViewerActions({ className, ...props }: React.ComponentProps<typeof DiffViewerActionsPrimitive>) {
  return <DiffViewerActionsPrimitive className={withClass("ms-auto flex shrink-0 items-center gap-1.5", className)} {...props} />
}

/* A small well with a key that slides between Unified and Split. Hidden while the viewer is too
   narrow for split. */
function DiffViewerViewSwitch({ className, ...props }: React.ComponentProps<typeof DiffViewerViewSwitchPrimitive>) {
  return (
    <DiffViewerViewSwitchPrimitive
      className={withClass(
        cn(
          "h-7 rounded-[9px] bg-muted p-0.5 shadow-[inset_0_1px_2px_rgb(0_0_0/0.07),inset_0_0_0_1px_rgb(0_0_0/0.035)] dark:shadow-[inset_0_1px_2px_rgb(0_0_0/0.5),inset_0_0_0_1px_rgb(255_255_255/0.04)]",
          "before:inset-y-0.5 before:start-0.5 before:w-[calc(50%-2px)] before:rounded-[7px] before:bg-background",
          "before:shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_1px_rgb(0_0_0/0.05),0_2px_4px_-2px_rgb(0_0_0/0.1)]",
          "dark:before:bg-accent dark:before:shadow-[0_0_0_1px_rgb(255_255_255/0.07),inset_0_1px_0_rgb(255_255_255/0.08)]",
          "data-narrow:hidden",
          "*:h-6 *:cursor-pointer *:rounded-[7px] *:px-2.5 *:text-[12px] *:leading-none *:font-medium *:text-muted-foreground *:outline-none",
          "*:hover:text-foreground *:data-selected:text-foreground *:focus-visible:ring-2 *:focus-visible:ring-ring",
        ),
        className,
      )}
      {...props}
    />
  )
}

function DiffViewerCopyButton({ className, ...props }: React.ComponentProps<typeof DiffViewerCopyButtonPrimitive>) {
  return (
    <DiffViewerCopyButtonPrimitive
      className={withClass(
        cn(
          "grid size-7 shrink-0 cursor-pointer place-items-center rounded-[8px] text-muted-foreground outline-none",
          "hover:bg-foreground/[0.06] hover:text-foreground",
          "data-copied:text-[oklch(0.62_0.16_150)] data-copied:hover:text-[oklch(0.62_0.16_150)]",
          "focus-visible:ring-2 focus-visible:ring-ring",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* Line tints: the row a light wash of its colour, changed words stronger. */

const lines = cn(
  /* Unified rows: old number, new number, sign, code. */
  "[&_[data-slot=diff-viewer-line]]:grid [&_[data-slot=diff-viewer-line]]:grid-cols-[var(--diff-num)_var(--diff-num)_1.25rem_1fr]",
  "[--diff-num:calc(4ch+0.875rem)] group-data-[numbers=off]/diff-viewer:[&_[data-slot=diff-viewer-line]]:grid-cols-[0_0_1.5rem_1fr]",
  "group-data-[numbers=off]/diff-viewer:[&_[data-slot=diff-viewer-line-number]]:invisible",
  /* Split rows: two cells, each number, sign, code; the code wraps. */
  "[&_[data-slot=diff-viewer-row]]:grid [&_[data-slot=diff-viewer-row]]:grid-cols-2",
  "[&_[data-slot=diff-viewer-cell]]:grid [&_[data-slot=diff-viewer-cell]]:min-w-0 [&_[data-slot=diff-viewer-cell]]:grid-cols-[var(--diff-num)_1.25rem_1fr]",
  "group-data-[numbers=off]/diff-viewer:[&_[data-slot=diff-viewer-cell]]:grid-cols-[0_1.5rem_1fr]",
  "[&_[data-slot=diff-viewer-cell][data-side=new]]:border-s [&_[data-slot=diff-viewer-cell][data-side=new]]:border-border/60",
  "[&_[data-slot=diff-viewer-cell]_[data-slot=diff-viewer-line-content]]:whitespace-pre-wrap [&_[data-slot=diff-viewer-cell]_[data-slot=diff-viewer-line-content]]:[overflow-wrap:anywhere]",
  "[&_[data-slot=diff-viewer-cell][data-kind=empty]]:bg-[repeating-linear-gradient(135deg,transparent_0_5px,color-mix(in_oklab,var(--foreground)_4%,transparent)_5px_6px)]",
  /* Gutter. */
  "[&_[data-slot=diff-viewer-line-number]]:pe-2.5 [&_[data-slot=diff-viewer-line-number]]:text-end [&_[data-slot=diff-viewer-line-number]]:text-muted-foreground/55 [&_[data-slot=diff-viewer-line-number]]:tabular-nums [&_[data-slot=diff-viewer-line-number]]:select-none",
  "[&_[data-slot=diff-viewer-line-sign]]:text-center [&_[data-slot=diff-viewer-line-sign]]:select-none [&_[data-slot=diff-viewer-line-content]]:pe-4",
  /* Added. */
  "[&_[data-kind=added]]:bg-[color-mix(in_oklab,var(--diff-add)_10%,transparent)] [&_[data-kind=added]_[data-slot=diff-viewer-line-number]]:bg-[color-mix(in_oklab,var(--diff-add)_8%,transparent)]",
  "[&_[data-kind=added]_[data-slot=diff-viewer-line-number]]:text-[color:color-mix(in_oklab,var(--diff-add)_70%,var(--foreground))]",
  "[&_[data-kind=added]_[data-slot=diff-viewer-line-sign]]:text-[color:var(--diff-add)]",
  "[&_[data-kind=added]_[data-changed]]:rounded-[3px] [&_[data-kind=added]_[data-changed]]:bg-[color-mix(in_oklab,var(--diff-add)_26%,transparent)] [&_[data-kind=added]_[data-changed]]:[box-shadow:0_0_0_1px_color-mix(in_oklab,var(--diff-add)_26%,transparent)]",
  /* Removed. */
  "[&_[data-kind=removed]]:bg-[color-mix(in_oklab,var(--diff-del)_8%,transparent)] [&_[data-kind=removed]_[data-slot=diff-viewer-line-number]]:bg-[color-mix(in_oklab,var(--diff-del)_6%,transparent)]",
  "[&_[data-kind=removed]_[data-slot=diff-viewer-line-number]]:text-[color:color-mix(in_oklab,var(--diff-del)_70%,var(--foreground))]",
  "[&_[data-kind=removed]_[data-slot=diff-viewer-line-sign]]:text-[color:var(--diff-del)]",
  "[&_[data-kind=removed]_[data-changed]]:rounded-[3px] [&_[data-kind=removed]_[data-changed]]:bg-[color-mix(in_oklab,var(--diff-del)_22%,transparent)] [&_[data-kind=removed]_[data-changed]]:[box-shadow:0_0_0_1px_color-mix(in_oklab,var(--diff-del)_22%,transparent)]",
  "dark:[&_[data-kind=added]]:bg-[color-mix(in_oklab,var(--diff-add)_14%,transparent)]",
  "dark:[&_[data-kind=removed]]:bg-[color-mix(in_oklab,var(--diff-del)_12%,transparent)]",
)

/* The slim rows above a hunk and after the last one: fold, range, review. */
const bars = cn(
  "[&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:sticky [&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:start-0",
  "[&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:flex [&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:h-[var(--diff-fold-height)] [&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:w-[100cqw]",
  "[&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:items-center [&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:gap-2 [&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:px-1.5",
  "[&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:font-sans [&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:text-[12px] [&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:text-muted-foreground",
  "[&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:bg-[color-mix(in_oklab,var(--muted)_70%,var(--diff-viewer-face,var(--card)))]",
  "[&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:border-y [&_:is([data-slot=diff-viewer-hunk-header],[data-slot=diff-viewer-gap])]:border-border/50",
  "[&_[data-slot=diff-viewer-body]>:first-child]:border-t-0",
  /* Fold button. */
  "[&_[data-slot=diff-viewer-fold]]:inline-flex [&_[data-slot=diff-viewer-fold]]:h-6 [&_[data-slot=diff-viewer-fold]]:shrink-0 [&_[data-slot=diff-viewer-fold]]:cursor-pointer [&_[data-slot=diff-viewer-fold]]:items-center [&_[data-slot=diff-viewer-fold]]:gap-1.5 [&_[data-slot=diff-viewer-fold]]:rounded-[7px] [&_[data-slot=diff-viewer-fold]]:px-2 [&_[data-slot=diff-viewer-fold]]:font-medium [&_[data-slot=diff-viewer-fold]]:outline-none",
  "[&_[data-slot=diff-viewer-fold]_svg]:size-3.5 [&_[data-slot=diff-viewer-fold]:hover]:bg-foreground/[0.06] [&_[data-slot=diff-viewer-fold]:hover]:text-foreground [&_[data-slot=diff-viewer-fold]:focus-visible]:ring-2 [&_[data-slot=diff-viewer-fold]:focus-visible]:ring-ring",
  "[&_[data-slot=diff-viewer-fold][data-disabled]]:cursor-default [&_[data-slot=diff-viewer-fold][data-disabled]]:bg-transparent [&_[data-slot=diff-viewer-fold][data-disabled]]:text-muted-foreground",
  /* Range. */
  "[&_[data-slot=diff-viewer-range]]:min-w-0 [&_[data-slot=diff-viewer-range]]:flex-1 [&_[data-slot=diff-viewer-range]]:truncate [&_[data-slot=diff-viewer-range]]:ps-1 [&_[data-slot=diff-viewer-range]]:font-mono [&_[data-slot=diff-viewer-range]]:text-[11px] [&_[data-slot=diff-viewer-range]]:text-muted-foreground/75",
  "[&_[data-slot=diff-viewer-section]]:text-muted-foreground",
  "[&_[data-slot=diff-viewer-fold]+[data-slot=diff-viewer-range]]:@max-[30rem]/diff-viewer:hidden @max-[26rem]/diff-viewer:[&_[data-slot=diff-viewer-fold-word]]:hidden",
  /* Review. */
  "[&_[data-slot=diff-viewer-review]]:ms-auto [&_[data-slot=diff-viewer-review]]:flex [&_[data-slot=diff-viewer-review]]:shrink-0 [&_[data-slot=diff-viewer-review]]:items-center [&_[data-slot=diff-viewer-review]]:gap-1",
  "[&_:is([data-slot=diff-viewer-accept],[data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo])]:h-6 [&_:is([data-slot=diff-viewer-accept],[data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo])]:cursor-pointer [&_:is([data-slot=diff-viewer-accept],[data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo])]:rounded-[7px] [&_:is([data-slot=diff-viewer-accept],[data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo])]:px-2.5 [&_:is([data-slot=diff-viewer-accept],[data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo])]:text-[12px] [&_:is([data-slot=diff-viewer-accept],[data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo])]:leading-none [&_:is([data-slot=diff-viewer-accept],[data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo])]:font-medium [&_:is([data-slot=diff-viewer-accept],[data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo])]:outline-none",
  "[&_:is([data-slot=diff-viewer-accept],[data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo]):focus-visible]:ring-2 [&_:is([data-slot=diff-viewer-accept],[data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo]):focus-visible]:ring-ring",
  "[&_:is([data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo]):hover]:bg-foreground/[0.06] [&_:is([data-slot=diff-viewer-reject],[data-slot=diff-viewer-undo]):hover]:text-foreground",
  "[&_[data-slot=diff-viewer-accept]]:bg-primary [&_[data-slot=diff-viewer-accept]]:text-primary-foreground [&_[data-slot=diff-viewer-accept]]:shadow-[inset_0_1px_0_rgb(255_255_255/0.14),0_1px_2px_rgb(0_0_0/0.25)] [&_[data-slot=diff-viewer-accept]:hover]:bg-primary/90",
  "[&_[data-slot=diff-viewer-status]]:inline-flex [&_[data-slot=diff-viewer-status]]:items-center [&_[data-slot=diff-viewer-status]]:gap-1 [&_[data-slot=diff-viewer-status]]:pe-1 [&_[data-slot=diff-viewer-status]]:font-medium [&_[data-slot=diff-viewer-status]_svg]:size-3.5",
  "[&_[data-slot=diff-viewer-status][data-decision=accepted]]:text-[oklch(0.62_0.16_150)] [&_[data-slot=diff-viewer-status][data-decision=rejected]]:text-muted-foreground",
  /* A rejected hunk steps back. */
  "[&_[data-slot=diff-viewer-hunk][data-decision=rejected]]:opacity-45 [&_[data-slot=diff-viewer-hunk][data-decision=rejected]]:grayscale",
)

/* The sunk ground the code sits on. With no children it renders the whole diff. */
function DiffViewerContent({ className, ...props }: React.ComponentProps<typeof DiffViewerContentPrimitive>) {
  return (
    <DiffViewerContentPrimitive
      className={withClass(
        cn(
          "@container min-h-0 max-h-[var(--diff-viewer-max-height,none)] min-w-0 overflow-auto font-mono text-[length:var(--diff-viewer-font,12.5px)] leading-[1.7] outline-none [scrollbar-width:thin] [--diff-fold-height:2.125rem]",
          "bg-[color-mix(in_oklab,var(--muted)_40%,var(--diff-viewer-face,var(--card)))] dark:bg-[color-mix(in_oklab,var(--muted)_30%,var(--diff-viewer-face,var(--card)))]",
          "[&_[data-slot=diff-viewer-body]]:min-w-full [&_[data-slot=diff-viewer-body]]:pb-1.5",
          "[&_[data-slot=diff-viewer-body][data-view=unified]]:w-max [&_[data-slot=diff-viewer-body][data-view=unified]_[data-slot=diff-viewer-line-content]]:whitespace-pre",
          lines,
          bars,
          tokens,
        ),
        className,
      )}
      {...props}
    />
  )
}

export {
  DiffViewer,
  DiffViewerActions,
  DiffViewerContent,
  DiffViewerCopyButton,
  DiffViewerHeader,
  DiffViewerStats,
  DiffViewerTitle,
  DiffViewerViewSwitch,
}
```

**components/keyframery/primitives/diff-viewer.tsx**

```tsx
"use client"

/* Animated diff viewer, on UI SDK's core. UI SDK ships no diff viewer, so the behaviour is defined in
   `@/components/core/diff-viewer` with `definePrimitive` and rendered here. This file adds motion only.
   Colours, radii, shadows and spacing stay yours (style `data-kind`, `data-changed`, `data-decision`,
   `data-view` and the `data-slot` names).

   Feedback (at every flourish):
   - Direction: switching unified and split, the new layout fades in from the side of its button,
     a few pixels, and the switch's key slides across.
   - Height: an opened fold grows from the fold row's height to its lines, which fade in.
   - A rejected hunk dims; the decision label rises in where the buttons were.
   Flourish (scaled by --kf-flourish; at 0 it is simply there):
   - Cascade: on mount, hunks rise in one after another with a little blur.
   - Roll: the +added and −removed counts roll up to their values.
   - Press depth on the buttons, the extra slide and blur of the view switch, the copy tick's draw. */

import type { StateOf } from "@ui-sdk/core"
import { createParts, type PartProps, usePart } from "@ui-sdk/react/primitive"
import * as React from "react"

import type { CodeBlockLanguage } from "@/components/keyframery/core/code-block-core"
import { type DiffBlock, type DiffLine, type DiffView, diffViewer, segmentsOf, splitRows, type SplitRow } from "@/components/keyframery/core/diff-viewer-core"
import { cn } from "@/lib/utils"

const parts = createParts(diffViewer, { root: "div", header: "div", title: "div", actions: "div" })

type ClassName<S> = string | ((state: S) => string | undefined) | undefined
/* UI SDK accepts a class name or a function of state; keep both working. */
function withClass<S>(base: string, className: ClassName<S>) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

const keyframes = [
  "@keyframes kf-diff-in{from{opacity:0;translate:0 calc(10px*var(--kf-flourish,1));filter:blur(calc(4px*var(--kf-flourish,1)))}}",
  "@keyframes kf-diff-view{from{opacity:0;translate:var(--diff-from,0) 0;filter:blur(calc(3px*var(--kf-flourish,1)))}}",
  "@keyframes kf-diff-tick{from{stroke-dashoffset:1}}",
].join("")

/* Hunks (and the row above each) rise in on mount, a beat apart. Not again after a view switch:
   then the whole body arrives by the switch. */
const cascade = cn(
  "animate-[kf-diff-in_calc(480ms*var(--kf-speed,1)*var(--kf-flourish,1))_var(--ease-spring)_both]",
  "[animation-delay:calc(var(--diff-hunk-index,0)*calc(70ms*var(--kf-speed,1))*var(--kf-flourish,1)+calc(80ms*var(--kf-speed,1))*var(--kf-flourish,1))]",
  "group-data-switched/diff-viewer:animate-none motion-reduce:animate-none!",
)

function DiffViewer({ className, ...props }: React.ComponentProps<typeof parts.Root>) {
  return (
    <>
      <style href="kf-diff-viewer" precedence="default">
        {keyframes}
      </style>
      <parts.Root className={withClass("group/diff-viewer relative", className)} {...props} />
    </>
  )
}

const DiffViewerHeader = parts.Header
const DiffViewerTitle = parts.Title
const DiffViewerActions = parts.Actions

/* ---------- Counts ---------- */

/* Each digit is a column of 0 to 9; the count rolls up to its value on mount and when it changes. */
function Roll({ value }: { value: number }) {
  return (
    <span aria-hidden className="inline-flex h-[1em] overflow-hidden leading-none tabular-nums">
      {String(value)
        .split("")
        .map((c, i, all) => (
          <span
            key={all.length - i}
            style={{ "--d": Number(c) } as React.CSSProperties}
            className={cn(
              "flex flex-col [translate:0_calc(var(--d)*-1em)] starting:[translate:0_0]",
              "transition-[translate] duration-[calc(720ms*var(--kf-speed,1)*var(--kf-flourish,1))] ease-spring",
              "delay-[calc((180ms+var(--diff-roll-i,0)*40ms)*var(--kf-speed,1)*var(--kf-flourish,1))] motion-reduce:transition-none",
            )}
          >
            {Array.from({ length: 10 }, (_, d) => (
              <span key={d} className="h-[1em]">
                {d}
              </span>
            ))}
          </span>
        ))}
    </span>
  )
}

function DiffViewerStats({ className, children, ...props }: PartProps<"div", StateOf<typeof diffViewer, "stats">>) {
  return usePart(
    diffViewer,
    "stats",
    {},
    {
      ...props,
      className: withClass("inline-flex items-center", className),
      children:
        children ??
        ((state) => (
          <>
            <span data-slot="diff-viewer-additions" className="inline-flex items-center">
              +<Roll value={state.additions} />
            </span>
            <span data-slot="diff-viewer-deletions" className="inline-flex items-center [--diff-roll-i:1]">
              −<Roll value={state.deletions} />
            </span>
          </>
        )),
    },
    "div",
  )
}

/* ---------- View switch ---------- */

/* The key slides between the two halves. Its surface follows the text colour; restyle it with before:. */
function DiffViewerViewSwitch({ className, children, ...props }: PartProps<"div", StateOf<typeof diffViewer, "view-switch">>) {
  return usePart(
    diffViewer,
    "view-switch",
    {},
    {
      ...props,
      className: withClass(
        cn(
          "relative isolate grid grid-cols-2",
          "before:pointer-events-none before:absolute before:inset-y-0 before:start-0 before:-z-10 before:w-1/2 before:content-['']",
          "before:bg-[color-mix(in_oklch,currentColor_9%,transparent)]",
          "before:transition-[translate] before:duration-[calc(320ms*var(--kf-speed,1))] before:ease-spring motion-reduce:before:transition-none",
          "data-[view=split]:before:translate-x-full rtl:data-[view=split]:before:-translate-x-full",
        ),
        className,
      ),
      children:
        children ??
        (() => (
          <>
            <DiffViewerViewOption value="unified" />
            <DiffViewerViewOption value="split" />
          </>
        )),
    },
    "div",
  )
}

function DiffViewerViewOption({
  value,
  className,
  children,
  ...props
}: { value: DiffView } & Omit<PartProps<"button", StateOf<typeof diffViewer, "view-option">>, "value">) {
  return usePart(
    diffViewer,
    "view-option",
    { value },
    {
      ...props,
      className: withClass(
        "transition-[color,scale] duration-[calc(200ms*var(--kf-speed,1))] ease-pop active:scale-[calc(1-0.05*var(--kf-flourish,1))] motion-reduce:transition-none",
        className,
      ),
      children: children ?? (value === "split" ? "Split" : "Unified"),
    },
    "button",
  )
}

/* ---------- Copy ---------- */

function CopyIcon({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden className={className}>
      <rect x="5.25" y="5.25" width="8" height="8" rx="2" />
      <path d="M10.75 5.25V4.5a1.75 1.75 0 0 0-1.75-1.75H4.5A1.75 1.75 0 0 0 2.75 4.5V9c0 .97.78 1.75 1.75 1.75h.75" />
    </svg>
  )
}

const swapIn = "transition-[opacity,scale,filter] duration-[calc(420ms*var(--kf-speed,1))] ease-pop motion-reduce:transition-none!"
const swapOut = "transition-[opacity,scale,filter] duration-[calc(160ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none!"

function DiffViewerCopyButton({ className, children, ...props }: PartProps<"button", StateOf<typeof diffViewer, "copy">>) {
  return usePart(
    diffViewer,
    "copy",
    {},
    {
      ...props,
      className: withClass(
        "relative transition-[scale] duration-[calc(260ms*var(--kf-speed,1))] ease-pop active:scale-[calc(1-0.08*var(--kf-flourish,1))] active:duration-[calc(90ms*var(--kf-speed,1))] motion-reduce:transition-none!",
        className,
      ),
      children:
        children ??
        ((state) => (
          <span className="grid place-items-center *:[grid-area:1/1]">
            <CopyIcon className={cn("size-4", state.copied ? cn(swapOut, "scale-[calc(1-0.5*var(--kf-flourish,1))] opacity-0 blur-[calc(3px*var(--kf-flourish,1))]") : swapIn)} />
            <svg
              viewBox="0 0 16 16"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.75"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden
              className={cn("size-4", state.copied ? swapIn : cn(swapOut, "scale-[calc(1-0.4*var(--kf-flourish,1))] opacity-0"))}
            >
              {state.copied && (
                <path
                  d="M3.5 8.5 6.5 11.5 12.5 4.75"
                  pathLength={1}
                  className="[stroke-dasharray:1] animate-[kf-diff-tick_calc(300ms*var(--kf-speed,1)*var(--kf-flourish,1))_var(--ease-house)_calc(80ms*var(--kf-speed,1)*var(--kf-flourish,1))_backwards] motion-reduce:animate-none"
                />
              )}
            </svg>
          </span>
        )),
    },
    "button",
  )
}

/* ---------- Lines ---------- */

const signs = { added: "+", removed: "−", context: " " } as const
const spoken = { added: "Added: ", removed: "Removed: ", context: "" } as const

/* A line's text, cut into coloured tokens; changed words carry `data-changed`. */
const LineText = React.memo(function LineText({ line, language, words }: { line: DiffLine; language: CodeBlockLanguage; words: boolean }) {
  const segments = segmentsOf(line, language, words)
  return (
    <span data-slot="diff-viewer-line-content">
      {spoken[line.kind] && <span className="sr-only">{spoken[line.kind]}</span>}
      {segments.length === 0 || (segments.length === 1 && segments[0].text === "")
        ? "​"
        : segments.map((segment, i) => (
            <span key={i} data-token={segment.kind} data-changed={segment.changed ? "" : undefined}>
              {segment.text}
            </span>
          ))}
    </span>
  )
})

const firstPaint = 240

type LinesProps = { lines: DiffLine[]; view: DiffView; language: CodeBlockLanguage; words: boolean }

/* The rows of one hunk or fold, in either view. Memoised: they re-render only when their lines,
   the view, the language or word marking change. */
const DiffViewerLines = React.memo(function DiffViewerLines({ lines: all, view, language, words }: LinesProps) {
  /* A very long run (a rewritten file) paints its first rows at once and the rest in a transition,
     which React renders in slices, so the page never stops answering. */
  const [ready, setReady] = React.useState<DiffLine[] | null>(all.length > firstPaint ? null : all)
  React.useEffect(() => {
    if (ready !== all) React.startTransition(() => setReady(all))
  }, [all, ready])
  const lines = ready === all ? all : all.slice(0, firstPaint)
  const rows: React.ReactNode[] =
    view === "split"
      ? splitOf(lines).map((row, i) => <SplitLine key={i} row={row} language={language} words={words} />)
      : lines.map((line, i) => <UnifiedLine key={i} line={line} language={language} words={words} />)
  if (rows.length <= chunk * 2) return rows
  /* Long runs go in chunks the browser skips styling and laying out while they are off screen. */
  const chunks: React.ReactNode[] = []
  for (let i = 0; i < rows.length; i += chunk)
    chunks.push(
      <div key={i} data-slot="diff-viewer-chunk" className="[content-visibility:auto] [contain-intrinsic-size:auto_calc(64*1.7em)]">
        {rows.slice(i, i + chunk)}
      </div>,
    )
  return chunks
})

const chunk = 64

const UnifiedLine = React.memo(function UnifiedLine({ line, language, words }: { line: DiffLine; language: CodeBlockLanguage; words: boolean }) {
  return (
    <div data-slot="diff-viewer-line" data-kind={line.kind}>
      <span data-slot="diff-viewer-line-number" data-side="old" aria-hidden>
        {line.old}
      </span>
      <span data-slot="diff-viewer-line-number" data-side="new" aria-hidden>
        {line.new}
      </span>
      <span data-slot="diff-viewer-line-sign" aria-hidden>
        {signs[line.kind]}
      </span>
      <LineText line={line} language={language} words={words} />
    </div>
  )
})

const splitCache = new WeakMap<DiffLine[], SplitRow[]>()
function splitOf(lines: DiffLine[]) {
  let rows = splitCache.get(lines)
  if (!rows) splitCache.set(lines, (rows = splitRows(lines)))
  return rows
}

function SplitCell({ line, side, language, words }: { line?: DiffLine; side: "old" | "new"; language: CodeBlockLanguage; words: boolean }) {
  return (
    <div data-slot="diff-viewer-cell" data-side={side} data-kind={line ? line.kind : "empty"}>
      <span data-slot="diff-viewer-line-number" data-side={side} aria-hidden>
        {line ? (side === "old" ? line.old : line.new) : null}
      </span>
      <span data-slot="diff-viewer-line-sign" aria-hidden>
        {line ? signs[line.kind] : null}
      </span>
      {line ? <LineText line={line} language={language} words={words} /> : <span data-slot="diff-viewer-line-content" />}
    </div>
  )
}

const SplitLine = React.memo(function SplitLine({ row, language, words }: { row: SplitRow; language: CodeBlockLanguage; words: boolean }) {
  return (
    <div data-slot="diff-viewer-row">
      <SplitCell line={row.left} side="old" language={language} words={words} />
      <SplitCell line={row.right} side="new" language={language} words={words} />
    </div>
  )
})

/* ---------- Hunks and folds ---------- */

function DiffViewerHunk({ value, className, ...props }: { value: string } & Omit<PartProps<"div", StateOf<typeof diffViewer, "hunk">>, "value">) {
  return usePart(
    diffViewer,
    "hunk",
    { value },
    {
      ...props,
      className: withClass(cn("relative transition-[opacity,filter] duration-[calc(240ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none", cascade), className),
    },
    "div",
  )
}

function DiffViewerHunkHeader({ value, className, ...props }: { value: string } & Omit<PartProps<"div", StateOf<typeof diffViewer, "hunk-header">>, "value">) {
  return usePart(diffViewer, "hunk-header", { value }, { ...props, className: withClass(cascade, className) }, "div")
}

function DiffViewerGap({ value, className, ...props }: { value: string } & Omit<PartProps<"div", StateOf<typeof diffViewer, "gap">>, "value">) {
  return usePart(diffViewer, "gap", { value }, { ...props, className: withClass(cascade, className) }, "div")
}

function UnfoldIcon({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden className={className}>
      <path d="M5 5.5 8 2.5l3 3M5 10.5l3 3 3-3M8 2.5v4M8 13.5v-4" />
    </svg>
  )
}

function DiffViewerFold({ value, className, children, ...props }: { value: string } & Omit<PartProps<"button", StateOf<typeof diffViewer, "fold">>, "value">) {
  return usePart(
    diffViewer,
    "fold",
    { value },
    {
      ...props,
      className: withClass(
        cn(
          "transition-[color,background-color,scale] duration-[calc(160ms*var(--kf-speed,1))] ease-house active:scale-[calc(1-0.015*var(--kf-flourish,1))] motion-reduce:transition-none",
          "[&_svg]:transition-[translate,scale] [&_svg]:duration-[calc(260ms*var(--kf-speed,1))] [&_svg]:ease-pop hover:[&_svg]:scale-[calc(1+0.12*var(--kf-flourish,1))]",
        ),
        className,
      ),
      children:
        children ??
        ((state) => (
          <>
            <UnfoldIcon />
            <span>
              {state.lines} <span data-slot="diff-viewer-fold-word">unchanged </span>
              {state.lines === 1 ? "line" : "lines"}
            </span>
          </>
        )),
    },
    "button",
  )
}

/* An opened fold: grows from the fold row's height (`--diff-fold-height`) to its lines, which fade in. */
function DiffViewerExpanded({ value, className, children, ...props }: { value: string } & Omit<PartProps<"div", StateOf<typeof diffViewer, "expanded">>, "value">) {
  return usePart(
    diffViewer,
    "expanded",
    { value },
    {
      ...props,
      className: withClass(
        cn(
          "grid grid-rows-[1fr] starting:grid-rows-[0fr] starting:min-h-[var(--diff-fold-height,2rem)]",
          "transition-[grid-template-rows,min-height] duration-[calc(380ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none",
        ),
        className,
      ),
      children: (state) => (
        <div
          data-slot="diff-viewer-expanded-lines"
          className="min-h-0 overflow-hidden opacity-100 transition-opacity delay-[calc(60ms*var(--kf-speed,1))] duration-[calc(320ms*var(--kf-speed,1))] ease-house starting:opacity-0 motion-reduce:transition-none"
        >
          {typeof children === "function" ? children(state) : children}
        </div>
      ),
    },
    "div",
  )
}

/* ---------- Review ---------- */

const press =
  "transition-[color,background-color,box-shadow,scale] duration-[calc(160ms*var(--kf-speed,1))] ease-pop active:scale-[calc(1-0.05*var(--kf-flourish,1))] motion-reduce:transition-none"
const arrive = cn(
  "transition-[opacity,translate] duration-[calc(300ms*var(--kf-speed,1))] ease-spring motion-reduce:transition-none",
  "starting:opacity-0 starting:translate-y-[calc(4px+4px*var(--kf-flourish,1))]",
)

function DiffViewerAccept({ value, className, children, ...props }: { value: string } & Omit<PartProps<"button", StateOf<typeof diffViewer, "accept">>, "value">) {
  return usePart(diffViewer, "accept", { value }, { ...props, className: withClass(cn(press, arrive), className), children: children ?? "Accept" }, "button")
}

function DiffViewerReject({ value, className, children, ...props }: { value: string } & Omit<PartProps<"button", StateOf<typeof diffViewer, "reject">>, "value">) {
  return usePart(diffViewer, "reject", { value }, { ...props, className: withClass(cn(press, arrive), className), children: children ?? "Reject" }, "button")
}

function DiffViewerStatus({ value, className, children, ...props }: { value: string } & Omit<PartProps<"span", StateOf<typeof diffViewer, "status">>, "value">) {
  return usePart(
    diffViewer,
    "status",
    { value },
    {
      ...props,
      className: withClass(arrive, className),
      children:
        children ??
        ((state) => (
          <>
            <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
              {state.decision === "accepted" ? (
                <path
                  d="M3.5 8.5 6.5 11.5 12.5 4.75"
                  pathLength={1}
                  className="[stroke-dasharray:1] animate-[kf-diff-tick_calc(320ms*var(--kf-speed,1)*var(--kf-flourish,1))_var(--ease-house)_calc(120ms*var(--kf-speed,1)*var(--kf-flourish,1))_backwards] motion-reduce:animate-none"
                />
              ) : (
                <path d="M4.5 4.5l7 7M11.5 4.5l-7 7" />
              )}
            </svg>
            {state.decision === "accepted" ? "Accepted" : "Rejected"}
          </>
        )),
    },
    "span",
  )
}

function DiffViewerUndo({ value, className, children, ...props }: { value: string } & Omit<PartProps<"button", StateOf<typeof diffViewer, "undo">>, "value">) {
  return usePart(diffViewer, "undo", { value }, { ...props, className: withClass(cn(press, arrive), className), children: children ?? "Undo" }, "button")
}

/* ---------- Content ---------- */

/* The review actions for one hunk: Reject and Accept, or the decision and Undo. */
function Review({ value }: { value: string }) {
  return (
    <span data-slot="diff-viewer-review">
      <DiffViewerReject value={value} />
      <DiffViewerAccept value={value} />
      <DiffViewerStatus value={value} />
      <DiffViewerUndo value={value} />
    </span>
  )
}

type BlocksProps = { blocks: DiffBlock[]; view: DiffView; expanded: string[]; review: boolean; language: CodeBlockLanguage; words: boolean }

/* Every block of the diff: folds, opened folds, hunk headers and hunks. */
const DiffViewerBlocks = React.memo(function DiffViewerBlocks({ blocks, view, expanded, review, language, words }: BlocksProps) {
  return blocks.map((block) => {
    const gap = block.gap
    const open = gap && expanded.includes(gap.key)
    const lines = gap && open && gap.lines ? (
      <DiffViewerExpanded key={`${gap.key}-open`} value={gap.key}>
        <DiffViewerLines lines={gap.lines} view={view} language={language} words={words} />
      </DiffViewerExpanded>
    ) : null
    if (block.type === "gap") {
      return lines ?? (
        <DiffViewerGap key={block.gap.key} value={block.gap.key}>
          <DiffViewerFold value={block.gap.key} />
        </DiffViewerGap>
      )
    }
    const value = String(block.hunk.index)
    const header = (gap && !open) || review
    return (
      <React.Fragment key={value}>
        {lines}
        {header && (
          <DiffViewerHunkHeader value={value}>
            {gap && !open && <DiffViewerFold value={gap.key} />}
            <span data-slot="diff-viewer-range">
              {block.hunk.range}
              {block.hunk.section && <span data-slot="diff-viewer-section"> {block.hunk.section}</span>}
            </span>
            {review && <Review value={value} />}
          </DiffViewerHunkHeader>
        )}
        <DiffViewerHunk value={value}>
          <DiffViewerLines lines={block.hunk.lines} view={view} language={language} words={words} />
        </DiffViewerHunk>
      </React.Fragment>
    )
  })
})

/* The scrolling body. With no children it renders the whole diff. Switching views remounts the body,
   which arrives from the side of the view chosen (split from the right, unified from the left). */
function DiffViewerContent({ className, children, ...props }: PartProps<"div", StateOf<typeof diffViewer, "content">>) {
  return usePart(
    diffViewer,
    "content",
    {},
    {
      ...props,
      className: withClass("isolate", className),
      children:
        children ??
        ((state) => (
          <div
            key={state.view}
            data-slot="diff-viewer-body"
            data-view={state.view}
            className={cn(
              "[--diff-from:calc(-1*(6px+10px*var(--kf-flourish,1)))] data-[view=split]:[--diff-from:calc(6px+10px*var(--kf-flourish,1))]",
              "group-data-switched/diff-viewer:animate-[kf-diff-view_calc(300ms*var(--kf-speed,1))_var(--ease-house)_both] motion-reduce:animate-none!",
            )}
          >
            <DiffViewerBlocks blocks={state.model.blocks} view={state.view} expanded={state.expanded} review={state.review} language={state.language} words={state.wordDiff} />
          </div>
        )),
    },
    "div",
  )
}

export {
  DiffViewer,
  DiffViewerAccept,
  DiffViewerActions,
  DiffViewerBlocks,
  DiffViewerContent,
  DiffViewerCopyButton,
  DiffViewerExpanded,
  DiffViewerFold,
  DiffViewerGap,
  DiffViewerHeader,
  DiffViewerHunk,
  DiffViewerHunkHeader,
  DiffViewerLines,
  DiffViewerReject,
  DiffViewerStats,
  DiffViewerStatus,
  DiffViewerTitle,
  DiffViewerUndo,
  DiffViewerViewOption,
  DiffViewerViewSwitch,
}
export {
  buildDiff,
  type DiffBlock,
  type DiffDecision,
  type DiffHunk,
  type DiffLine,
  type DiffModel,
  type DiffView,
  diffWords,
  parsePatch,
} from "@/components/keyframery/core/diff-viewer-core"
```

**components/keyframery/core/diff-viewer-core.ts**

```ts
/* A diff viewer, as a UI SDK primitive. UI SDK ships none, so it is defined with its core: the same
   definition renders in React, Vue, Svelte, Solid and web components.

   For reviewing the changes an AI agent proposes to a file, or any code review. It owns the diff:
   computing it from `before` and `after` (Myers, in `./diff-viewer-diff`, no package) or reading a
   unified `patch`, the hunks and the folded runs between them, which view is shown (unified or split,
   falling back to unified when the viewer is narrower than `splitMinWidth`), which folds are open,
   what the reviewer decided for each hunk, and the copy button.

   Agents read the file name, the counts, the view, the folds and a summary of every hunk, and can
   switch the view and open folds. Accepting or rejecting a hunk is left to the person reviewing. */

import { announce, createChange, css, definePrimitive } from "@ui-sdk/core"

import { type CodeBlockLanguage, type CodeToken, tokenize } from "@/components/keyframery/core/code-block-core"
import { buildDiff, type DiffHunk, type DiffLine, type DiffModel } from "@/components/keyframery/core/diff-viewer-diff-core"

type DiffView = "unified" | "split"
type DiffDecision = "accepted" | "rejected"

/* ---------- Text ---------- */

const extensions: Record<string, CodeBlockLanguage> = {
  ts: "ts", mts: "ts", cts: "ts", tsx: "tsx", js: "js", mjs: "js", cjs: "js", jsx: "jsx",
  json: "json", css: "css", html: "html", htm: "html", sh: "bash", bash: "bash", zsh: "bash",
}

/** The tokenizer for a file name, by its extension. */
function languageOf(filename: string | undefined): CodeBlockLanguage {
  const ext = filename?.split(".").pop()?.toLowerCase()
  return (ext && extensions[ext]) || "text"
}

/** A run of a line's text: its token kind for colour, and whether it is a word that changed. */
type DiffSegment = { text: string; kind?: CodeToken["kind"]; changed?: boolean }

/* Tokenizing is the costly part of drawing a line, so lines are cached by their text. */
const tokenCache = new Map<string, CodeToken[]>()
function tokensOf(text: string, language: CodeBlockLanguage): CodeToken[] {
  if (language === "text") return [{ text }]
  const key = `${language}\u0000${text}`
  let tokens = tokenCache.get(key)
  if (!tokens) {
    /* A line inside a block comment can't know it is one on its own; its leading star says so. */
    const comment = /^(ts|tsx|js|jsx|css)$/.test(language) && /^\s*(\*|\/\*|\/\/)/.test(text)
    tokens = comment ? [{ text, kind: "comment" }] : (tokenize(text, language)[0] ?? [])
    if (tokenCache.size > 8000) tokenCache.clear()
    tokenCache.set(key, tokens)
  }
  return tokens
}

/** Splits a line into coloured segments, cut again where a changed word starts or ends. */
function segmentsOf(line: DiffLine, language: CodeBlockLanguage, words = true): DiffSegment[] {
  const tokens = tokensOf(line.text, language)
  const ranges = words ? line.words : undefined
  if (!ranges?.length) return tokens
  const out: DiffSegment[] = []
  let at = 0
  for (const token of tokens) {
    const end = at + token.text.length
    let from = at
    for (const [s, e] of ranges) {
      if (e <= from || s >= end) continue
      if (s > from) out.push({ text: line.text.slice(from, s), kind: token.kind })
      const stop = Math.min(e, end)
      out.push({ text: line.text.slice(Math.max(s, from), stop), kind: token.kind, changed: true })
      from = stop
    }
    if (from < end) out.push({ text: line.text.slice(from, end), kind: token.kind })
    at = end
  }
  /* Neighbouring changed segments become one, so the highlight is one shape. */
  return out
}

/* ---------- Options and state ---------- */

type DiffViewerOptions = {
  /** The file before the change. With `after`, the diff is computed here. */
  before?: string
  /** The file after the change. Also what the copy button copies. */
  after?: string
  /** A unified diff (`git diff`), used when `before` and `after` are left out. */
  patch?: string
  /** The file name in the header. Read from the patch when left out. */
  filename?: string
  /** Which tokenizer colours the code. Defaults to one guessed from the file name. */
  language?: CodeBlockLanguage
  /** "unified" or "split", controlled. */
  view?: DiffView
  /** The view at first, when uncontrolled. Defaults to "unified". */
  defaultView?: DiffView
  /** Runs when the view wants to change. */
  onViewChange?: (view: DiffView) => void
  /** Below this width (px) the split view shows as unified. Defaults to 640. */
  splitMinWidth?: number
  /** Unchanged lines kept around each change. Defaults to 3. */
  context?: number
  /** Marks the words that changed inside a changed line. Defaults to true. */
  wordDiff?: boolean
  /** Shows Accept and Reject on every hunk. Defaults to on when `onAccept` or `onReject` is given. */
  review?: boolean
  /** Called with the hunk's index (and the hunk) when the reviewer accepts it. */
  onAccept?: (index: number, hunk: DiffHunk) => void
  /** Called with the hunk's index (and the hunk) when the reviewer rejects it. */
  onReject?: (index: number, hunk: DiffHunk) => void
  /** Called with the hunk's index when the reviewer takes a decision back. */
  onUndo?: (index: number, hunk: DiffHunk) => void
  /** Called after the copy button copied the new text. */
  onCopy?: (text: string) => void
}

/** What an agent reads about each hunk. */
type DiffHunkSummary = { index: number; range: string; section: string; additions: number; deletions: number; decision: DiffDecision | "pending"; gap?: string }
/** What an agent reads about each fold. */
type DiffFoldSummary = { key: string; lines: number; expanded: boolean; expandable: boolean }

type DiffViewerState = {
  model: DiffModel
  filename: string
  language: CodeBlockLanguage
  /** The view asked for. */
  view: DiffView
  /** The view on screen: unified while narrow. */
  shown: DiffView
  narrow: boolean
  splitMinWidth: number
  wordDiff: boolean
  review: boolean
  /** Keys of the folds that are open. */
  expanded: string[]
  /** Decisions by hunk index. */
  decisions: Record<string, DiffDecision>
  /** The view changed since mount, so content arrives by the switch instead of cascading again. */
  switched: boolean
  copied: boolean
  /** What the copy button copies. */
  text: string
  additions: number
  deletions: number
  hunks: DiffHunkSummary[]
  folds: DiffFoldSummary[]
  /** One sentence for agents: the counts and every hunk with its decision. */
  summary: string
}

/* The diff is rebuilt only when its inputs change, so the hunks keep their identity and rows don't
   re-render for nothing. A few recent inputs are kept, for pages with more than one viewer. */
const models: { key: string; model: DiffModel }[] = []
function modelOf(options: DiffViewerOptions): DiffModel {
  const key = JSON.stringify([options.before, options.after, options.patch, options.context ?? 3, options.wordDiff ?? true])
  const hit = models.find((entry) => entry.key === key)
  if (hit) return hit.model
  const model = buildDiff({ before: options.before, after: options.after, patch: options.patch, context: options.context, words: options.wordDiff })
  models.unshift({ key, model })
  if (models.length > 6) models.pop()
  return model
}

const summaries = new WeakMap<DiffModel, Map<string, DiffHunkSummary[]>>()
function hunkSummaries(model: DiffModel, decisions: Record<string, DiffDecision>): DiffHunkSummary[] {
  const key = JSON.stringify(decisions)
  let byModel = summaries.get(model)
  if (!byModel) summaries.set(model, (byModel = new Map()))
  let list = byModel.get(key)
  if (!list) {
    list = model.blocks.flatMap((block) =>
      block.type === "hunk"
        ? [{
            index: block.hunk.index,
            range: block.hunk.range,
            section: block.hunk.section,
            additions: block.hunk.additions,
            deletions: block.hunk.deletions,
            decision: decisions[block.hunk.index] ?? "pending",
            gap: block.gap?.key,
          }]
        : [],
    )
    if (byModel.size > 32) byModel.clear()
    byModel.set(key, list)
  }
  return list
}

const foldCache = new WeakMap<DiffModel, Map<string, DiffFoldSummary[]>>()
function foldSummaries(model: DiffModel, expanded: string[]): DiffFoldSummary[] {
  const key = expanded.join(",")
  let byModel = foldCache.get(model)
  if (!byModel) foldCache.set(model, (byModel = new Map()))
  let list = byModel.get(key)
  if (!list) {
    list = model.gaps.map((gap) => ({ key: gap.key, lines: gap.count, expanded: expanded.includes(gap.key), expandable: !!gap.lines }))
    if (byModel.size > 32) byModel.clear()
    byModel.set(key, list)
  }
  return list
}

const summaryOf = (filename: string, model: DiffModel, hunks: DiffHunkSummary[]) =>
  `${filename || "File"}: +${model.additions} −${model.deletions} in ${hunks.length} ${hunks.length === 1 ? "change" : "changes"}. ` +
  hunks.map((h) => `${h.index + 1}. ${h.range}${h.section ? ` ${h.section}` : ""} (+${h.additions} −${h.deletions}, ${h.decision})`).join("; ")

const fromOptions = (options: DiffViewerOptions) => {
  const model = modelOf(options)
  const filename = options.filename ?? model.filename ?? ""
  return {
    model,
    filename,
    language: options.language ?? languageOf(filename),
    splitMinWidth: options.splitMinWidth ?? 640,
    wordDiff: options.wordDiff ?? true,
    review: options.review ?? !!(options.onAccept || options.onReject),
    text: options.after ?? options.patch ?? "",
    additions: model.additions,
    deletions: model.deletions,
  }
}

const diffViewer = definePrimitive({
  name: "diff-viewer",
  options: {
    before: "string",
    after: "string",
    patch: "string",
    filename: "string",
    language: "string",
    view: "string",
    defaultView: "string",
    onViewChange: "callback",
    splitMinWidth: "number",
    context: "number",
    wordDiff: "boolean",
    review: "boolean",
    onAccept: "callback",
    onReject: "callback",
    onUndo: "callback",
    onCopy: "callback",
  },
  controlled: ["filename", "view", "summary", "additions", "deletions", "hunks", "folds", "expanded"],
  state: (options: DiffViewerOptions): DiffViewerState => {
    const base = fromOptions(options)
    const view = options.view ?? options.defaultView ?? "unified"
    return {
      ...base,
      view,
      shown: view,
      narrow: false,
      expanded: [],
      decisions: {},
      switched: false,
      copied: false,
      hunks: hunkSummaries(base.model, {}),
      folds: foldSummaries(base.model, []),
      summary: summaryOf(base.filename, base.model, hunkSummaries(base.model, {})),
    }
  },
  sync: (options) => ({ ...fromOptions(options), ...(options.view === undefined ? {} : { view: options.view }) }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    let timer: ReturnType<typeof setTimeout> | undefined
    context.onDestroy(() => clearTimeout(timer))

    /* Keep what follows from the rest current: the view on screen, the summaries, and a fresh start
       (folds closed, decisions cleared) when the diff itself changes. */
    let seen = { model: store.get().model, view: store.get().view, narrow: store.get().narrow, expanded: store.get().expanded, decisions: store.get().decisions, filename: store.get().filename }
    context.onDestroy(
      store.subscribe(() => {
        const s = store.get()
        if (s.model === seen.model && s.view === seen.view && s.narrow === seen.narrow && s.expanded === seen.expanded && s.decisions === seen.decisions && s.filename === seen.filename) return
        const fresh = s.model !== seen.model
        const expanded = fresh ? [] : s.expanded
        const decisions = fresh ? {} : s.decisions
        const shown: DiffView = s.narrow ? "unified" : s.view
        const switched = s.switched || (shown !== s.shown && !fresh)
        seen = { model: s.model, view: s.view, narrow: s.narrow, expanded, decisions, filename: s.filename }
        const hunks = hunkSummaries(s.model, decisions)
        store.set({
          expanded,
          decisions,
          shown,
          switched: fresh ? false : switched,
          hunks,
          folds: foldSummaries(s.model, expanded),
          summary: summaryOf(s.filename, s.model, hunks),
          ...(fresh ? { copied: false } : {}),
        })
      }),
    )

    const hunk = (index: number) => store.get().model.hunks[index]
    const decide = (index: number, decision: DiffDecision | undefined) => {
      const h = hunk(index)
      if (!h) return false
      const decisions = { ...store.get().decisions }
      if (decision) decisions[index] = decision
      else delete decisions[index]
      store.set({ decisions })
      announce(decision ? `Change ${index + 1} ${decision}` : `Change ${index + 1} back to pending`)
      const options = context.options()
      if (decision === "accepted") options.onAccept?.(index, h)
      else if (decision === "rejected") options.onReject?.(index, h)
      else options.onUndo?.(index, h)
      return true
    }

    const write = async (text: string) => {
      try {
        await navigator.clipboard.writeText(text)
      } catch {
        const area = document.createElement("textarea")
        area.value = text
        area.setAttribute("readonly", "")
        area.style.position = "fixed"
        area.style.opacity = "0"
        document.body.append(area)
        area.select()
        document.execCommand("copy")
        area.remove()
      }
    }

    const setView = (view: DiffView, event?: Event) => {
      if (view !== "unified" && view !== "split") throw new Error(`No view "${view}". Views: unified, split.`)
      if (view === store.get().view) return false
      return change("view", view, { reason: "item-press", event })
    }

    return {
      /** Shows "unified" or "split". */
      setView,
      /** Switches between unified and split. */
      toggleView: (event?: Event) => setView(store.get().view === "split" ? "unified" : "split", event),
      /** Opens a fold of unchanged lines, by its key ("g0", "g1", ...). */
      expandFold(key: string) {
        const s = store.get()
        const gap = s.model.gaps.find((g) => g.key === key)
        if (!gap) throw new Error(`No fold "${key}". Folds: ${s.model.gaps.map((g) => g.key).join(", ") || "none"}.`)
        if (!gap.lines || s.expanded.includes(key)) return false
        store.set({ expanded: [...s.expanded, key] })
        return true
      },
      /** Opens every fold that can be opened. */
      expandAll() {
        const s = store.get()
        const keys = s.model.gaps.filter((g) => g.lines && !s.expanded.includes(g.key)).map((g) => g.key)
        if (!keys.length) return false
        store.set({ expanded: [...s.expanded, ...keys] })
        return true
      },
      /** Closes every fold again. */
      collapseAll() {
        if (!store.get().expanded.length) return false
        store.set({ expanded: [] })
        return true
      },
      /** Accepts a hunk, by index. */
      accept: (index: number) => decide(index, "accepted"),
      /** Rejects a hunk, by index. */
      reject: (index: number) => decide(index, "rejected"),
      /** Takes a hunk's decision back. */
      undo: (index: number) => decide(index, undefined),
      /** Copies the new text (or the patch), shows "Copied" for two seconds and tells screen readers. */
      async copy() {
        const text = store.get().text
        await write(text)
        clearTimeout(timer)
        store.set({ copied: true })
        announce("Copied")
        context.options().onCopy?.(text)
        const el = context.element("copy")
        const speed = (el && parseFloat(getComputedStyle(el).getPropertyValue("--kf-speed"))) || 1
        timer = setTimeout(() => store.set({ copied: false }), 2000 * speed)
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { view: DiffView; narrow: boolean; copied: boolean }>({
      state: (state) => ({ view: state.shown, narrow: state.narrow, copied: state.copied }),
      attrs: (state) => ({
        "data-view": state.shown,
        "data-narrow": state.narrow ? "" : undefined,
        "data-switched": state.switched ? "" : undefined,
        "data-copied": state.copied ? "" : undefined,
        "data-review": state.review ? "" : undefined,
      }),
      /* Falls back to unified while the viewer is narrower than `splitMinWidth`. */
      bind: (el, part) => {
        if (typeof ResizeObserver === "undefined") return
        const check = () => {
          const narrow = el.getBoundingClientRect().width < part.store.get().splitMinWidth
          if (narrow !== part.store.get().narrow) part.store.set({ narrow })
        }
        check()
        const observer = new ResizeObserver(check)
        observer.observe(el)
        return () => observer.disconnect()
      },
    }),
    header: slot({}),
    title: slot<{}, { filename: string }>({
      state: (state) => ({ filename: state.filename }),
    }),
    /* The +added and −removed counts. Read out as words. */
    stats: slot<{}, { additions: number; deletions: number }>({
      state: (state) => ({ additions: state.additions, deletions: state.deletions }),
      attrs: (state) => ({
        role: "img",
        "aria-label": `${state.additions} ${state.additions === 1 ? "addition" : "additions"}, ${state.deletions} ${state.deletions === 1 ? "deletion" : "deletions"}`,
      }),
    }),
    actions: slot({}),
    /* The unified / split switch: two pressed-state buttons in a group. */
    "view-switch": slot<{}, { view: DiffView; narrow: boolean }>({
      role: "group",
      state: (state) => ({ view: state.shown, narrow: state.narrow }),
      attrs: (state) => ({
        "aria-label": "View",
        "data-view": state.shown,
        "data-narrow": state.narrow ? "" : undefined,
      }),
    }),
    "view-option": slot<{ value: string }, { selected: boolean; disabled: boolean }>({
      props: { value: "string" },
      role: "button",
      focus: "native",
      state: (state, part) => ({ selected: state.shown === part.key, disabled: part.key === "split" && state.narrow }),
      attrs: (state, part) => ({
        type: "button",
        "aria-pressed": String(state.shown === part.key),
        "data-selected": state.shown === part.key ? "" : undefined,
        "data-value": part.key,
        "aria-disabled": part.key === "split" && state.narrow ? "true" : undefined,
        "data-disabled": part.key === "split" && state.narrow ? "" : undefined,
      }),
      press: ({ api, key, store }, event) => {
        if (key === "split" && store.get().narrow) return
        void api.setView(key as DiffView, event)
      },
    }),
    copy: slot<{}, { copied: boolean }>({
      role: "button",
      focus: "native",
      state: (state) => ({ copied: state.copied }),
      attrs: (state) => ({
        type: "button",
        "aria-label": state.copied ? "Copied" : "Copy new version",
        "data-copied": state.copied ? "" : undefined,
      }),
      press: ({ api }) => void api.copy(),
    }),
    /* The scrolling body. Renders every block of the diff unless given children. */
    content: slot<{}, { model: DiffModel; view: DiffView; expanded: string[]; review: boolean; language: CodeBlockLanguage; wordDiff: boolean }>({
      state: (state) => ({
        model: state.model,
        view: state.shown,
        expanded: state.expanded,
        review: state.review,
        language: state.language,
        wordDiff: state.wordDiff,
      }),
      attrs: (state) => ({
        role: "region",
        tabindex: "0",
        dir: "ltr",
        "aria-label": state.filename ? `Changes to ${state.filename}` : "Changes",
        "data-view": state.shown,
      }),
    }),
    /* One hunk's lines. `--diff-hunk-index` gives its place, for a cascade. */
    hunk: slot<{ value: string }, { decision: DiffDecision | undefined; index: number }>({
      props: { value: "string" },
      state: (state, part) => ({ decision: state.decisions[part.key], index: Number(part.key) }),
      attrs: (state, part) => ({
        role: "group",
        "aria-label": `Change ${Number(part.key) + 1} of ${state.model.hunks.length}`,
        "data-decision": state.decisions[part.key],
        "data-hunk": part.key,
        style: css({ "--diff-hunk-index": Math.min(Number(part.key), 12) }),
      }),
    }),
    /* The row above a hunk: its fold, its range and the review actions. */
    "hunk-header": slot<{ value: string }, { hunk: DiffHunk | undefined; decision: DiffDecision | undefined; review: boolean }>({
      props: { value: "string" },
      state: (state, part) => ({ hunk: state.model.hunks[Number(part.key)], decision: state.decisions[part.key], review: state.review }),
      attrs: (state, part) => ({
        "data-decision": state.decisions[part.key],
        "data-hunk": part.key,
        style: css({ "--diff-hunk-index": Math.min(Number(part.key), 12) }),
      }),
    }),
    /* A folded run after the last hunk. */
    gap: slot<{ value: string }, { lines: number }>({
      props: { value: "string" },
      state: (state, part) => ({ lines: state.model.gaps.find((g) => g.key === part.key)?.count ?? 0 }),
      attrs: (state) => ({ style: css({ "--diff-hunk-index": Math.min(state.model.hunks.length, 12) }) }),
    }),
    /* The button that opens a fold. Disabled when its lines aren't known (a patch). */
    fold: slot<{ value: string }, { lines: number; expandable: boolean }>({
      props: { value: "string" },
      role: "button",
      focus: "native",
      state: (state, part) => {
        const gap = state.model.gaps.find((g) => g.key === part.key)
        return { lines: gap?.count ?? 0, expandable: !!gap?.lines }
      },
      attrs: (state, part) => {
        const gap = state.model.gaps.find((g) => g.key === part.key)
        return {
          type: "button",
          "aria-expanded": "false",
          "aria-label": `Show ${gap?.count ?? 0} unchanged ${gap?.count === 1 ? "line" : "lines"}`,
          "aria-disabled": gap?.lines ? undefined : "true",
          "data-disabled": gap?.lines ? undefined : "",
          "data-fold": part.key,
        }
      },
      press: ({ api, key }) => void api.expandFold(key),
    }),
    /* A fold's lines once opened. */
    expanded: slot<{ value: string }, {}>({
      props: { value: "string" },
      attrs: (_state, part) => ({ "data-fold": part.key }),
    }),
    accept: slot<{ value: string }, { decision: DiffDecision | undefined }>({
      props: { value: "string" },
      role: "button",
      focus: "native",
      present: (state, part) => state.review && !state.decisions[part.key],
      state: (state, part) => ({ decision: state.decisions[part.key] }),
      attrs: (_state, part) => ({ type: "button", "aria-label": `Accept change ${Number(part.key) + 1}` }),
      press: ({ api, key }) => void api.accept(Number(key)),
    }),
    reject: slot<{ value: string }, { decision: DiffDecision | undefined }>({
      props: { value: "string" },
      role: "button",
      focus: "native",
      present: (state, part) => state.review && !state.decisions[part.key],
      state: (state, part) => ({ decision: state.decisions[part.key] }),
      attrs: (_state, part) => ({ type: "button", "aria-label": `Reject change ${Number(part.key) + 1}` }),
      press: ({ api, key }) => void api.reject(Number(key)),
    }),
    /* The decision, once taken: "Accepted" or "Rejected". */
    status: slot<{ value: string }, { decision: DiffDecision | undefined }>({
      props: { value: "string" },
      present: (state, part) => state.review && !!state.decisions[part.key],
      state: (state, part) => ({ decision: state.decisions[part.key] }),
      attrs: (state, part) => ({ "data-decision": state.decisions[part.key] }),
    }),
    undo: slot<{ value: string }, { decision: DiffDecision | undefined }>({
      props: { value: "string" },
      role: "button",
      focus: "native",
      present: (state, part) => state.review && !!state.decisions[part.key],
      state: (state, part) => ({ decision: state.decisions[part.key] }),
      attrs: (_state, part) => ({ type: "button", "aria-label": `Undo decision on change ${Number(part.key) + 1}` }),
      press: ({ api, key }) => void api.undo(Number(key)),
    }),
  }),
  /* Agents read the file, the counts, the hunks and the folds, and change only what is shown.
     Accepting or rejecting an edit stays with the person reviewing it. */
  agent: { actions: ["setView", "toggleView", "expandFold", "expandAll", "collapseAll"] },
})

export {
  type DiffDecision,
  type DiffFoldSummary,
  type DiffHunkSummary,
  type DiffSegment,
  type DiffView,
  diffViewer,
  type DiffViewerOptions,
  type DiffViewerState,
  languageOf,
  segmentsOf,
}
export { buildDiff, type DiffBlock, type DiffGap, type DiffHunk, type DiffLine, type DiffModel, diffWords, parsePatch, type SplitRow, splitRows } from "@/components/keyframery/core/diff-viewer-diff-core"
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

**Vue**

```bash
npx shadcn-vue@latest add https://keyframery.com/r/vue/diff-viewer.json
```

This adds `components/keyframery/diff-viewer/` (one file per part, with the same part names as React) to your Vue or Nuxt project, installs UI SDK for Vue and adds the motion tokens to your global CSS. See [Install for Vue](/docs/installation/vue).

## Usage [#usage]

**React**

```tsx
import { DiffViewer } from "@/components/keyframery/diff-viewer"

export default function Usage() {
  return (
    <DiffViewer
      filename="src/config.ts"
      before={`export const config = {\n  retries: 2,\n  timeout: 5000,\n}\n`}
      after={`export const config = {\n  retries: 3,\n  timeout: 8000,\n}\n`}
    />
  )
}
```

**Vue**

```vue
<script setup lang="ts">
import { DiffViewer } from "@/components/keyframery/diff-viewer"
</script>

<template>
  <DiffViewer
    filename="src/config.ts"
    before="export const config = {
  retries: 2,
  timeout: 5000,
}
"
    after="export const config = {
  retries: 3,
  timeout: 8000,
}
"
  />
</template>
```

## Examples [#examples]

### Review an agent's edit [#review-an-agents-edit]

Pass `onAccept` and `onReject` and every hunk gets the two buttons. Each call carries the hunk's index, so you can apply or drop that part of the edit.

<ExamplePreview name="diff-viewer/review">
**React**

  ```tsx
  import * as React from "react"

  import { DiffViewer } from "@/components/keyframery/diff-viewer"

  const before = `export function formatPrice(cents: number) {
    return "$" + (cents / 100).toFixed(2)
  }

  export function formatDate(date: Date) {
    return date.toLocaleDateString()
  }
  `

  const after = `export function formatPrice(cents: number, currency = "USD") {
    return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(cents / 100)
  }

  export function formatDate(date: Date) {
    return date.toLocaleDateString("en-US", { dateStyle: "medium" })
  }
  `

  export default function DiffViewerReview() {
    const [log, setLog] = React.useState<string[]>([])
    return (
      <div className="w-full max-w-[640px] space-y-2">
        <DiffViewer
          filename="src/lib/format.ts"
          before={before}
          after={after}
          context={1}
          onAccept={(index) => setLog((l) => [...l, `Accepted change ${index + 1}`])}
          onReject={(index) => setLog((l) => [...l, `Rejected change ${index + 1}`])}
        />
        <p className="text-[12px] text-muted-foreground">{log.at(-1) ?? "Nothing reviewed yet"}</p>
      </div>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { ref } from "vue"

  import { DiffViewer } from "@/components/keyframery/diff-viewer"

  const before = `export function formatPrice(cents: number) {
    return "$" + (cents / 100).toFixed(2)
  }

  export function formatDate(date: Date) {
    return date.toLocaleDateString()
  }
  `
  const after = `export function formatPrice(cents: number, currency = "USD") {
    return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(cents / 100)
  }

  export function formatDate(date: Date) {
    return date.toLocaleDateString("en-US", { dateStyle: "medium" })
  }
  `

  const log = ref<string[]>([])
  </script>

  <template>
    <div class="w-full max-w-[640px] space-y-2">
      <DiffViewer
        filename="src/lib/format.ts"
        :before="before"
        :after="after"
        :context="1"
        @accept="(index) => log = [...log, `Accepted change ${index + 1}`]"
        @reject="(index) => log = [...log, `Rejected change ${index + 1}`]"
      />
      <p class="text-[12px] text-muted-foreground">{{ log.at(-1) ?? 'Nothing reviewed yet' }}</p>
    </div>
  </template>
  ```
</ExamplePreview>

### From a patch [#from-a-patch]

Give it the output of `git diff` instead of two texts. The file name comes from the patch; folds between hunks show how many lines they hide.

<ExamplePreview name="diff-viewer/patch">
**React**

  ```tsx
  import { DiffViewer } from "@/components/keyframery/diff-viewer"

  const patch = `diff --git a/styles/cart.css b/styles/cart.css
  --- a/styles/cart.css
  +++ b/styles/cart.css
  @@ -12,6 +12,7 @@ .cart {
   .price {
     font-weight: 500;
  -  color: #6b6b6b;
  +  color: var(--muted-foreground);
  +  font-variant-numeric: tabular-nums;
   }
   
   .total {
  @@ -40,3 +41,3 @@ .checkout {
   .checkout button {
  -  border-radius: 6px;
  +  border-radius: 10px;
   }
  `

  export default function DiffViewerPatch() {
    return <DiffViewer patch={patch} className="max-w-[560px]" />
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { DiffViewer } from "@/components/keyframery/diff-viewer"

  const patch = `diff --git a/styles/cart.css b/styles/cart.css
  --- a/styles/cart.css
  +++ b/styles/cart.css
  @@ -12,6 +12,7 @@ .cart {
   .price {
     font-weight: 500;
  -  color: #6b6b6b;
  +  color: var(--muted-foreground);
  +  font-variant-numeric: tabular-nums;
   }
   
   .total {
  @@ -40,3 +41,3 @@ .checkout {
   .checkout button {
  -  border-radius: 6px;
  +  border-radius: 10px;
   }
  `
  </script>

  <template>
    <DiffViewer :patch="patch" class="max-w-[560px]" />
  </template>
  ```
</ExamplePreview>

### Side by side [#side-by-side]

Start in the split view with `defaultView="split"`. Below `splitMinWidth` (640px by default) it shows as unified, so it still reads on a phone.

<ExamplePreview name="diff-viewer/split">
**React**

  ```tsx
  import { DiffViewer } from "@/components/keyframery/diff-viewer"

  const before = `{
    "name": "orders-api",
    "version": "1.4.0",
    "dependencies": {
      "zod": "^3.22.0"
    }
  }
  `

  const after = `{
    "name": "orders-api",
    "version": "1.5.0",
    "dependencies": {
      "zod": "^3.23.8",
      "pino": "^9.4.0"
    }
  }
  `

  export default function DiffViewerSplit() {
    return <DiffViewer filename="package.json" before={before} after={after} defaultView="split" lineNumbers={false} />
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { DiffViewer } from "@/components/keyframery/diff-viewer"

  const before = `{
    "name": "orders-api",
    "version": "1.4.0",
    "dependencies": {
      "zod": "^3.22.0"
    }
  }
  `
  const after = `{
    "name": "orders-api",
    "version": "1.5.0",
    "dependencies": {
      "zod": "^3.23.8",
      "pino": "^9.4.0"
    }
  }
  `
  </script>

  <template>
    <DiffViewer
      filename="package.json"
      :before="before"
      :after="after"
      default-view="split"
      :line-numbers="false"
    />
  </template>
  ```
</ExamplePreview>

## Motion [#motion]

| Move          | What you see                                                                                                           |
| ------------- | ---------------------------------------------------------------------------------------------------------------------- |
| **Direction** | Switching unified and split, the new layout fades in from the side of its button while the switch's key slides across. |
| **Height**    | An opened fold grows from its row to its lines, which fade in.                                                         |
| **Cascade**   | On mount, hunks rise in one after another (flourish).                                                                  |
| **Roll**      | The +added and −removed counts roll up to their values (flourish).                                                     |
| **Draw**      | Accepting a hunk swaps its buttons for a tick that draws itself; a rejected hunk steps back.                           |
| **Press**     | The view switch, review buttons and copy key sink under the press.                                                     |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this diff viewer moves, pass `speed`:

```tsx
<DiffViewer speed="fast">
  …
</DiffViewer>
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable                   | What it changes               | Default              |
| -------------------------- | ----------------------------- | -------------------- |
| `--diff-viewer-face`       | Sheet                         | bg-card              |
| `--diff-viewer-ink`        | Code text                     | text-card-foreground |
| `--diff-viewer-added`      | Added lines and words         | oklch(0.62 0.16 150) |
| `--diff-viewer-removed`    | Removed lines and words       | var(--destructive)   |
| `--diff-viewer-radius`     | Sheet corners                 | rounded-\[14px]      |
| `--diff-viewer-font`       | Code size                     | text-\[12.5px]       |
| `--diff-viewer-max-height` | Body height before it scrolls | none                 |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### DiffViewer [#diffviewer]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast it moves: \&#x22;fast\&#x22;, \&#x22;normal\&#x22;, \&#x22;slow\&#x22; or a multiplier.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;view&#x22;,&#x22;type&#x22;:&#x22;\&#x22;split\&#x22; | \&#x22;unified\&#x22;&#x22;,&#x22;full&#x22;:&#x22;DiffView&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;\&#x22;unified\&#x22; or \&#x22;split\&#x22;, controlled.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onCopy&#x22;,&#x22;type&#x22;:&#x22;(text: string) => void&#x22;,&#x22;full&#x22;:&#x22;(text: string) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Called with the text after the copy button copied it.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;language&#x22;,&#x22;type&#x22;:&#x22;\&#x22;text\&#x22; | \&#x22;html\&#x22; | \&#x22;ts\&#x22; | \&#x22;tsx\&#x22; | \&#x22;js\&#x22; | \&#x22;jsx\&#x22; | \&#x22;json\&#x22; | \&#x22;css\&#x22; | \&#x22;bash\&#x22;&#x22;,&#x22;full&#x22;:&#x22;CodeBlockLanguage&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Which tokenizer colours the code: \&#x22;ts\&#x22;, \&#x22;tsx\&#x22;, \&#x22;js\&#x22;, \&#x22;jsx\&#x22;, \&#x22;json\&#x22;, \&#x22;css\&#x22;, \&#x22;html\&#x22;, \&#x22;bash\&#x22; or \&#x22;text\&#x22;. Guessed from the file name by default.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;before&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The file before the change. With after, the diff is computed in the browser (Myers, no package).&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;after&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The file after the change. Also what the copy button copies.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;patch&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A unified diff (git diff), used when before and after are left out. Folds between its hunks show their size but can't open.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;filename&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The file name in the header. Read from the patch when left out.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultView&#x22;,&#x22;type&#x22;:&#x22;\&#x22;split\&#x22; | \&#x22;unified\&#x22;&#x22;,&#x22;full&#x22;:&#x22;DiffView&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The view at first, when uncontrolled. Defaults to \&#x22;unified\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onViewChange&#x22;,&#x22;type&#x22;:&#x22;(view: DiffView) => void&#x22;,&#x22;full&#x22;:&#x22;(view: DiffView) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Called with the view someone (or an agent) switched to.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;splitMinWidth&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Below this width in pixels the split view shows as unified. Defaults to 640.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;context&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Unchanged lines kept around each change. Defaults to 3.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;wordDiff&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Marks the words that changed inside a changed line. Defaults to true.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;review&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Shows Accept and Reject on every hunk. On by default when onAccept or onReject is given.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onAccept&#x22;,&#x22;type&#x22;:&#x22;(index: number, hunk: DiffHunk) => void&#x22;,&#x22;full&#x22;:&#x22;(index: number, hunk: DiffHunk) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Called with the hunk's index and the hunk when the reviewer accepts it.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onReject&#x22;,&#x22;type&#x22;:&#x22;(index: number, hunk: DiffHunk) => void&#x22;,&#x22;full&#x22;:&#x22;(index: number, hunk: DiffHunk) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Called with the hunk's index and the hunk when the reviewer rejects it.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onUndo&#x22;,&#x22;type&#x22;:&#x22;(index: number, hunk: DiffHunk) => void&#x22;,&#x22;full&#x22;:&#x22;(index: number, hunk: DiffHunk) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Called with the hunk's index and the hunk when the reviewer takes a decision back.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;lineNumbers&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Shows the old and new line numbers. Defaults to true.&#x22;,&#x22;required&#x22;:false}]" />

### DiffViewerBlocks [#diffviewerblocks]

<PropsTable rows="[{&#x22;name&#x22;:&#x22;blocks&#x22;,&#x22;type&#x22;:&#x22;DiffBlock[]&#x22;,&#x22;full&#x22;:&#x22;DiffBlock[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;view&#x22;,&#x22;type&#x22;:&#x22;\&#x22;split\&#x22; | \&#x22;unified\&#x22;&#x22;,&#x22;full&#x22;:&#x22;DiffView&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;expanded&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;review&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;language&#x22;,&#x22;type&#x22;:&#x22;\&#x22;text\&#x22; | \&#x22;html\&#x22; | \&#x22;ts\&#x22; | \&#x22;tsx\&#x22; | \&#x22;js\&#x22; | \&#x22;jsx\&#x22; | \&#x22;json\&#x22; | \&#x22;css\&#x22; | \&#x22;bash\&#x22;&#x22;,&#x22;full&#x22;:&#x22;CodeBlockLanguage&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;words&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true}]" />

### DiffViewerLines [#diffviewerlines]

<PropsTable rows="[{&#x22;name&#x22;:&#x22;lines&#x22;,&#x22;type&#x22;:&#x22;DiffLine[]&#x22;,&#x22;full&#x22;:&#x22;DiffLine[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;view&#x22;,&#x22;type&#x22;:&#x22;\&#x22;split\&#x22; | \&#x22;unified\&#x22;&#x22;,&#x22;full&#x22;:&#x22;DiffView&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;language&#x22;,&#x22;type&#x22;:&#x22;\&#x22;text\&#x22; | \&#x22;html\&#x22; | \&#x22;ts\&#x22; | \&#x22;tsx\&#x22; | \&#x22;js\&#x22; | \&#x22;jsx\&#x22; | \&#x22;json\&#x22; | \&#x22;css\&#x22; | \&#x22;bash\&#x22;&#x22;,&#x22;full&#x22;:&#x22;CodeBlockLanguage&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;words&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true}]" />

### DiffViewerViewOption [#diffviewerviewoption]

Renders a `<button>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;value&#x22;,&#x22;type&#x22;:&#x22;\&#x22;split\&#x22; | \&#x22;unified\&#x22;&#x22;,&#x22;full&#x22;:&#x22;DiffView&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;\&#x22;unified\&#x22; or \&#x22;split\&#x22;.&#x22;,&#x22;required&#x22;:true}]" />

### Other parts [#other-parts]

These take the props of the element they render, and nothing else:

* `DiffViewerActions`: a `<div>`
* `DiffViewerContent`: a `<div>`
* `DiffViewerCopyButton`: a `<button>`
* `DiffViewerHeader`: a `<div>`
* `DiffViewerStats`: a `<div>`
* `DiffViewerTitle`: a `<div>`
* `DiffViewerViewSwitch`: a `<div>`
* `DiffViewerAccept`: a `<button>`
* `DiffViewerExpanded`: a `<div>`
* `DiffViewerFold`: a `<button>`
* `DiffViewerGap`: a `<div>`
* `DiffViewerHunk`: a `<div>`
* `DiffViewerHunkHeader`: a `<div>`
* `DiffViewerReject`: a `<button>`
* `DiffViewerStatus`: a `<span>`
* `DiffViewerUndo`: a `<button>`

## Keyboard [#keyboard]

| Key                       | What it does                                                                                              |
| ------------------------- | --------------------------------------------------------------------------------------------------------- |
| <kbd>Tab</kbd>            | Moves to the view switch, the copy button, the body (so it can scroll), then each fold and review button. |
| <kbd>← → ↑ ↓</kbd>        | Scroll the diff while the body has focus.                                                                 |
| <kbd>Enter or Space</kbd> | Presses the focused button: switch view, open a fold, accept, reject, undo or copy.                       |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a diff viewer, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/diff-viewer-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/diff-viewer`.

## Questions

### How does the animated Diff Viewer for UI SDK move?

Direction: Switching unified and split, the new layout fades in from the side of its button while the switch's key slides across. Height: An opened fold grows from its row to its lines, which fade in. Cascade: On mount, hunks rise in one after another (flourish). Roll: The +added and −removed counts roll up to their values (flourish). Draw: Accepting a hunk swaps its buttons for a tick that draws itself; a rejected hunk steps back. Press: The view switch, review buttons and copy key sink under the press.

### Do I need Motion or Framer Motion for the animated Diff Viewer?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no diff viewer. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/diff-viewer-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Diff Viewer when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
