@lyrumu/pi-diff 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,755 @@
1
+ import { diffWordsWithSpace } from "diff";
2
+ import { getLanguageFromPath, highlightCode, type Theme } from "@earendil-works/pi-coding-agent";
3
+ import { visibleWidth } from "@earendil-works/pi-tui";
4
+ import type { FilePatch } from "../diff-engine.ts";
5
+ import { messages, type Language } from "../language.ts";
6
+ import { displayText, emphasisBgAnsi, fit, safeBg, safeBgAnsi, safeFgAnsi } from "./text.ts";
7
+
8
+ export const VIRTUAL_MIN_LINES = 3000;
9
+ export const VIRTUAL_CHUNK_LINES = 128;
10
+ const CONTEXT_LINES = 3;
11
+ const MAX_UNFOLDED_CONTEXT_LINES = 12;
12
+ const MAX_HIGHLIGHT_LINES = 2500;
13
+ const MAX_HIGHLIGHT_CHARS = 250_000;
14
+ const MAX_INTRALINE_CHARS = 2000;
15
+ export type DiffView = "unified" | "split";
16
+
17
+ interface GraphemeMetrics {
18
+ offsets: number[];
19
+ widths: number[];
20
+ }
21
+ interface SyntaxSpan {
22
+ start: number;
23
+ end: number;
24
+ ansi: string;
25
+ }
26
+ type Span = readonly [number, number];
27
+
28
+ interface Line {
29
+ sign: " " | "+" | "-" | "\\";
30
+ text: string;
31
+ oldLine?: number;
32
+ newLine?: number;
33
+ metrics?: GraphemeMetrics;
34
+ emphasis?: readonly Span[];
35
+ syntax?: readonly SyntaxSpan[];
36
+ }
37
+ type Row = { header: string; metrics?: GraphemeMetrics } | { left?: Line; right?: Line };
38
+ const isContext = (row: Row | undefined) => row && !("header" in row) && row.left?.sign === " ";
39
+ const isChange = (row: Row | undefined) => row && !("header" in row) && (row.left?.sign === "-" || row.right?.sign === "+");
40
+
41
+ interface WrappedText {
42
+ text: string;
43
+ width: number;
44
+ count: number;
45
+ starts?: number[];
46
+ }
47
+ interface WrappedRow {
48
+ source: Row;
49
+ start: number;
50
+ height: number;
51
+ left: WrappedText;
52
+ right?: WrappedText;
53
+ fold?: { start: number; count: number };
54
+ }
55
+ interface RenderPalette {
56
+ theme: Theme;
57
+ dimAnsi: string;
58
+ addedFg: string;
59
+ removedFg: string;
60
+ contextFg: string;
61
+ addedBg: string;
62
+ removedBg: string;
63
+ addedEmphasisBg: string;
64
+ removedEmphasisBg: string;
65
+ borderAnsi: string;
66
+ }
67
+
68
+ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
69
+ const ASCII_ONLY = /^[\x20-\x7e]*$/;
70
+ const SGR_RE = /\x1b\[([0-9;]*)m/g;
71
+
72
+ function measureGraphemes(text: string): GraphemeMetrics {
73
+ const offsets: number[] = [];
74
+ const widths: number[] = [];
75
+ for (const { segment, index } of graphemes.segment(text)) {
76
+ offsets.push(index);
77
+ widths.push(visibleWidth(segment));
78
+ }
79
+ return { offsets, widths };
80
+ }
81
+
82
+ /** Word wrapping trims code whitespace; keep graphemes and every space instead. */
83
+ function wrap(text: string, width: number, metrics?: GraphemeMetrics): WrappedText {
84
+ width = Math.max(1, width);
85
+ if (ASCII_ONLY.test(text)) return { text, width, count: Math.max(1, Math.ceil(text.length / width)) };
86
+ const resolved = metrics ?? measureGraphemes(text);
87
+ const starts = [0];
88
+ let used = 0;
89
+ for (let i = 0; i < resolved.offsets.length; i++) {
90
+ const cells = resolved.widths[i]!;
91
+ if (used > 0 && used + cells > width) {
92
+ starts.push(resolved.offsets[i]!);
93
+ used = 0;
94
+ }
95
+ used += cells;
96
+ }
97
+ return { text, width, starts, count: starts.length };
98
+ }
99
+
100
+ function wrapLine(line: Line, width: number): WrappedText {
101
+ if (!ASCII_ONLY.test(line.text) && !line.metrics) line.metrics = measureGraphemes(line.text);
102
+ return wrap(line.text, width, line.metrics);
103
+ }
104
+
105
+ const partStart = (text: WrappedText, part: number) => text.starts?.[part] ?? part * text.width;
106
+ const partEnd = (text: WrappedText, part: number) => part + 1 < text.count ? partStart(text, part + 1) : text.text.length;
107
+ const partText = (text: WrappedText, part: number) => text.text.slice(partStart(text, part), partEnd(text, part));
108
+
109
+ /** Compute word-level emphasis spans for a paired deletion/addition line. */
110
+ function computeIntraLineEmphasis(oldLine: Line, newLine: Line): void {
111
+ if (oldLine.text === newLine.text) return;
112
+ if (oldLine.text.length + newLine.text.length > MAX_INTRALINE_CHARS) return;
113
+ const parts = diffWordsWithSpace(oldLine.text, newLine.text);
114
+ const countNonSpace = (s: string) => s.replace(/\s+/g, "").length;
115
+
116
+ // Group consecutive removed/added pieces into change chunks separated by unchanged segments.
117
+ type Chunk =
118
+ | { kind: "same"; text: string; nonSpace: number; oldStart: number; oldEnd: number; newStart: number; newEnd: number }
119
+ | { kind: "change"; oldStart: number; oldEnd: number; newStart: number; newEnd: number };
120
+ const chunks: Chunk[] = [];
121
+ let oldPos = 0;
122
+ let newPos = 0;
123
+ let oldNonSpace = 0;
124
+ let newNonSpace = 0;
125
+
126
+ for (const part of parts) {
127
+ const len = part.value.length;
128
+ const ns = countNonSpace(part.value);
129
+ if (part.removed || part.added) {
130
+ const prev = chunks.at(-1);
131
+ const chunk: Extract<Chunk, { kind: "change" }> = prev?.kind === "change"
132
+ ? prev
133
+ : { kind: "change", oldStart: oldPos, oldEnd: oldPos, newStart: newPos, newEnd: newPos };
134
+ if (prev?.kind !== "change") chunks.push(chunk);
135
+ if (part.removed) {
136
+ oldPos += len;
137
+ chunk.oldEnd = oldPos;
138
+ oldNonSpace += ns;
139
+ } else {
140
+ newPos += len;
141
+ chunk.newEnd = newPos;
142
+ newNonSpace += ns;
143
+ }
144
+ } else {
145
+ chunks.push({ kind: "same", text: part.value, nonSpace: ns, oldStart: oldPos, oldEnd: oldPos + len, newStart: newPos, newEnd: newPos + len });
146
+ oldPos += len;
147
+ newPos += len;
148
+ oldNonSpace += ns;
149
+ newNonSpace += ns;
150
+ }
151
+ }
152
+
153
+ // Coalesce tiny interior unchanged islands (<= 2 non-space chars, e.g. stray CJK chars or punctuation)
154
+ // between two edits so rewritten prose never turns into patchy checkerboard highlights.
155
+ const merged: Chunk[] = [];
156
+ for (let i = 0; i < chunks.length; i++) {
157
+ const cur = chunks[i]!;
158
+ const prev = merged.at(-1);
159
+ const next = chunks[i + 1];
160
+ if (cur.kind === "same" && prev?.kind === "change" && next?.kind === "change" && cur.nonSpace <= 2) {
161
+ prev.oldEnd = next.oldEnd;
162
+ prev.newEnd = next.newEnd;
163
+ i++;
164
+ continue;
165
+ }
166
+ merged.push(cur);
167
+ }
168
+
169
+ let meaningfulCommon = 0;
170
+ const oldSpans: Span[] = [];
171
+ const newSpans: Span[] = [];
172
+ const pushTrimmed = (target: Span[], text: string, start: number, end: number) => {
173
+ if (start >= end) return;
174
+ let s = start;
175
+ let e = end;
176
+ while (s < e && text[s] === " ") s++;
177
+ while (e > s && text[e - 1] === " ") e--;
178
+ if (s < e) target.push([s, e]);
179
+ else target.push([start, end]); // Pure whitespace edit.
180
+ };
181
+
182
+ for (const chunk of merged) {
183
+ if (chunk.kind === "same") {
184
+ meaningfulCommon += chunk.nonSpace;
185
+ } else {
186
+ pushTrimmed(oldSpans, oldLine.text, chunk.oldStart, chunk.oldEnd);
187
+ pushTrimmed(newSpans, newLine.text, chunk.newStart, chunk.newEnd);
188
+ }
189
+ }
190
+
191
+ // Only emphasize focused in-place edits; skip full-line rewrites and noisy fragmented diffs.
192
+ const maxNonSpace = Math.max(oldNonSpace, newNonSpace);
193
+ if (maxNonSpace === 0) return;
194
+ const similarity = meaningfulCommon / maxNonSpace;
195
+ if (meaningfulCommon < 3 || similarity < 0.45) return;
196
+ const maxSpans = Math.max(oldSpans.length, newSpans.length);
197
+ if (maxSpans > 4 && similarity < 0.7) return;
198
+ if (oldSpans.length) oldLine.emphasis = oldSpans;
199
+ if (newSpans.length) newLine.emphasis = newSpans;
200
+ }
201
+
202
+ /** Extract foreground/attribute ANSI spans aligned to plain text offsets. */
203
+ function parseSyntaxSpans(highlighted: string, expectedPlain: string): SyntaxSpan[] | undefined {
204
+ const spans: SyntaxSpan[] = [];
205
+ let plain = "";
206
+ let pos = 0;
207
+ let activeFg = "";
208
+ let bold = false;
209
+ let italic = false;
210
+ let underline = false;
211
+ let lastIndex = 0;
212
+ const currentAnsi = () => {
213
+ let out = activeFg;
214
+ if (bold) out += "\x1b[1m";
215
+ if (italic) out += "\x1b[3m";
216
+ if (underline) out += "\x1b[4m";
217
+ return out;
218
+ };
219
+ SGR_RE.lastIndex = 0;
220
+ let match: RegExpExecArray | null;
221
+ while ((match = SGR_RE.exec(highlighted)) !== null) {
222
+ if (match.index > lastIndex) {
223
+ const chunk = highlighted.slice(lastIndex, match.index);
224
+ const ansi = currentAnsi();
225
+ if (ansi && chunk.length > 0) spans.push({ start: pos, end: pos + chunk.length, ansi });
226
+ plain += chunk;
227
+ pos += chunk.length;
228
+ }
229
+ const codes = (match[1] ?? "").split(";").map((v) => v === "" ? 0 : Number(v));
230
+ for (let i = 0; i < codes.length; i++) {
231
+ const c = codes[i]!;
232
+ if (c === 0) { activeFg = ""; bold = false; italic = false; underline = false; }
233
+ else if (c === 1) bold = true;
234
+ else if (c === 3) italic = true;
235
+ else if (c === 4) underline = true;
236
+ else if (c === 22) bold = false;
237
+ else if (c === 23) italic = false;
238
+ else if (c === 24) underline = false;
239
+ else if (c === 39) activeFg = "";
240
+ else if ((c >= 30 && c <= 37) || (c >= 90 && c <= 97)) activeFg = `\x1b[${c}m`;
241
+ else if (c === 38) {
242
+ if (codes[i + 1] === 5 && codes[i + 2] !== undefined) {
243
+ activeFg = `\x1b[38;5;${codes[i + 2]}m`;
244
+ i += 2;
245
+ } else if (codes[i + 1] === 2 && codes[i + 4] !== undefined) {
246
+ activeFg = `\x1b[38;2;${codes[i + 2]};${codes[i + 3]};${codes[i + 4]}m`;
247
+ i += 4;
248
+ }
249
+ }
250
+ }
251
+ lastIndex = match.index + match[0].length;
252
+ }
253
+ if (lastIndex < highlighted.length) {
254
+ const chunk = highlighted.slice(lastIndex);
255
+ const ansi = currentAnsi();
256
+ if (ansi && chunk.length > 0) spans.push({ start: pos, end: pos + chunk.length, ansi });
257
+ plain += chunk;
258
+ }
259
+ return plain === expectedPlain ? spans : undefined;
260
+ }
261
+
262
+ /** Paint a character slice combining optional syntax fg spans and intra-line emphasis spans. */
263
+ function renderStyledSlice(
264
+ line: Line,
265
+ sliceStart: number,
266
+ sliceEnd: number,
267
+ baseFg: string,
268
+ baseBg: string,
269
+ emphasisBg: string,
270
+ ): string {
271
+ const slice = line.text.slice(sliceStart, sliceEnd);
272
+ const syntax = line.syntax;
273
+ const emphasis = line.emphasis;
274
+ const hasSyntax = syntax !== undefined;
275
+ const hasEmphasis = emphasis !== undefined && emphasis.length > 0;
276
+ if (!hasSyntax && !hasEmphasis) return baseFg ? `${baseFg}${slice}\x1b[39m` : slice;
277
+ if (hasSyntax && syntax.length === 0 && !hasEmphasis) return slice;
278
+
279
+ const points = new Set<number>([sliceStart, sliceEnd]);
280
+ if (hasSyntax) {
281
+ for (const s of syntax) {
282
+ if (s.end <= sliceStart || s.start >= sliceEnd) continue;
283
+ points.add(Math.max(sliceStart, s.start));
284
+ points.add(Math.min(sliceEnd, s.end));
285
+ }
286
+ }
287
+ if (hasEmphasis) {
288
+ for (const [start, end] of emphasis) {
289
+ if (end <= sliceStart || start >= sliceEnd) continue;
290
+ points.add(Math.max(sliceStart, start));
291
+ points.add(Math.min(sliceEnd, end));
292
+ }
293
+ }
294
+ const sorted = [...points].sort((a, b) => a - b);
295
+ let out = "";
296
+ for (let i = 0; i + 1 < sorted.length; i++) {
297
+ const a = sorted[i]!;
298
+ const b = sorted[i + 1]!;
299
+ if (a >= b) continue;
300
+ const text = line.text.slice(a, b);
301
+ let fg = hasSyntax ? "" : baseFg;
302
+ if (hasSyntax) {
303
+ for (const s of syntax) {
304
+ if (s.start <= a && s.end >= b) { fg = s.ansi; break; }
305
+ }
306
+ }
307
+ let emphasized = false;
308
+ if (hasEmphasis) {
309
+ for (const [start, end] of emphasis) {
310
+ if (start <= a && end >= b) { emphasized = true; break; }
311
+ }
312
+ }
313
+ let seg = text;
314
+ if (fg) seg = `${fg}${seg}\x1b[39m\x1b[22m\x1b[23m\x1b[24m`;
315
+ if (emphasized) {
316
+ if (emphasisBg) seg = `${emphasisBg}${seg}${baseBg}`;
317
+ else seg = `\x1b[4m${seg}\x1b[24m`;
318
+ }
319
+ out += seg;
320
+ }
321
+ return out;
322
+ }
323
+
324
+ /** pi-tui has no DiffRenderable: parse once, then paint only viewport chunks. */
325
+ export class PatchDiff {
326
+ private readonly filePath: string;
327
+ private readonly unified: Row[] = [];
328
+ private readonly split: Row[] = [];
329
+ private readonly folds = new Map<Row, number>();
330
+ private readonly foldOrder: Row[] = [];
331
+ private readonly expandedFolds = new Set<Row>();
332
+ private readonly digits: number;
333
+ private readonly placeholder: "unavailable" | "binary" | "tooLarge" | "deletedUnknown" | "noPatch" | "noTextChanges" | undefined;
334
+ private language: Language;
335
+ private readonly status: FilePatch["status"];
336
+ private cacheSignature = "";
337
+ private readonly chunks = new Map<number, string[]>();
338
+ private wrapped: WrappedRow[] = [];
339
+ private changeStarts: number[] = [];
340
+ private totalRows = 0;
341
+ private cacheTheme: Theme | undefined;
342
+ private palette: RenderPalette | undefined;
343
+ private highlightedForTheme: Theme | undefined;
344
+
345
+ constructor(file: FilePatch, language: Language = "en") {
346
+ this.filePath = file.file;
347
+ this.language = language;
348
+ this.status = file.status;
349
+ let modes: string[] = file.patch.match(/^(?:old mode|new mode|new file mode|deleted file mode) [0-7]{6}$/gm) ?? [];
350
+ if (file.oldMode !== undefined && file.newMode !== undefined && file.oldMode !== file.newMode) {
351
+ modes = [];
352
+ if (file.oldMode !== null) modes.push(`${file.newMode === null ? "deleted file mode" : "old mode"} ${file.oldMode}`);
353
+ if (file.newMode !== null) modes.push(`${file.oldMode === null ? "new file mode" : "new mode"} ${file.newMode}`);
354
+ }
355
+ for (const header of modes) this.unified.push({ header });
356
+ this.placeholder = file.unavailable ? "unavailable"
357
+ : file.binary ? "binary"
358
+ : file.tooLarge ? "tooLarge"
359
+ : file.baselineUnknown && file.status === "deleted" ? "deletedUnknown"
360
+ : !file.patch && modes.length === 0 ? "noPatch" : undefined;
361
+ let oldLine = 0;
362
+ let newLine = 0;
363
+ let inHunk = false;
364
+ let maxLine = 0;
365
+ if (!this.placeholder) for (const text of file.patch.replace(/\n$/, "").split("\n")) {
366
+ const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(text);
367
+ if (hunk) {
368
+ oldLine = Number(hunk[1]);
369
+ newLine = Number(hunk[2]);
370
+ inHunk = true;
371
+ this.unified.push({ header: displayText(text) });
372
+ continue;
373
+ }
374
+ if (text.startsWith("diff --git ")) inHunk = false;
375
+ if (!inHunk || ![" ", "+", "-", "\\"].includes(text[0] ?? "")) continue;
376
+ const sign = text[0] as Line["sign"];
377
+ const line: Line = { sign, text: displayText(text.slice(1)) };
378
+ if (sign === " " || sign === "-") line.oldLine = oldLine++;
379
+ if (sign === " " || sign === "+") line.newLine = newLine++;
380
+ maxLine = Math.max(maxLine, line.oldLine ?? 0, line.newLine ?? 0);
381
+ this.unified.push({ left: line, right: line });
382
+ }
383
+ this.digits = Math.max(1, String(maxLine).length);
384
+ for (let start = 0; start < this.unified.length;) {
385
+ if (!isContext(this.unified[start])) {
386
+ start++;
387
+ continue;
388
+ }
389
+ let end = start + 1;
390
+ while (isContext(this.unified[end])) end++;
391
+ if (end - start > MAX_UNFOLDED_CONTEXT_LINES) {
392
+ const first = start + (isChange(this.unified[start - 1]) ? CONTEXT_LINES : 0);
393
+ const next = this.unified[end];
394
+ const endsWithoutNewline = next && !("header" in next) && next.left?.sign === "\\";
395
+ const keepEnd = isChange(next) ? CONTEXT_LINES : endsWithoutNewline ? 1 : 0;
396
+ const last = end - keepEnd;
397
+ const anchor = this.unified[first]!;
398
+ this.folds.set(anchor, last - first);
399
+ this.foldOrder.push(anchor);
400
+ }
401
+ start = end;
402
+ }
403
+ for (let i = 0; i < this.unified.length;) {
404
+ const row = this.unified[i]!;
405
+ if ("header" in row || row.left?.sign === " " || row.left?.sign === "\\") {
406
+ this.split.push(row);
407
+ i++;
408
+ continue;
409
+ }
410
+ const removed: Line[] = [];
411
+ const added: Line[] = [];
412
+ while (i < this.unified.length) {
413
+ const next = this.unified[i]!;
414
+ if ("header" in next || !next.left || !["-", "+"].includes(next.left.sign)) break;
415
+ (next.left.sign === "-" ? removed : added).push(next.left);
416
+ i++;
417
+ }
418
+ const paired = Math.min(removed.length, added.length);
419
+ for (let j = 0; j < paired; j++) computeIntraLineEmphasis(removed[j]!, added[j]!);
420
+ for (let j = 0; j < Math.max(removed.length, added.length); j++) this.split.push({ left: removed[j], right: added[j] });
421
+ }
422
+ if (!this.placeholder && this.unified.length === 0) this.placeholder = "noTextChanges";
423
+ }
424
+
425
+ private ensureSyntaxHighlighting(theme: Theme): void {
426
+ if (this.highlightedForTheme === theme) return;
427
+ this.highlightedForTheme = theme;
428
+ // Only highlight when a real pi Theme is active and the file size is bounded.
429
+ if (typeof theme.getFgAnsi !== "function" || !theme.colors) return;
430
+ const lang = getLanguageFromPath(this.filePath);
431
+ if (!lang || lang === "markdown") return;
432
+ const oldLines: Line[] = [];
433
+ const newLines: Line[] = [];
434
+ let chars = 0;
435
+ for (const row of this.unified) {
436
+ if ("header" in row || !row.left) continue;
437
+ const line = row.left;
438
+ if (line.sign === "\\") continue;
439
+ line.syntax = undefined;
440
+ chars += line.text.length;
441
+ if (line.sign === " " || line.sign === "-") oldLines.push(line);
442
+ if (line.sign === " " || line.sign === "+") newLines.push(line);
443
+ }
444
+ if (oldLines.length + newLines.length === 0) return;
445
+ if (Math.max(oldLines.length, newLines.length) > MAX_HIGHLIGHT_LINES || chars > MAX_HIGHLIGHT_CHARS) return;
446
+ const fallbackAnsi = safeFgAnsi(theme, "mdCodeBlock");
447
+ const apply = (lines: Line[]) => {
448
+ if (!lines.length) return;
449
+ try {
450
+ const highlighted = highlightCode(lines.map((line) => line.text).join("\n"), lang);
451
+ if (highlighted.length !== lines.length) return;
452
+ const parsed = lines.map((line, i) => parseSyntaxSpans(highlighted[i]!, line.text));
453
+ // Skip unsupported-grammar fallback where highlightCode wraps every non-empty line in mdCodeBlock.
454
+ const isFallbackOnly = fallbackAnsi !== "" && parsed.every((spans, i) => {
455
+ const text = lines[i]!.text;
456
+ if (!text.length) return true;
457
+ return spans !== undefined && spans.length === 1 && spans[0]!.start === 0 && spans[0]!.end === text.length && spans[0]!.ansi === fallbackAnsi;
458
+ });
459
+ if (isFallbackOnly) return;
460
+ for (let i = 0; i < lines.length; i++) {
461
+ if (parsed[i]) lines[i]!.syntax = parsed[i];
462
+ }
463
+ } catch {
464
+ // Global pi theme may be uninitialized in isolated unit tests; fall back cleanly.
465
+ }
466
+ };
467
+ apply(oldLines);
468
+ apply(newLines);
469
+ }
470
+
471
+ private getPalette(theme: Theme): RenderPalette {
472
+ if (this.palette?.theme === theme) return this.palette;
473
+ this.palette = {
474
+ theme,
475
+ dimAnsi: safeFgAnsi(theme, "dim", "muted"),
476
+ addedFg: safeFgAnsi(theme, "toolDiffAdded", "success"),
477
+ removedFg: safeFgAnsi(theme, "toolDiffRemoved", "error"),
478
+ contextFg: safeFgAnsi(theme, "toolDiffContext", "muted"),
479
+ addedBg: safeBgAnsi(theme, "toolSuccessBg"),
480
+ removedBg: safeBgAnsi(theme, "toolErrorBg"),
481
+ addedEmphasisBg: emphasisBgAnsi(theme, "toolSuccessBg", "success"),
482
+ removedEmphasisBg: emphasisBgAnsi(theme, "toolErrorBg", "error"),
483
+ borderAnsi: safeFgAnsi(theme, "borderMuted", "muted"),
484
+ };
485
+ return this.palette;
486
+ }
487
+
488
+ setLanguage(language: Language): void {
489
+ this.language = language;
490
+ this.chunks.clear();
491
+ }
492
+
493
+ contextState(): "expandContext" | "foldContext" | undefined {
494
+ if (!this.folds.size) return undefined;
495
+ return this.expandedFolds.size < this.folds.size ? "expandContext" : "foldContext";
496
+ }
497
+
498
+ toggleContext(): void {
499
+ if (!this.folds.size) return;
500
+ if (this.expandedFolds.size < this.folds.size) {
501
+ for (const anchor of this.folds.keys()) this.expandedFolds.add(anchor);
502
+ } else {
503
+ this.expandedFolds.clear();
504
+ }
505
+ }
506
+
507
+ /** Expand one collapsed context block when clicked. */
508
+ expandFoldAt(visualRow: number): boolean {
509
+ const row = this.rowAt(visualRow);
510
+ if (!row?.fold) return false;
511
+ this.expandedFolds.add(row.source);
512
+ this.cacheSignature = "";
513
+ this.chunks.clear();
514
+ return true;
515
+ }
516
+
517
+ getExpandedFoldIndices(): number[] {
518
+ const indices: number[] = [];
519
+ for (let i = 0; i < this.foldOrder.length; i++) {
520
+ if (this.expandedFolds.has(this.foldOrder[i]!)) indices.push(i);
521
+ }
522
+ return indices;
523
+ }
524
+
525
+ restoreExpandedFoldIndices(indices: Iterable<number>): void {
526
+ this.expandedFolds.clear();
527
+ for (const i of indices) {
528
+ const anchor = this.foldOrder[i];
529
+ if (anchor) this.expandedFolds.add(anchor);
530
+ }
531
+ this.cacheSignature = "";
532
+ this.chunks.clear();
533
+ }
534
+
535
+ effectiveView(view: DiffView): DiffView {
536
+ return this.status === "modified" ? view : "unified";
537
+ }
538
+
539
+ private foldSignature(): string {
540
+ if (!this.expandedFolds.size) return "0";
541
+ if (this.expandedFolds.size === this.folds.size) return "all";
542
+ return this.getExpandedFoldIndices().join(",");
543
+ }
544
+
545
+ private prepare(width: number, view: DiffView): void {
546
+ const signature = `${width}:${view}:${this.foldSignature()}`;
547
+ if (signature === this.cacheSignature) return;
548
+ this.cacheSignature = signature;
549
+ this.chunks.clear();
550
+ this.wrapped = [];
551
+ this.changeStarts = [];
552
+ this.totalRows = 0;
553
+ const sepWidth = width >= 4 ? 2 : 1;
554
+ const leftWidth = Math.floor((width - sepWidth) / 2);
555
+ const rows = view === "split" ? this.split : this.unified;
556
+ let inChange = false;
557
+ for (let i = 0; i < rows.length; i++) {
558
+ const source = rows[i]!;
559
+ const hidden = this.expandedFolds.has(source) ? undefined : this.folds.get(source);
560
+ if (hidden !== undefined) {
561
+ this.wrapped.push({ source, start: this.totalRows++, height: 1, left: wrap("", width), fold: { start: i, count: hidden } });
562
+ i += hidden - 1;
563
+ inChange = false;
564
+ continue;
565
+ }
566
+ if (isChange(source)) {
567
+ if (!inChange) this.changeStarts.push(this.totalRows);
568
+ inChange = true;
569
+ } else if ("header" in source || source.left?.sign !== "\\") inChange = false;
570
+ let left: WrappedText;
571
+ let right: WrappedText | undefined;
572
+ if ("header" in source) {
573
+ if (!ASCII_ONLY.test(source.header) && !source.metrics) source.metrics = measureGraphemes(source.header);
574
+ left = wrap(source.header, width, source.metrics);
575
+ } else if (source.left?.sign === "\\") {
576
+ left = wrap(`\\${source.left.text}`, width);
577
+ } else if (view === "unified") {
578
+ left = wrapLine(source.left!, width - 2 * this.digits - 4);
579
+ } else {
580
+ left = source.left ? wrapLine(source.left, leftWidth - this.digits - 3) : wrap("", leftWidth - this.digits - 3);
581
+ right = source.right ? wrapLine(source.right, width - leftWidth - sepWidth - this.digits - 3) : wrap("", width - leftWidth - sepWidth - this.digits - 3);
582
+ }
583
+ const height = Math.max(left.count, right?.count ?? 1);
584
+ this.wrapped.push({ source, start: this.totalRows, height, left, right });
585
+ this.totalRows += height;
586
+ }
587
+ }
588
+
589
+ private rowAt(index: number): WrappedRow | undefined {
590
+ let low = 0;
591
+ let high = this.wrapped.length;
592
+ while (low < high) {
593
+ const mid = Math.floor((low + high) / 2);
594
+ if (this.wrapped[mid]!.start <= index) low = mid + 1;
595
+ else high = mid;
596
+ }
597
+ const row = this.wrapped[low - 1];
598
+ return row && index < row.start + row.height ? row : undefined;
599
+ }
600
+
601
+ rowCount(width: number, view: DiffView): number {
602
+ this.prepare(width, this.effectiveView(view));
603
+ return this.totalRows + (this.placeholder ? 1 : 0);
604
+ }
605
+
606
+ changeCount(): number {
607
+ return this.changeStarts.length;
608
+ }
609
+
610
+ changeRow(index: number): number | undefined {
611
+ return this.changeStarts[index];
612
+ }
613
+
614
+ adjacentChangeIndex(top: number, direction: -1 | 1): number | undefined {
615
+ let low = 0;
616
+ let high = this.changeStarts.length;
617
+ while (low < high) {
618
+ const mid = Math.floor((low + high) / 2);
619
+ const start = this.changeStarts[mid]!;
620
+ if (start < top || (direction === 1 && start === top)) low = mid + 1;
621
+ else high = mid;
622
+ }
623
+ const idx = direction === 1 ? low : low - 1;
624
+ return idx >= 0 && idx < this.changeStarts.length ? idx : undefined;
625
+ }
626
+
627
+ adjacentChange(top: number, direction: -1 | 1): number | undefined {
628
+ const idx = this.adjacentChangeIndex(top, direction);
629
+ return idx === undefined ? undefined : this.changeStarts[idx];
630
+ }
631
+
632
+ /** Keep the same source character visible when width or layout changes. */
633
+ reflowTop(width: number, view: DiffView, top: number): number {
634
+ view = this.effectiveView(view);
635
+ if (this.cacheSignature === `${width}:${view}:${this.foldSignature()}`) return top;
636
+ const old = this.rowAt(top);
637
+ const part = old ? top - old.start : 0;
638
+ const right = old && part >= old.left.count;
639
+ const text = right ? old?.right : old?.left;
640
+ const line = old && !("header" in old.source) ? right ? old.source.right : old.source.left : undefined;
641
+ const offset = text ? partStart(text, part) : 0;
642
+ this.prepare(width, view);
643
+ if (!old) return top;
644
+ const next = this.wrapped.find((item) => item.source === old.source || (line && !("header" in item.source) && (item.source.left === line || item.source.right === line)));
645
+ if (!next) {
646
+ const rows = view === "split" ? this.split : this.unified;
647
+ const index = rows.indexOf(old.source);
648
+ return this.wrapped.find(({ fold }) => fold && index >= fold.start && index < fold.start + fold.count)?.start ?? top;
649
+ }
650
+ const nextText = line && !("header" in next.source) && next.source.right === line && next.source.left !== line ? next.right! : next.left;
651
+ let nextPart = nextText.starts ? 0 : Math.floor(offset / nextText.width);
652
+ if (nextText.starts) {
653
+ while (nextPart + 1 < nextText.count && nextText.starts[nextPart + 1]! <= offset) nextPart++;
654
+ }
655
+ return next.start + Math.min(nextPart, next.height - 1);
656
+ }
657
+
658
+ private paintLine(line: Line, gutterNums: string, signChar: string, text: WrappedText, part: number, size: number, theme: Theme, palette: RenderPalette): string {
659
+ const start = partStart(text, part);
660
+ const end = partEnd(text, part);
661
+ const isAdded = line.sign === "+";
662
+ const isRemoved = line.sign === "-";
663
+ const baseBg = isAdded ? palette.addedBg : isRemoved ? palette.removedBg : "";
664
+ const emphasisBg = isAdded ? palette.addedEmphasisBg : isRemoved ? palette.removedEmphasisBg : "";
665
+ const baseFg = isAdded ? palette.addedFg : isRemoved ? palette.removedFg : palette.contextFg;
666
+ const signFg = isAdded ? palette.addedFg : isRemoved ? palette.removedFg : palette.dimAnsi;
667
+ const isContinuation = part > 0;
668
+ const useFastAnsi = Boolean(baseFg || palette.dimAnsi);
669
+
670
+ let styledRow: string;
671
+ if (useFastAnsi) {
672
+ const numPart = palette.dimAnsi ? `${palette.dimAnsi}${gutterNums}\x1b[39m\x1b[22m` : gutterNums;
673
+ const signPart = isContinuation
674
+ ? (palette.dimAnsi ? `${palette.dimAnsi}${signChar} \x1b[39m\x1b[22m` : `${signChar} `)
675
+ : (signFg ? `${signFg}${signChar} \x1b[39m\x1b[22m` : `${signChar} `);
676
+ const bodyPart = renderStyledSlice(line, start, end, baseFg, baseBg, emphasisBg);
677
+ styledRow = fit(numPart + signPart + bodyPart, size);
678
+ } else {
679
+ // Fallback for mock themes that only implement theme.fg/theme.bg.
680
+ const color = isAdded ? "success" : isRemoved ? "error" : "muted";
681
+ styledRow = fit(theme.fg(color, `${gutterNums}${signChar} ${line.text.slice(start, end)}`), size);
682
+ }
683
+ if (isAdded) return baseBg ? `${baseBg}${styledRow}\x1b[49m` : theme.bg("toolSuccessBg", styledRow);
684
+ if (isRemoved) return baseBg ? `${baseBg}${styledRow}\x1b[49m` : theme.bg("toolErrorBg", styledRow);
685
+ return styledRow;
686
+ }
687
+
688
+ private paint(wrapped: WrappedRow, part: number, width: number, view: DiffView, theme: Theme, palette: RenderPalette): string {
689
+ if (wrapped.fold) {
690
+ const label = messages[this.language].foldedLines(wrapped.fold.count);
691
+ return safeBg(theme, "customMessageBg", fit(theme.fg("muted", label), width));
692
+ }
693
+ const row = wrapped.source;
694
+ if ("header" in row) {
695
+ return safeBg(theme, "customMessageBg", fit(theme.fg("accent", partText(wrapped.left, part)), width));
696
+ }
697
+ if (row.left?.sign === "\\") {
698
+ return fit(theme.fg("muted", partText(wrapped.left, part)), width);
699
+ }
700
+ const number = (value: number | undefined) => String(value ?? "").padStart(this.digits);
701
+ if (view === "unified") {
702
+ const line = row.left!;
703
+ const nums = `${number(part === 0 ? line.oldLine : undefined)} ${number(part === 0 ? line.newLine : undefined)} `;
704
+ return this.paintLine(line, nums, part === 0 ? line.sign : "↳", wrapped.left, part, width, theme, palette);
705
+ }
706
+ const sepWidth = width >= 4 ? 2 : 1;
707
+ const leftWidth = Math.floor((width - sepWidth) / 2);
708
+ const rightWidth = width - leftWidth - sepWidth;
709
+ const side = (line: Line | undefined, text: WrappedText, size: number, old: boolean) => {
710
+ if (!line || part >= text.count) return fit("", size);
711
+ const nums = `${number(part === 0 ? (old ? line.oldLine : line.newLine) : undefined)} `;
712
+ return this.paintLine(line, nums, part === 0 ? line.sign : "↳", text, part, size, theme, palette);
713
+ };
714
+ const bar = palette.borderAnsi ? `${palette.borderAnsi}│\x1b[39m` : theme.fg("borderMuted", "│");
715
+ const sep = sepWidth === 2 ? bar + " " : bar;
716
+ return side(row.left, wrapped.left, leftWidth, true) + sep + side(row.right, wrapped.right!, rightWidth, false);
717
+ }
718
+
719
+ renderViewport(width: number, height: number, top: number, view: DiffView, theme: Theme): string[] {
720
+ view = this.effectiveView(view);
721
+ this.prepare(width, view);
722
+ if (theme !== this.cacheTheme) {
723
+ this.chunks.clear();
724
+ this.cacheTheme = theme;
725
+ this.palette = undefined;
726
+ }
727
+ this.ensureSyntaxHighlighting(theme);
728
+ const palette = this.getPalette(theme);
729
+ const maxChunks = this.totalRows >= VIRTUAL_MIN_LINES ? 4 : 8;
730
+ return Array.from({ length: height }, (_, offset) => {
731
+ const index = top + offset;
732
+ if (this.placeholder && index === this.totalRows) return fit(theme.fg("muted", messages[this.language][this.placeholder]), width);
733
+ const row = this.rowAt(index);
734
+ if (!row) return fit("", width);
735
+ const chunkIndex = Math.floor(index / VIRTUAL_CHUNK_LINES);
736
+ let chunk = this.chunks.get(chunkIndex);
737
+ if (!chunk) {
738
+ const start = chunkIndex * VIRTUAL_CHUNK_LINES;
739
+ chunk = Array.from({ length: Math.min(VIRTUAL_CHUNK_LINES, this.totalRows - start) }, (_, i) => {
740
+ const item = this.rowAt(start + i)!;
741
+ return this.paint(item, start + i - item.start, width, view, theme, palette);
742
+ });
743
+ this.chunks.set(chunkIndex, chunk);
744
+ if (this.chunks.size > maxChunks) this.chunks.delete(this.chunks.keys().next().value!);
745
+ }
746
+ return chunk[index % VIRTUAL_CHUNK_LINES]!;
747
+ });
748
+ }
749
+
750
+ invalidate(): void {
751
+ this.chunks.clear();
752
+ this.palette = undefined;
753
+ this.highlightedForTheme = undefined;
754
+ }
755
+ }