# #134 — Side-by-Side Diff Viewer

> Precision code diff inspector with inline character highlights, hunk jump controls, whitespace toggle, and mobile unified view.

## Metadata

- **Index**: #134
- **Slug**: `side-by-side-diff-viewer`
- **Kind**: `ui`
- **Family**: Developer & Code
- **Theme**: `light`
- **Mobile Strength**: `high`
- **Tags**: `diff-viewer`, `code-review`, `side-by-side`, `unified-diff`, `developer-tools`, `syntax`
- **Best For**: Pull request and code review platforms, CMS revision and legal document comparisons, Config drift and infrastructure diff tools, AI patch review interfaces
- **Real-World Inspiration**: [Kaleidoscope](https://kaleidoscope.app/)
- **Detail Page**: https://templates.michaelpitts.net/t/side-by-side-diff-viewer
- **Live Demo**: https://templates.michaelpitts.net/demos/side-by-side-diff-viewer.html
- **JSON API**: https://templates.michaelpitts.net/api/templates/side-by-side-diff-viewer

## Why This Aesthetic Is Unique

Highlights exact word-level deltas inside split additions and deletions on desktop, then automatically switches to a clean unified diff stream with toggleable split mode on mobile.

## Color Palette

| Role | Name | Hex |
|------|------|-----|
| `canvas` | Cool Paper | `#F8FAFC` |
| `surface` | Diff Surface | `#FFFFFF` |
| `ink` | Slate Ink | `#0F172A` |
| `accent` | Addition Emerald | `#059669` |
| `muted` | Line-Number Gray | `#64748B` |

## Typography

- **Display**: `Inter`
- **Body**: `Inter`
- **Mono**: `JetBrains Mono`
- **Scale Notes**: 12.5px/1.6 monospace diff rows with tabular line numbers, 13px sans file header and hunk navigation pills.
- **Google Fonts**: https://fonts.googleapis.com/css2?family=Inter:wght@500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap
  ```html
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap">
  ```

## Layout Architecture

Two synchronized code columns with dual line-number gutters on desktop; automatic single-column unified diff mode on narrow screens with manual Split/Unified switcher.

## Interaction & Micro-Motion Rules

Next/Prev hunk buttons jump and highlight changed blocks, Ignore Whitespace filters noise live, and users can switch files or review/approve hunks.

## Mobile & Responsive Rules

Defaults to Unified mode on 390px viewports with wrapped or contained code scrolling and >=44px hunk-jump controls.

## Agent Guardrails

### DO
- Auto-default to Unified diff mode on viewports under 768px while keeping a manual toggle.
- Pair green/red background tints with explicit + and - prefixes for color-blind accessibility.
- Provide Next/Previous hunk navigation so reviewers can jump straight to changes.

### DON'T
- Never rely solely on red/green hue without textual +/− markers.
- Avoid overflowing the outer page when long code lines appear in a diff row.

## Complete Standalone Starter Code

File: `demos/side-by-side-diff-viewer.html`

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>PrismDiff — Side-by-Side Code Diff Viewer</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg: #f1f5f9;
      --surface: #ffffff;
      --surface-subtle: #f8fafc;
      --ink: #0f172a;
      --ink-muted: #475569;
      --ink-faint: #94a3b8;
      --border: #e2e8f0;
      --border-strong: #cbd5e1;

      --add-bg: #ecfdf5;
      --add-gutter: #d1fae5;
      --add-mark: #a7f3d0;
      --add-ink: #065f46;
      --add-sign: #059669;

      --del-bg: #fff1f2;
      --del-gutter: #ffe4e6;
      --del-mark: #fecdd3;
      --del-ink: #881337;
      --del-sign: #e11d48;

      --hunk-bg: #eef2ff;
      --hunk-border: #c7d2fe;
      --hunk-ink: #3730a3;
      --accent: #4f46e5;

      --font-sans: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
      --font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;
    }

    * { box-sizing: border-box; margin: 0; padding: 0; }

    html, body {
      min-height: 100%;
      background: var(--bg);
      color: var(--ink);
      font-family: var(--font-sans);
      -webkit-font-smoothing: antialiased;
      overflow-x: hidden;
    }

    .shell {
      max-width: 1360px;
      margin: 0 auto;
      padding: 18px 20px 36px;
      display: flex;
      flex-direction: column;
      gap: 14px;
    }

    /* Header Bar */
    .topbar {
      background: var(--surface);
      border: 1px solid var(--border);
      border-radius: 12px;
      padding: 12px 16px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 14px;
      flex-wrap: wrap;
      box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
    }

    .file-identity {
      display: flex;
      align-items: center;
      gap: 12px;
      min-width: 0;
    }

    .brand-badge {
      width: 34px;
      height: 34px;
      border-radius: 8px;
      background: linear-gradient(135deg, #0f172a, #334155);
      color: #fff;
      display: grid;
      place-items: center;
      flex-shrink: 0;
    }

    .file-meta {
      min-width: 0;
    }

    .file-path {
      font-family: var(--font-mono);
      font-size: 13.5px;
      font-weight: 600;
      color: var(--ink);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .commit-sub {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-top: 3px;
      font-size: 12px;
      color: var(--ink-muted);
      flex-wrap: wrap;
    }

    .sha-pill {
      font-family: var(--font-mono);
      font-size: 11px;
      background: var(--surface-subtle);
      border: 1px solid var(--border);
      padding: 1px 6px;
      border-radius: 4px;
      color: var(--ink-muted);
    }

    .stat-add {
      color: var(--add-sign);
      font-family: var(--font-mono);
      font-weight: 600;
    }

    .stat-del {
      color: var(--del-sign);
      font-family: var(--font-mono);
      font-weight: 600;
    }

    /* Controls */
    .controls {
      display: flex;
      align-items: center;
      gap: 8px;
      flex-wrap: wrap;
    }

    .segmented {
      display: inline-flex;
      background: var(--bg);
      padding: 3px;
      border-radius: 8px;
      border: 1px solid var(--border);
    }

    .seg-btn {
      appearance: none;
      border: none;
      background: transparent;
      color: var(--ink-muted);
      font-family: var(--font-sans);
      font-size: 12.5px;
      font-weight: 500;
      padding: 0 12px;
      min-height: 36px;
      border-radius: 6px;
      cursor: pointer;
      transition: background 0.15s, color 0.15s, box-shadow 0.15s;
    }

    .seg-btn.active {
      background: var(--surface);
      color: var(--ink);
      box-shadow: 0 1px 2px rgba(15, 23, 42, 0.08);
    }

    .ctrl-btn {
      appearance: none;
      border: 1px solid var(--border);
      background: var(--surface);
      color: var(--ink-muted);
      font-family: var(--font-sans);
      font-size: 12.5px;
      font-weight: 500;
      padding: 0 11px;
      min-height: 38px;
      border-radius: 8px;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 6px;
      transition: background 0.15s, border-color 0.15s, color 0.15s;
      white-space: nowrap;
    }

    .ctrl-btn:hover {
      background: var(--surface-subtle);
      color: var(--ink);
      border-color: var(--border-strong);
    }

    .ctrl-btn.active {
      background: var(--hunk-bg);
      color: var(--hunk-ink);
      border-color: var(--hunk-border);
    }

    .hunk-nav {
      display: inline-flex;
      align-items: center;
      border: 1px solid var(--border);
      border-radius: 8px;
      background: var(--surface);
      overflow: hidden;
    }

    .hunk-nav button {
      appearance: none;
      border: none;
      background: transparent;
      color: var(--ink-muted);
      width: 36px;
      min-height: 36px;
      cursor: pointer;
      display: grid;
      place-items: center;
      transition: background 0.12s, color 0.12s;
    }

    .hunk-nav button:hover {
      background: var(--surface-subtle);
      color: var(--ink);
    }

    .hunk-counter {
      font-family: var(--font-mono);
      font-size: 11.5px;
      color: var(--ink-muted);
      padding: 0 10px;
      border-left: 1px solid var(--border);
      border-right: 1px solid var(--border);
      white-space: nowrap;
    }

    /* Diff Card */
    .diff-card {
      background: var(--surface);
      border: 1px solid var(--border);
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(15, 23, 42, 0.04);
    }

    .diff-col-headers {
      display: grid;
      grid-template-columns: 1fr 1fr;
      background: var(--surface-subtle);
      border-bottom: 1px solid var(--border);
      font-size: 12px;
      font-weight: 600;
      color: var(--ink-muted);
    }

    .diff-col-headers.unified {
      grid-template-columns: 1fr;
    }

    .col-hdr {
      padding: 9px 14px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 8px;
    }

    .col-hdr + .col-hdr {
      border-left: 1px solid var(--border);
    }

    .col-tag {
      font-family: var(--font-mono);
      font-size: 11px;
      font-weight: 500;
      padding: 2px 7px;
      border-radius: 99px;
      background: var(--bg);
      color: var(--ink-muted);
    }

    .diff-scroll {
      width: 100%;
      overflow-x: auto;
    }

    .diff-table {
      width: 100%;
      border-collapse: collapse;
      table-layout: fixed;
      font-family: var(--font-mono);
      font-size: 12.5px;
      line-height: 1.6;
    }

    /* Split Table Columns */
    .diff-table.split .col-ln { width: 46px; }
    .diff-table.split .col-sign { width: 22px; }
    .diff-table.split .col-code { width: calc(50% - 68px); }

    /* Unified Table Columns */
    .diff-table.unified .col-ln { width: 42px; }
    .diff-table.unified .col-sign { width: 22px; }
    .diff-table.unified .col-code { width: auto; }

    .diff-table td {
      vertical-align: top;
      padding: 2px 0;
    }

    .ln {
      text-align: right;
      padding: 2px 8px !important;
      color: var(--ink-faint);
      user-select: none;
      font-size: 11.5px;
      background: var(--surface-subtle);
      border-right: 1px solid var(--border);
    }

    .sign {
      text-align: center;
      user-select: none;
      font-weight: 600;
    }

    .code {
      padding: 2px 10px 2px 4px !important;
      white-space: pre;
      overflow-x: auto;
      scrollbar-width: none;
    }
    .code::-webkit-scrollbar { display: none; }

    .wrap-on .code {
      white-space: pre-wrap;
      word-break: break-word;
    }

    .split-mid {
      border-left: 1px solid var(--border);
    }

    /* Line States */
    .cell-add { background: var(--add-bg); color: var(--add-ink); }
    .cell-add-ln { background: var(--add-gutter); color: var(--add-sign); }
    .cell-add-sign { background: var(--add-bg); color: var(--add-sign); }

    .cell-del { background: var(--del-bg); color: var(--del-ink); }
    .cell-del-ln { background: var(--del-gutter); color: var(--del-sign); }
    .cell-del-sign { background: var(--del-bg); color: var(--del-sign); }

    .cell-empty {
      background: repeating-linear-gradient(
        -45deg,
        #f8fafc,
        #f8fafc 6px,
        #f1f5f9 6px,
        #f1f5f9 12px
      );
    }

    mark.ch-add {
      background: var(--add-mark);
      color: var(--add-ink);
      border-radius: 2px;
      padding: 0 1px;
    }

    mark.ch-del {
      background: var(--del-mark);
      color: var(--del-ink);
      border-radius: 2px;
      padding: 0 1px;
    }

    /* Hunk Header Row */
    .hunk-row td {
      background: var(--hunk-bg);
      color: var(--hunk-ink);
      border-top: 1px solid var(--hunk-border);
      border-bottom: 1px solid var(--hunk-border);
      padding: 7px 14px !important;
      font-family: var(--font-mono);
      font-size: 12px;
      font-weight: 500;
    }

    .hunk-row.active-hunk td {
      box-shadow: inset 4px 0 0 var(--accent);
      background: #e0e7ff;
    }

    .hunk-row-inner {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      flex-wrap: wrap;
    }

    .hunk-label {
      font-family: var(--font-sans);
      font-size: 11.5px;
      font-weight: 600;
      color: var(--accent);
      background: rgba(79, 70, 229, 0.1);
      padding: 2px 8px;
      border-radius: 99px;
    }

    .expand-row td {
      background: var(--surface-subtle);
      border-top: 1px dashed var(--border);
      border-bottom: 1px dashed var(--border);
      padding: 0 !important;
    }

    .expand-btn {
      width: 100%;
      appearance: none;
      border: none;
      background: transparent;
      color: var(--ink-muted);
      font-family: var(--font-sans);
      font-size: 12px;
      font-weight: 500;
      min-height: 36px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
    }
    .expand-btn:hover {
      background: var(--bg);
      color: var(--ink);
    }

    .kbd-hint {
      font-size: 12px;
      color: var(--ink-muted);
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      padding: 0 4px;
    }

    kbd {
      font-family: var(--font-mono);
      font-size: 11px;
      background: var(--surface);
      border: 1px solid var(--border-strong);
      border-radius: 4px;
      padding: 1px 5px;
      color: var(--ink);
    }

    /* Mobile Responsive (390px) */
    @media (max-width: 780px) {
      .shell {
        padding: 10px 10px 24px;
        gap: 10px;
      }

      .topbar {
        padding: 12px;
        gap: 10px;
      }

      .controls {
        width: 100%;
        justify-content: space-between;
      }

      .seg-btn, .ctrl-btn {
        min-height: 44px;
      }

      .hunk-nav button {
        width: 44px;
        min-height: 44px;
      }

      .expand-btn {
        min-height: 44px;
      }

      .diff-table.unified .col-ln {
        width: 34px;
      }

      .ln {
        padding: 2px 5px !important;
        font-size: 10.5px;
      }

      .diff-table {
        font-size: 12px;
      }

      .kbd-hint {
        display: none;
      }
    }
  </style>
</head>
<body>
  <div class="shell">
    <header class="topbar">
      <div class="file-identity">
        <div class="brand-badge" aria-hidden="true">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 3v18M5 8h4M7 6v4M15 16h4"/></svg>
        </div>
        <div class="file-meta">
          <div class="file-path">src/cache/lru-store.ts</div>
          <div class="commit-sub">
            <span class="sha-pill">a94c1f2 → e31b8d0</span>
            <span id="statAdd" class="stat-add">+0</span>
            <span id="statDel" class="stat-del">-0</span>
            <span id="wsNote"></span>
          </div>
        </div>
      </div>

      <div class="controls">
        <div class="segmented" role="group" aria-label="Diff view mode">
          <button id="btnSplit" class="seg-btn active" type="button">Split</button>
          <button id="btnUnified" class="seg-btn" type="button">Unified</button>
        </div>

        <button id="btnWhitespace" class="ctrl-btn" type="button" aria-pressed="false">
          Ignore WS
        </button>

        <button id="btnWrap" class="ctrl-btn active" type="button" aria-pressed="true">
          Wrap
        </button>

        <div class="hunk-nav" aria-label="Hunk navigation">
          <button id="btnPrevHunk" type="button" title="Previous hunk (k)" aria-label="Previous hunk">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M18 15l-6-6-6 6"/></svg>
          </button>
          <span id="hunkCounter" class="hunk-counter">1 / 3</span>
          <button id="btnNextHunk" type="button" title="Next hunk (j)" aria-label="Next hunk">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M6 9l6 6 6-6"/></svg>
          </button>
        </div>
      </div>
    </header>

    <main id="diffCard" class="diff-card wrap-on">
      <div id="colHeaders" class="diff-col-headers"></div>
      <div class="diff-scroll">
        <table id="diffTable" class="diff-table split" aria-label="Code diff"></table>
      </div>
    </main>

    <div class="kbd-hint">
      <span>Press <kbd>j</kbd> / <kbd>k</kbd> to jump between hunks · Toggle <strong>Ignore WS</strong> to collapse formatting-only lines</span>
      <span id="modeHint">Auto-switches to Unified below 780px</span>
    </div>
  </div>

  <script>
    // Structured realistic diff hunks for src/cache/lru-store.ts
    // Includes modified pairs (for inline char diff), pure adds/deletes, whitespace-only diffs, and collapsible context.
    const HUNKS = [
      {
        id: 'hunk-1',
        header: '@@ -12,11 +12,15 @@ export interface CacheOptions',
        label: 'TTL & Telemetry Options',
        rows: [
          { type: 'ctx', o: 12, n: 12, left: 'export interface CacheOptions {', right: 'export interface CacheOptions {' },
          { type: 'mod', o: 13, n: 13, left: '  maxEntries: number;', right: '  maxEntries: number;' , wsOnly: false, forceCtx: true },
          { type: 'mod', o: 14, n: 14, left: '  ttlMs?: number;', right: '  defaultTtlMs?: number;' },
          { type: 'add', n: 15, right: '  staleWhileRevalidateMs?: number;' },
          { type: 'add', n: 16, right: '  onEvict?: (key: string, reason: EvictReason) => void;' },
          { type: 'ctx', o: 15, n: 17, left: '}', right: '}' },
          { type: 'mod', o: 16, n: 18, left: '  const DEFAULT_LIMIT = 512;', right: 'const DEFAULT_LIMIT = 512;', wsOnly: true },
          { type: 'mod', o: 17, n: 19, left: 'const DEFAULT_TTL_MS = 60_000;', right: 'const DEFAULT_TTL_MS = 120_000;' },
        ]
      },
      {
        id: 'hunk-2',
        header: '@@ -41,12 +45,14 @@ export class LruStore<T>',
        label: 'Lazy Expiration on Read',
        collapsedBefore: [
          { o: 34, n: 38, text: '  private readonly map = new Map<string, CacheNode<T>>();' },
          { o: 35, n: 39, text: '  private hits = 0;' },
          { o: 36, n: 40, text: '  private misses = 0;' },
          { o: 37, n: 41, text: '' },
          { o: 38, n: 42, text: '  constructor(private readonly opts: CacheOptions) {}' },
          { o: 39, n: 43, text: '' },
        ],
        rows: [
          { type: 'ctx', o: 41, n: 45, left: '  get(key: string): T | undefined {', right: '  get(key: string): T | undefined {' },
          { type: 'ctx', o: 42, n: 46, left: '    const node = this.map.get(key);', right: '    const node = this.map.get(key);' },
          { type: 'del', o: 43, left: '    if (!node) return undefined;' },
          { type: 'add', n: 47, right: '    if (!node) {' },
          { type: 'add', n: 48, right: '      this.misses += 1;' },
          { type: 'add', n: 49, right: '      return undefined;' },
          { type: 'add', n: 50, right: '    }' },
          { type: 'mod', o: 44, n: 51, left: '    if (node.expiresAt < Date.now()) {', right: '    if (node.expiresAt <= performance.now()) {' },
          { type: 'mod', o: 45, n: 52, left: '      this.map.delete(key);', right: '      this.evict(key, "expired");' },
          { type: 'ctx', o: 46, n: 53, left: '      return undefined;', right: '      return undefined;' },
          { type: 'ctx', o: 47, n: 54, left: '    }', right: '    }' },
          { type: 'mod', o: 48, n: 55, left: '    this.touch(key, node);', right: '    this.promote(key, node);' },
          { type: 'add', n: 56, right: '    this.hits += 1;' },
          { type: 'ctx', o: 49, n: 57, left: '    return node.value;', right: '    return node.value;' },
        ]
      },
      {
        id: 'hunk-3',
        header: '@@ -78,9 +86,12 @@ export class LruStore<T>',
        label: 'Eviction Hook & Hit Ratio',
        rows: [
          { type: 'ctx', o: 78, n: 86, left: '  private evictOldest(): void {', right: '  private evictOldest(): void {' },
          { type: 'mod', o: 79, n: 87, left: '    const oldestKey = this.map.keys().next().value;', right: '    const oldestKey =  this.map.keys().next().value;', wsOnly: true },
          { type: 'mod', o: 80, n: 88, left: '    if (oldestKey) this.map.delete(oldestKey);', right: '    if (oldestKey) this.evict(oldestKey, "capacity");' },
          { type: 'ctx', o: 81, n: 89, left: '  }', right: '  }' },
          { type: 'add', n: 90, right: '' },
          { type: 'add', n: 91, right: '  stats(): { size: number; hitRate: number } {' },
          { type: 'add', n: 92, right: '    const total = this.hits + this.misses;' },
          { type: 'add', n: 93, right: '    return { size: this.map.size, hitRate: total ? this.hits / total : 0 };' },
          { type: 'add', n: 94, right: '  }' },
        ]
      }
    ];

    const state = {
      mode: window.innerWidth <= 780 ? 'unified' : 'split',
      userPinnedMode: false,
      ignoreWhitespace: false,
      wrap: true,
      activeHunk: 0,
      expandedHunks: new Set()
    };

    const diffTable = document.getElementById('diffTable');
    const colHeaders = document.getElementById('colHeaders');
    const diffCard = document.getElementById('diffCard');
    const btnSplit = document.getElementById('btnSplit');
    const btnUnified = document.getElementById('btnUnified');
    const btnWhitespace = document.getElementById('btnWhitespace');
    const btnWrap = document.getElementById('btnWrap');
    const hunkCounter = document.getElementById('hunkCounter');

    function esc(s) {
      return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }

    // Inline character diff via common prefix + common suffix
    function inlineCharDiff(oldStr, newStr) {
      let start = 0;
      const minLen = Math.min(oldStr.length, newStr.length);
      while (start < minLen && oldStr[start] === newStr[start]) start++;

      let oldEnd = oldStr.length - 1;
      let newEnd = newStr.length - 1;
      while (oldEnd >= start && newEnd >= start && oldStr[oldEnd] === newStr[newEnd]) {
        oldEnd--;
        newEnd--;
      }

      const oldPre = esc(oldStr.slice(0, start));
      const oldMid = esc(oldStr.slice(start, oldEnd + 1));
      const oldSuf = esc(oldStr.slice(oldEnd + 1));

      const newPre = esc(newStr.slice(0, start));
      const newMid = esc(newStr.slice(start, newEnd + 1));
      const newSuf = esc(newStr.slice(newEnd + 1));

      return {
        leftHtml: oldMid ? `${oldPre}<mark class="ch-del">${oldMid}</mark>${oldSuf}` : esc(oldStr),
        rightHtml: newMid ? `${newPre}<mark class="ch-add">${newMid}</mark>${newSuf}` : esc(newStr)
      };
    }

    function effectiveType(row) {
      if (row.forceCtx) return 'ctx';
      if (row.type === 'mod' && row.wsOnly && state.ignoreWhitespace) return 'ctx';
      return row.type;
    }

    function render() {
      const isSplit = state.mode === 'split';
      btnSplit.classList.toggle('active', isSplit);
      btnUnified.classList.toggle('active', !isSplit);
      btnWhitespace.classList.toggle('active', state.ignoreWhitespace);
      btnWhitespace.setAttribute('aria-pressed', String(state.ignoreWhitespace));
      btnWrap.classList.toggle('active', state.wrap);
      btnWrap.setAttribute('aria-pressed', String(state.wrap));
      diffCard.classList.toggle('wrap-on', state.wrap);

      colHeaders.className = `diff-col-headers ${isSplit ? 'split' : 'unified'}`;
      colHeaders.innerHTML = isSplit
        ? `<div class="col-hdr"><span>Base · main</span><span class="col-tag">a94c1f2</span></div>
           <div class="col-hdr"><span>Head · feat/lru-telemetry</span><span class="col-tag">e31b8d0</span></div>`
        : `<div class="col-hdr"><span>Unified Diff · main → feat/lru-telemetry</span><span class="col-tag">3 hunks</span></div>`;

      let adds = 0;
      let dels = 0;
      let wsHidden = 0;

      const colgroup = isSplit
        ? `<colgroup>
             <col class="col-ln"><col class="col-sign"><col class="col-code">
             <col class="col-ln"><col class="col-sign"><col class="col-code">
           </colgroup>`
        : `<colgroup>
             <col class="col-ln"><col class="col-ln"><col class="col-sign"><col class="col-code">
           </colgroup>`;

      const colspan = isSplit ? 6 : 4;
      let tbody = '<tbody>';

      HUNKS.forEach((hunk, hIdx) => {
        // Optional collapsed context expander
        if (hunk.collapsedBefore) {
          if (state.expandedHunks.has(hunk.id)) {
            hunk.collapsedBefore.forEach(c => {
              if (isSplit) {
                tbody += `<tr>
                  <td class="ln">${c.o}</td><td class="sign"></td><td class="code">${esc(c.text)}</td>
                  <td class="ln split-mid">${c.n}</td><td class="sign"></td><td class="code">${esc(c.text)}</td>
                </tr>`;
              } else {
                tbody += `<tr>
                  <td class="ln">${c.o}</td><td class="ln">${c.n}</td><td class="sign"></td><td class="code">${esc(c.text)}</td>
                </tr>`;
              }
            });
          } else {
            tbody += `<tr class="expand-row"><td colspan="${colspan}">
              <button class="expand-btn" type="button" data-expand="${hunk.id}">
                ↕ Show ${hunk.collapsedBefore.length} unchanged context lines
              </button>
            </td></tr>`;
          }
        }

        const isActive = hIdx === state.activeHunk;
        tbody += `<tr id="${hunk.id}" class="hunk-row ${isActive ? 'active-hunk' : ''}">
          <td colspan="${colspan}">
            <div class="hunk-row-inner">
              <span>${esc(hunk.header)}</span>
              <span class="hunk-label">${esc(hunk.label)}</span>
            </div>
          </td>
        </tr>`;

        hunk.rows.forEach(row => {
          const t = effectiveType(row);
          if (row.wsOnly && state.ignoreWhitespace) wsHidden++;

          if (t === 'ctx') {
            const text = esc(row.right ?? row.left);
            if (isSplit) {
              tbody += `<tr>
                <td class="ln">${row.o}</td><td class="sign"></td><td class="code">${text}</td>
                <td class="ln split-mid">${row.n}</td><td class="sign"></td><td class="code">${text}</td>
              </tr>`;
            } else {
              tbody += `<tr>
                <td class="ln">${row.o}</td><td class="ln">${row.n}</td><td class="sign"></td><td class="code">${text}</td>
              </tr>`;
            }
          } else if (t === 'mod') {
            adds++; dels++;
            const { leftHtml, rightHtml } = inlineCharDiff(row.left, row.right);
            if (isSplit) {
              tbody += `<tr>
                <td class="ln cell-del-ln">${row.o}</td><td class="sign cell-del-sign">-</td><td class="code cell-del">${leftHtml}</td>
                <td class="ln split-mid cell-add-ln">${row.n}</td><td class="sign cell-add-sign">+</td><td class="code cell-add">${rightHtml}</td>
              </tr>`;
            } else {
              tbody += `<tr>
                <td class="ln cell-del-ln">${row.o}</td><td class="ln cell-del-ln"></td><td class="sign cell-del-sign">-</td><td class="code cell-del">${leftHtml}</td>
              </tr>
              <tr>
                <td class="ln cell-add-ln"></td><td class="ln cell-add-ln">${row.n}</td><td class="sign cell-add-sign">+</td><td class="code cell-add">${rightHtml}</td>
              </tr>`;
            }
          } else if (t === 'del') {
            dels++;
            if (isSplit) {
              tbody += `<tr>
                <td class="ln cell-del-ln">${row.o}</td><td class="sign cell-del-sign">-</td><td class="code cell-del">${esc(row.left)}</td>
                <td class="ln split-mid cell-empty"></td><td class="sign cell-empty"></td><td class="code cell-empty"></td>
              </tr>`;
            } else {
              tbody += `<tr>
                <td class="ln cell-del-ln">${row.o}</td><td class="ln cell-del-ln"></td><td class="sign cell-del-sign">-</td><td class="code cell-del">${esc(row.left)}</td>
              </tr>`;
            }
          } else if (t === 'add') {
            adds++;
            if (isSplit) {
              tbody += `<tr>
                <td class="ln cell-empty"></td><td class="sign cell-empty"></td><td class="code cell-empty"></td>
                <td class="ln split-mid cell-add-ln">${row.n}</td><td class="sign cell-add-sign">+</td><td class="code cell-add">${esc(row.right)}</td>
              </tr>`;
            } else {
              tbody += `<tr>
                <td class="ln cell-add-ln"></td><td class="ln cell-add-ln">${row.n}</td><td class="sign cell-add-sign">+</td><td class="code cell-add">${esc(row.right)}</td>
              </tr>`;
            }
          }
        });
      });

      tbody += '</tbody>';
      diffTable.className = `diff-table ${isSplit ? 'split' : 'unified'}`;
      diffTable.innerHTML = colgroup + tbody;

      document.getElementById('statAdd').textContent = `+${adds}`;
      document.getElementById('statDel').textContent = `-${dels}`;
      document.getElementById('wsNote').textContent = wsHidden ? `· ${wsHidden} ws hidden` : '';
      hunkCounter.textContent = `${state.activeHunk + 1} / ${HUNKS.length}`;
    }

    function jumpToHunk(idx) {
      state.activeHunk = (idx + HUNKS.length) % HUNKS.length;
      render();
      const el = document.getElementById(HUNKS[state.activeHunk].id);
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }

    btnSplit.addEventListener('click', () => {
      state.mode = 'split';
      state.userPinnedMode = true;
      render();
    });

    btnUnified.addEventListener('click', () => {
      state.mode = 'unified';
      state.userPinnedMode = true;
      render();
    });

    btnWhitespace.addEventListener('click', () => {
      state.ignoreWhitespace = !state.ignoreWhitespace;
      render();
    });

    btnWrap.addEventListener('click', () => {
      state.wrap = !state.wrap;
      render();
    });

    document.getElementById('btnPrevHunk').addEventListener('click', () => jumpToHunk(state.activeHunk - 1));
    document.getElementById('btnNextHunk').addEventListener('click', () => jumpToHunk(state.activeHunk + 1));

    diffTable.addEventListener('click', (e) => {
      const btn = e.target.closest('button[data-expand]');
      if (btn) {
        state.expandedHunks.add(btn.dataset.expand);
        render();
      }
    });

    document.addEventListener('keydown', (e) => {
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
      if (e.key === 'j') jumpToHunk(state.activeHunk + 1);
      if (e.key === 'k') jumpToHunk(state.activeHunk - 1);
    });

    window.addEventListener('resize', () => {
      if (!state.userPinnedMode) {
        const nextMode = window.innerWidth <= 780 ? 'unified' : 'split';
        if (nextMode !== state.mode) {
          state.mode = nextMode;
          render();
        }
      }
    });

    render();
  </script>
</body>
</html>
```
