@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,446 @@
1
+ import { matchesKey, visibleWidth, wrapTextWithAnsi, type Component, type OverlayOptions, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
2
+ import type { Theme } from "@earendil-works/pi-coding-agent";
3
+ import type { FilePatch } from "../diff-engine.ts";
4
+ import { localize, messages, type Language, type LocalizedText } from "../language.ts";
5
+ import { FileTree } from "./file-tree.ts";
6
+ import { PatchDiff, type DiffView } from "./patch-diff.ts";
7
+ import { displayText, fit, fitEllipsis, safeBg, safeFg, type TuiHost } from "./text.ts";
8
+
9
+ export const MIN_SPLIT_WIDTH = 100;
10
+ export const FILE_TREE_MIN_WIDTH = 10;
11
+ export const FILE_TREE_MAX_WIDTH = 40;
12
+ const MIN_PATCH_WIDTH = 40;
13
+ export const FILE_HEADER_HEIGHT = 2;
14
+ const JUMP_LEAD_LINES = 3;
15
+ const MAX_CACHED_PATCHES = 16;
16
+ export const FULLSCREEN_OPTIONS = {
17
+ overlay: true,
18
+ overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0, margin: 0 } satisfies OverlayOptions,
19
+ } as const;
20
+
21
+ export interface DiffScreenPreferences {
22
+ language?: Language;
23
+ onLanguageChange?: (language: Language) => void;
24
+ view?: DiffView;
25
+ onViewChange?: (view: DiffView) => void;
26
+ emptyMessage?: LocalizedText;
27
+ notice?: LocalizedText;
28
+ onScopeChange?: (direction: 1 | -1) => void;
29
+ }
30
+
31
+ interface SavedFileState {
32
+ top: number;
33
+ changeJump: boolean;
34
+ activeChange: number | undefined;
35
+ expandedFolds: number[];
36
+ }
37
+
38
+ /** Selected-file view on a fullscreen overlay; all data comes from FilePatch[]. */
39
+ export class DiffScreen implements Component {
40
+ private readonly host: TuiHost;
41
+ private readonly theme: Theme;
42
+ private title: LocalizedText;
43
+ private language: Language;
44
+ private files: readonly FilePatch[];
45
+ private totals = { additions: 0, deletions: 0 };
46
+ private readonly close: () => void;
47
+ private readonly preferences: DiffScreenPreferences;
48
+ private tree: FileTree;
49
+ private emptyMessage: LocalizedText | undefined;
50
+ private notice: LocalizedText | undefined;
51
+ private selected: number | undefined;
52
+ private patch: PatchDiff | undefined;
53
+ private readonly patchCache = new Map<number, PatchDiff>();
54
+ private readonly fileStates = new Map<number, SavedFileState>();
55
+ private focus: "tree" | "diff" = "diff";
56
+ private viewOverride: DiffView | undefined;
57
+ private top = 0;
58
+ private changeJump = false;
59
+ private activeChange: number | undefined;
60
+ private viewButton = 0;
61
+ private showFilesButton = 0;
62
+ private contextButton = { start: -1, end: -1 };
63
+ private viewHint: "noFileToSwitch" | "tooNarrow" | undefined;
64
+ private treeWidthOverride: number | undefined;
65
+ private treeCollapsed = false;
66
+ private dividerGesture: "dragging" | "released" | undefined;
67
+ private dividerMoved = false;
68
+ private lastDividerClick = 0;
69
+ private pointer: { x: number; y: number } | undefined;
70
+
71
+ constructor(host: TuiHost, theme: Theme, title: LocalizedText, files: readonly FilePatch[], close: () => void, preferences: DiffScreenPreferences = {}) {
72
+ this.host = host;
73
+ this.theme = theme;
74
+ this.title = title;
75
+ this.files = files;
76
+ this.totals = this.computeTotals(files);
77
+ this.close = close;
78
+ this.preferences = preferences;
79
+ this.language = preferences.language ?? "en";
80
+ this.emptyMessage = preferences.emptyMessage;
81
+ this.notice = preferences.notice;
82
+ this.viewOverride = preferences.view;
83
+ this.tree = new FileTree(files);
84
+ this.select(this.tree.selectedFile());
85
+ }
86
+
87
+ private computeTotals(files: readonly FilePatch[]) {
88
+ return files.reduce((sum, file) => ({ additions: sum.additions + file.additions, deletions: sum.deletions + file.deletions }), { additions: 0, deletions: 0 });
89
+ }
90
+
91
+ /** Replace the source inside the existing overlay; never expose the chat between scopes. */
92
+ setData(title: LocalizedText, files: readonly FilePatch[], status: { emptyMessage?: LocalizedText; notice?: LocalizedText } = {}): void {
93
+ this.title = title;
94
+ this.files = files;
95
+ this.totals = this.computeTotals(files);
96
+ this.emptyMessage = status.emptyMessage;
97
+ this.notice = status.notice;
98
+ this.tree = new FileTree(files);
99
+ this.selected = undefined;
100
+ this.patch = undefined;
101
+ this.patchCache.clear();
102
+ this.fileStates.clear();
103
+ this.top = 0;
104
+ this.changeJump = false;
105
+ this.activeChange = undefined;
106
+ this.focus = "diff";
107
+ this.viewHint = undefined;
108
+ this.pointer = undefined;
109
+ this.lastDividerClick = 0;
110
+ if (this.dividerGesture === "dragging") this.dividerGesture = "released";
111
+ this.select(this.tree.selectedFile());
112
+ this.host.requestRender();
113
+ }
114
+
115
+ private saveCurrentFileState(): void {
116
+ if (this.selected === undefined || !this.patch) return;
117
+ this.fileStates.set(this.selected, {
118
+ top: this.top,
119
+ changeJump: this.changeJump,
120
+ activeChange: this.activeChange,
121
+ expandedFolds: this.patch.getExpandedFoldIndices(),
122
+ });
123
+ }
124
+
125
+ private select(index: number | undefined): void {
126
+ if (index === undefined || index === this.selected) return;
127
+ const file = this.files[index];
128
+ if (!file) return;
129
+ this.saveCurrentFileState();
130
+ this.selected = index;
131
+ const saved = this.fileStates.get(index);
132
+ let cached = this.patchCache.get(index);
133
+ if (cached) {
134
+ this.patchCache.delete(index);
135
+ this.patchCache.set(index, cached);
136
+ } else {
137
+ cached = new PatchDiff(file, this.language);
138
+ if (saved?.expandedFolds.length) cached.restoreExpandedFoldIndices(saved.expandedFolds);
139
+ this.patchCache.set(index, cached);
140
+ if (this.patchCache.size > MAX_CACHED_PATCHES) {
141
+ const oldest = this.patchCache.keys().next().value;
142
+ if (oldest !== undefined) this.patchCache.delete(oldest);
143
+ }
144
+ }
145
+ this.patch = cached;
146
+ this.top = saved?.top ?? 0;
147
+ this.changeJump = saved?.changeJump ?? false;
148
+ this.activeChange = saved?.activeChange;
149
+ this.viewHint = undefined;
150
+ }
151
+
152
+ private layout(width: number, rows = this.host.terminal.rows) {
153
+ const inset = width < 90 ? 0 : 2;
154
+ const maxTreeWidth = Math.min(Math.floor(width / 4), width - inset * 2 - MIN_PATCH_WIDTH);
155
+ const defaultTreeWidth = Math.max(30, Math.min(FILE_TREE_MAX_WIDTH, Math.floor(width / 4)));
156
+ const treeWidth = width >= 90 && this.files.length > 0 && !this.treeCollapsed
157
+ ? Math.min(maxTreeWidth, Math.max(FILE_TREE_MIN_WIDTH, this.treeWidthOverride ?? defaultTreeWidth)) : 0;
158
+ const patchWidth = Math.max(1, width - treeWidth - inset * 2);
159
+ const view: DiffView = patchWidth >= MIN_SPLIT_WIDTH ? this.viewOverride ?? "split" : "unified";
160
+ const notice = this.notice ? wrapTextWithAnsi(localize(this.notice, this.language), Math.max(1, width))
161
+ .slice(0, Math.max(0, rows - 3 - FILE_HEADER_HEIGHT)) : [];
162
+ const bodyEnd = rows - 1 - notice.length;
163
+ const height = Math.max(0, bodyEnd - 1 - FILE_HEADER_HEIGHT);
164
+ return { inset, treeWidth, maxTreeWidth, patchWidth, view, height, notice, bodyEnd };
165
+ }
166
+
167
+ private scrollDiff(delta: number): void {
168
+ if (!this.patch) return;
169
+ const { patchWidth, view, height } = this.layout(this.host.terminal.columns);
170
+ this.top = this.patch.reflowTop(patchWidth, view, this.top);
171
+ const bottom = Math.max(0, this.patch.rowCount(patchWidth, view) - Math.max(1, height));
172
+ this.top = Math.max(0, Math.min(this.top + delta, this.changeJump ? Math.max(this.top, bottom) : bottom));
173
+ this.changeJump &&= this.top > bottom;
174
+ this.activeChange = undefined;
175
+ }
176
+
177
+ handleInput(data: string): void {
178
+ if (matchesKey(data, "escape") || matchesKey(data, "q")) {
179
+ this.close();
180
+ return;
181
+ }
182
+ if (matchesKey(data, "tab") || matchesKey(data, "shift+tab")) {
183
+ this.preferences.onScopeChange?.(matchesKey(data, "tab") ? 1 : -1);
184
+ return;
185
+ }
186
+ if (matchesKey(data, "l") || matchesKey(data, "shift+l")) {
187
+ this.language = this.language === "en" ? "zh-CN" : "en";
188
+ for (const cached of this.patchCache.values()) cached.setLanguage(this.language);
189
+ this.preferences.onLanguageChange?.(this.language);
190
+ this.host.requestRender();
191
+ return;
192
+ }
193
+ const { patchWidth, view, height } = this.layout(this.host.terminal.columns);
194
+ if (matchesKey(data, "[")) {
195
+ // Explicit reopening takes precedence over pending drag/release events.
196
+ if (this.dividerGesture === "dragging") this.dividerGesture = "released";
197
+ this.lastDividerClick = 0;
198
+ this.treeCollapsed = false;
199
+ this.focus = "tree";
200
+ } else if (matchesKey(data, "]")) this.focus = "diff";
201
+ else if (matchesKey(data, "v") || matchesKey(data, "shift+v")) {
202
+ const file = this.selected === undefined ? undefined : this.files[this.selected];
203
+ if (!file) this.viewHint = "noFileToSwitch";
204
+ else if (file.status !== "modified") return;
205
+ else if (patchWidth < MIN_SPLIT_WIDTH) this.viewHint = "tooNarrow";
206
+ else {
207
+ this.viewOverride = view === "split" ? "unified" : "split";
208
+ this.preferences.onViewChange?.(this.viewOverride);
209
+ this.viewHint = undefined;
210
+ }
211
+ } else if (this.focus === "tree" && (matchesKey(data, "j") || matchesKey(data, "k"))) {
212
+ const next = this.tree.moveFile(this.selected, matchesKey(data, "j") ? 1 : -1);
213
+ if (next !== undefined) this.tree.selectFile(next);
214
+ this.select(next);
215
+ } else if (this.focus === "tree") {
216
+ if (matchesKey(data, "up") || matchesKey(data, "down")) this.select(this.tree.move(matchesKey(data, "up") ? -1 : 1));
217
+ else if (matchesKey(data, "pageUp") || matchesKey(data, "pageDown")) this.select(this.tree.move(matchesKey(data, "pageUp") ? -Math.max(1, height) : Math.max(1, height)));
218
+ else if (matchesKey(data, "enter") || matchesKey(data, "space")) {
219
+ const file = this.tree.toggle();
220
+ this.select(file);
221
+ if (file !== undefined) this.focus = "diff";
222
+ }
223
+ } else {
224
+ if (this.patch && (matchesKey(data, "n") || matchesKey(data, "p"))) {
225
+ this.top = this.patch.reflowTop(patchWidth, view, this.top);
226
+ const direction = matchesKey(data, "n") ? 1 : -1;
227
+ const count = this.patch.changeCount();
228
+ let targetIndex: number | undefined;
229
+ if (this.activeChange !== undefined && this.activeChange < count) {
230
+ const candidate = this.activeChange + direction;
231
+ if (candidate >= 0 && candidate < count) targetIndex = candidate;
232
+ } else {
233
+ targetIndex = this.patch.adjacentChangeIndex(this.top, direction);
234
+ }
235
+ if (targetIndex !== undefined) {
236
+ const row = this.patch.changeRow(targetIndex);
237
+ if (row !== undefined) {
238
+ this.activeChange = targetIndex;
239
+ this.top = Math.max(0, row - JUMP_LEAD_LINES);
240
+ this.changeJump = true;
241
+ }
242
+ }
243
+ } else if (matchesKey(data, "up") || matchesKey(data, "down") || matchesKey(data, "j") || matchesKey(data, "k")) this.scrollDiff(matchesKey(data, "up") || matchesKey(data, "k") ? -1 : 1);
244
+ else if (matchesKey(data, "pageUp") || matchesKey(data, "pageDown")) this.scrollDiff(matchesKey(data, "pageUp") ? -Math.max(1, height) : Math.max(1, height));
245
+ else if (matchesKey(data, "home") || matchesKey(data, "end")) {
246
+ this.changeJump = false;
247
+ this.activeChange = undefined;
248
+ this.top = matchesKey(data, "home") ? 0 : Math.max(0, (this.patch?.rowCount(patchWidth, view) ?? 0) - Math.max(1, height));
249
+ }
250
+ }
251
+ this.host.requestRender();
252
+ }
253
+
254
+ private isOnDivider(treeWidth: number, bodyEnd: number): boolean {
255
+ return treeWidth > 0 && this.pointer !== undefined && this.pointer.x >= treeWidth - 1 && this.pointer.x <= treeWidth && this.pointer.y >= 1 && this.pointer.y < bodyEnd;
256
+ }
257
+
258
+ private resizeTree(x: number, maxWidth: number): number {
259
+ this.treeCollapsed = x <= 0;
260
+ if (this.treeCollapsed) {
261
+ this.focus = "diff";
262
+ return 0;
263
+ }
264
+ this.treeWidthOverride = Math.max(FILE_TREE_MIN_WIDTH, Math.min(maxWidth, x + 1));
265
+ return this.treeWidthOverride;
266
+ }
267
+
268
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult {
269
+ // Captured event bounds can predate a terminal resize.
270
+ const dragging = this.dividerGesture === "dragging";
271
+ const width = dragging ? this.host.terminal.columns : event.width;
272
+ const rows = dragging ? this.host.terminal.rows : event.height;
273
+ const { treeWidth, maxTreeWidth, patchWidth, view, bodyEnd } = this.layout(width, rows);
274
+ const wasHovered = this.isOnDivider(treeWidth, bodyEnd);
275
+ this.pointer = { x: event.x, y: event.y };
276
+ const hovered = this.isOnDivider(treeWidth, bodyEnd);
277
+ if (event.type === "move") return { handled: true, render: wasHovered !== hovered };
278
+ if (event.type === "press") {
279
+ this.dividerGesture = undefined;
280
+ if (event.button === "left" && hovered) {
281
+ if (Date.now() - this.lastDividerClick < 300) {
282
+ this.lastDividerClick = 0;
283
+ this.treeWidthOverride = undefined;
284
+ this.dividerGesture = "released";
285
+ return { handled: true, capture: true };
286
+ }
287
+ this.dividerMoved = false;
288
+ this.dividerGesture = "dragging";
289
+ return { handled: true, capture: true };
290
+ }
291
+ this.lastDividerClick = 0;
292
+ }
293
+ if (this.dividerGesture) {
294
+ if (this.host.terminal.columns < 90 || !this.files.length) {
295
+ this.dividerGesture = "released";
296
+ this.lastDividerClick = 0;
297
+ }
298
+ if (event.type === "release") {
299
+ if (this.dividerGesture === "dragging") {
300
+ if (this.dividerMoved) this.resizeTree(event.x, maxTreeWidth);
301
+ this.lastDividerClick = this.dividerMoved ? 0 : Date.now();
302
+ }
303
+ this.dividerGesture = "released";
304
+ return { handled: true, render: true };
305
+ }
306
+ if (event.type === "click") {
307
+ // pi synthesizes a click after an unmoved press/release.
308
+ this.dividerGesture = undefined;
309
+ return { handled: true, render: false };
310
+ }
311
+ if (event.type === "drag") {
312
+ if (this.dividerGesture !== "dragging" || event.button !== "left") return { handled: true, render: false };
313
+ this.dividerMoved = true;
314
+ this.lastDividerClick = 0;
315
+ return { handled: true, render: this.resizeTree(event.x, maxTreeWidth) !== treeWidth };
316
+ }
317
+ }
318
+ const treeOnly = !treeWidth && this.focus === "tree" && this.files.length > 0;
319
+ const inTree = treeOnly || (treeWidth > 0 && event.x < treeWidth - 1);
320
+ const treeTop = treeOnly ? 2 : 3;
321
+ const treeHeight = Math.max(0, bodyEnd - treeTop);
322
+ if (event.type === "wheel") {
323
+ if (event.y >= treeTop && event.y < treeTop + treeHeight && inTree) {
324
+ this.focus = "tree";
325
+ this.tree.scroll(event.wheelDelta ?? 0, treeHeight);
326
+ } else if (!inTree && event.y >= 3 && event.y < bodyEnd) {
327
+ this.focus = "diff";
328
+ this.scrollDiff(event.wheelDelta ?? 0);
329
+ }
330
+ return { handled: true };
331
+ }
332
+ if (event.type === "click" && event.button === "left") {
333
+ if (event.y === 0 && event.x < this.showFilesButton) this.handleInput("[");
334
+ else if (event.y === 0 && this.viewButton >= 0 && event.x >= this.viewButton && event.x < this.viewButton + visibleWidth(messages[this.language].switchView)) this.handleInput("v");
335
+ else if (inTree && event.y >= treeTop && event.y < treeTop + treeHeight) {
336
+ this.focus = "tree";
337
+ const selected = this.tree.clickRow(event.y - treeTop);
338
+ this.select(selected);
339
+ if (treeOnly && selected !== undefined) this.focus = "diff";
340
+ } else if (!inTree && event.y === 2 && this.patch && event.x >= this.contextButton.start && event.x < this.contextButton.end) {
341
+ this.focus = "diff";
342
+ this.patch.toggleContext();
343
+ this.top = this.patch.reflowTop(patchWidth, view, this.top);
344
+ } else if (!inTree && event.y > 0 && event.y < bodyEnd) {
345
+ this.focus = "diff";
346
+ if (event.y >= 3 && this.patch) {
347
+ this.top = this.patch.reflowTop(patchWidth, view, this.top);
348
+ this.patch.expandFoldAt(this.top + (event.y - 3));
349
+ }
350
+ }
351
+ return { handled: true, focus: true };
352
+ }
353
+ // Consume overlay mouse events so they cannot scroll the conversation underneath.
354
+ return { handled: true, render: wasHovered !== hovered };
355
+ }
356
+
357
+ render(width: number): string[] {
358
+ const rows = Math.max(1, this.host.terminal.rows);
359
+ const { inset, treeWidth, patchWidth, view, height, notice, bodyEnd } = this.layout(width, rows);
360
+ if ((width < 90 || !this.files.length) && this.dividerGesture === "dragging") {
361
+ this.dividerGesture = "released";
362
+ this.lastDividerClick = 0;
363
+ }
364
+ const dividerActive = treeWidth > 0 && (this.dividerGesture === "dragging" || this.isOnDivider(treeWidth, bodyEnd));
365
+ if (patchWidth >= MIN_SPLIT_WIDTH && this.viewHint === "tooNarrow") this.viewHint = undefined;
366
+ this.top = this.patch?.reflowTop(patchWidth, view, this.top) ?? 0;
367
+ const totalRows = this.patch?.rowCount(patchWidth, view) ?? 0;
368
+ // A jump can place the final change near the top even when fewer rows remain.
369
+ this.top = Math.max(0, Math.min(this.top, totalRows - (this.changeJump ? 1 : Math.max(1, height))));
370
+ const theme = this.theme;
371
+ const text = messages[this.language];
372
+ const file = this.selected === undefined ? undefined : this.files[this.selected];
373
+ const fixedUnified = file !== undefined && file.status !== "modified";
374
+ const heading = theme.bold(theme.fg("accent", `${displayText(localize(this.title, this.language))} · ${text.fileCount(this.files.length)} `)
375
+ + theme.fg("success", `+${this.totals.additions}`) + " " + theme.fg("error", `-${this.totals.deletions}`) + " ");
376
+ const showFiles = this.treeCollapsed && this.files.length ? theme.bold(theme.fg("accent", text.showFiles)) + " " : "";
377
+ this.showFilesButton = showFiles ? visibleWidth(text.showFiles) : 0;
378
+ this.viewButton = fixedUnified ? -1 : visibleWidth(showFiles + heading);
379
+ const header = showFiles + heading + theme.bold(theme.fg("accent", fixedUnified ? text.unifiedOnly : text.switchView));
380
+ const lines = [safeBg(theme, "customMessageBg", fit(header, width))];
381
+ const bodyHeight = Math.max(0, bodyEnd - 1);
382
+ this.contextButton = { start: -1, end: -1 };
383
+ if (!treeWidth && this.focus === "tree" && this.files.length) {
384
+ lines.push(fit(theme.bold(theme.fg("accent", text.files)), width), ...this.tree.render(width, Math.max(0, bodyHeight - 1), theme, true, this.selected, this.language));
385
+ } else {
386
+ const label = file ? displayText(file.file) : localize(this.emptyMessage ?? text.noChanges, this.language);
387
+ const note = file?.cumulativeFallback ? text.cumulativeFallback
388
+ : file?.baselineUnknown ? text.baselineUnknown : "";
389
+ const counts = file ? theme.fg("success", `+${file.additions}`) + " " + theme.fg("error", `-${file.deletions}`) : "";
390
+ const effectiveView = this.patch?.effectiveView(view) ?? view;
391
+ const layoutLabel = fixedUnified ? text.fixedUnified : effectiveView === "split" ? text.split : text.unified;
392
+ const hint = this.viewHint ? text[this.viewHint] : note;
393
+ const changeCount = this.patch?.changeCount() ?? 0;
394
+ const changeLabel = changeCount > 0 ? ` · ${text.changeProgress(this.activeChange !== undefined ? this.activeChange + 1 : undefined, changeCount)}` : "";
395
+ const scrollPct = totalRows > height && height > 0 ? ` · ${Math.min(100, Math.round((this.top / Math.max(1, totalRows - height)) * 100))}%` : "";
396
+ const context = this.patch?.contextState();
397
+ const detailPrefix = counts + theme.fg("muted", ` · ${layoutLabel}${hint ? ` · ${hint}` : ""}${changeLabel}${scrollPct}`);
398
+ let detail = detailPrefix;
399
+ if (context) {
400
+ const buttonLabel = text[context];
401
+ const sep = theme.fg("muted", " · ");
402
+ const paneStart = treeWidth + inset;
403
+ const start = paneStart + visibleWidth(detailPrefix) + 3;
404
+ const end = Math.min(paneStart + patchWidth, start + visibleWidth(buttonLabel));
405
+ if (start < paneStart + patchWidth) this.contextButton = { start, end };
406
+ detail += sep + theme.bold(theme.fg("accent", buttonLabel));
407
+ }
408
+ detail += theme.fg("muted", ` · ${text.wrap}`);
409
+ const titleLine = this.focus === "diff" && file ? theme.bold(theme.fg("accent", label)) : theme.bold(label);
410
+ const metadata = [fitEllipsis(titleLine, patchWidth), fit(detail, patchWidth)];
411
+ const content = this.patch?.renderViewport(patchWidth, height, this.top, view, theme) ?? Array.from({ length: height }, () => fit("", patchWidth));
412
+ const pane = [...metadata, ...content];
413
+ const treeRule = treeWidth ? fit(safeFg(theme, "borderMuted", "muted", "─".repeat(Math.max(0, treeWidth - 1))), treeWidth - 1) : "";
414
+ const left = treeWidth ? [fit(theme.bold(theme.fg(this.focus === "tree" ? "accent" : "muted", text.files)), treeWidth - 1), treeRule, ...this.tree.render(treeWidth - 1, height, theme, this.focus === "tree", this.selected, this.language)] : [];
415
+ const divider = theme.fg(dividerActive ? "accent" : "borderMuted", "│");
416
+ const separator = dividerActive ? theme.bg("selectedBg", divider) : divider;
417
+ const showScrollbar = inset >= 1 && totalRows > height && height >= 2;
418
+ const thumbSize = showScrollbar ? Math.max(1, Math.round((height / totalRows) * height)) : 0;
419
+ const thumbStart = showScrollbar ? Math.min(height - thumbSize, Math.round((this.top / Math.max(1, totalRows - height)) * (height - thumbSize))) : 0;
420
+ const thumbGlyph = showScrollbar ? safeFg(theme, "scrollbarThumb", "muted", "┃") : "";
421
+ const trackGlyph = showScrollbar ? safeFg(theme, "scrollbarTrack", "borderMuted", "│") : "";
422
+ for (let i = 0; i < bodyHeight; i++) {
423
+ const tree = treeWidth ? fit(left[i] ?? "", treeWidth - 1) + separator : "";
424
+ let rightPad = " ".repeat(inset);
425
+ if (showScrollbar && i >= FILE_HEADER_HEIGHT) {
426
+ const contentRow = i - FILE_HEADER_HEIGHT;
427
+ const bar = contentRow >= thumbStart && contentRow < thumbStart + thumbSize ? thumbGlyph : trackGlyph;
428
+ rightPad = " ".repeat(inset - 1) + bar;
429
+ }
430
+ lines.push(fit(tree + " ".repeat(inset) + fit(pane[i] ?? "", patchWidth) + rightPad, width));
431
+ }
432
+ }
433
+ for (const line of notice) lines.push(fit(theme.fg("muted", line), width));
434
+ if (rows > 1) {
435
+ const dragPrefix = dividerActive ? `${text.dragDivider} · ` : "";
436
+ const footerText = text.footer(fixedUnified, this.focus, Math.max(0, width - visibleWidth(dragPrefix)));
437
+ const footer = (dividerActive ? theme.fg("accent", dragPrefix) : "") + theme.fg("muted", footerText);
438
+ lines.push(safeBg(theme, "customMessageBg", fit(footer, width)));
439
+ }
440
+ return lines.slice(0, rows);
441
+ }
442
+
443
+ invalidate(): void {
444
+ for (const cached of this.patchCache.values()) cached.invalidate();
445
+ }
446
+ }
@@ -0,0 +1,183 @@
1
+ import { isAbsolute } from "node:path"
2
+
3
+ export type FileTreeItem = {
4
+ readonly file: string
5
+ readonly status?: "added" | "deleted" | "modified"
6
+ }
7
+
8
+ export type FileTreeNode = {
9
+ readonly id: number
10
+ readonly name: string
11
+ readonly parent: number | undefined
12
+ readonly children: number[]
13
+ readonly depth: number
14
+ readonly kind: "directory" | "file"
15
+ readonly fileIndex?: number
16
+ readonly externalRoot?: boolean
17
+ }
18
+
19
+ export type FileTree = {
20
+ readonly roots: number[]
21
+ readonly nodes: FileTreeNode[]
22
+ }
23
+
24
+ export type FileTreeRow = {
25
+ readonly id: number
26
+ readonly depth: number
27
+ readonly kind: "directory" | "file"
28
+ readonly name: string
29
+ readonly fileIndex?: number
30
+ readonly externalRoot?: boolean
31
+ }
32
+
33
+ export function buildFileTree(files: readonly FileTreeItem[]): FileTree {
34
+ const roots: number[] = []
35
+ const nodes: FileTreeNode[] = []
36
+ const directoryByPath = new Map<string, number>()
37
+
38
+ files.forEach((file, fileIndex) => {
39
+ const external = isAbsolute(file.file)
40
+ const segments = (external && process.platform === "win32" ? file.file.replaceAll("\\", "/") : file.file).split("/").filter(Boolean)
41
+ if (segments.length === 0) return
42
+ if (external) segments.unshift("External files")
43
+
44
+ const parent = segments.slice(0, -1).reduce(
45
+ (state, segment) => {
46
+ const directoryPath = state.path ? `${state.path}/${segment}` : segment
47
+ const existing = directoryByPath.get(directoryPath)
48
+ if (existing !== undefined) return { id: existing, path: directoryPath, depth: state.depth + 1 }
49
+
50
+ const id = addFileTreeNode(nodes, roots, {
51
+ name: segment,
52
+ parent: state.id,
53
+ depth: state.depth,
54
+ kind: "directory",
55
+ ...(external && state.depth === 0 ? { externalRoot: true } : {}),
56
+ })
57
+ directoryByPath.set(directoryPath, id)
58
+ return { id, path: directoryPath, depth: state.depth + 1 }
59
+ },
60
+ { id: undefined as number | undefined, path: external ? "\0external" : "", depth: 0 },
61
+ )
62
+
63
+ addFileTreeNode(nodes, roots, {
64
+ name: segments[segments.length - 1]!,
65
+ parent: parent.id,
66
+ depth: parent.depth,
67
+ kind: "file",
68
+ fileIndex,
69
+ })
70
+ })
71
+
72
+ const tree = { roots, nodes }
73
+ tree.roots.sort((left, right) => compareFileTreeNodes(tree, left, right))
74
+ tree.nodes.forEach((node) => node.children.sort((left, right) => compareFileTreeNodes(tree, left, right)))
75
+ return tree
76
+ }
77
+
78
+ export function flattenFileTree(tree: FileTree, expanded?: ReadonlySet<number>): FileTreeRow[] {
79
+ const rows: FileTreeRow[] = []
80
+ const visit = (id: number, depth: number) => {
81
+ const node = tree.nodes[id]!
82
+ if (node.kind === "file") {
83
+ rows.push({
84
+ id: node.id,
85
+ depth,
86
+ kind: node.kind,
87
+ name: node.name,
88
+ fileIndex: node.fileIndex,
89
+ })
90
+ return
91
+ }
92
+
93
+ const chain = collapsedFileTreeDirectoryChain(tree, node.id)
94
+ const last = chain[chain.length - 1]!
95
+ rows.push({
96
+ id: node.id,
97
+ depth,
98
+ kind: node.kind,
99
+ name: chain.map((item) => item.name).join("/"),
100
+ fileIndex: node.fileIndex,
101
+ ...(node.externalRoot ? { externalRoot: true } : {}),
102
+ })
103
+ if (!expanded || expanded.has(node.id)) last.children.forEach((child) => visit(child, depth + 1))
104
+ }
105
+ tree.roots.forEach((root) => visit(root, 0))
106
+ return rows
107
+ }
108
+
109
+ function collapsedFileTreeDirectoryChain(tree: FileTree, id: number): FileTreeNode[] {
110
+ const node = tree.nodes[id]!
111
+ if (node.externalRoot) return [node]
112
+ const child = node.children.length === 1 ? tree.nodes[node.children[0]!] : undefined
113
+ if (child?.kind !== "directory") return [node]
114
+ return [node, ...collapsedFileTreeDirectoryChain(tree, child.id)]
115
+ }
116
+
117
+ export function compareFileTreeNodes(tree: FileTree, left: number, right: number) {
118
+ const leftNode = tree.nodes[left]!
119
+ const rightNode = tree.nodes[right]!
120
+ if (leftNode.kind !== rightNode.kind) return leftNode.kind === "directory" ? -1 : 1
121
+ if (leftNode.name < rightNode.name) return -1
122
+ if (leftNode.name > rightNode.name) return 1
123
+ return left - right
124
+ }
125
+
126
+ export function fileTreeFileSelection(tree: FileTree, fileIndex: number) {
127
+ const node = tree.nodes.find((item) => item.kind === "file" && item.fileIndex === fileIndex)
128
+ if (!node) return undefined
129
+ return {
130
+ expandedNodes: fileTreeParentDirectories(tree, node.id),
131
+ }
132
+ }
133
+
134
+ export function singlePatchFileIndex(
135
+ selected: number | undefined,
136
+ current: number | undefined,
137
+ first: number | undefined,
138
+ ) {
139
+ return selected ?? current ?? first
140
+ }
141
+
142
+ export function orderedPatchFileIndexes(rows: readonly FileTreeRow[]) {
143
+ return rows.flatMap((row) => (row.fileIndex === undefined ? [] : [row.fileIndex]))
144
+ }
145
+
146
+ export function showDiffViewerFileTree(showFileTree: boolean, fileCount: number) {
147
+ return showFileTree && fileCount > 0
148
+ }
149
+
150
+ export function movePatchFileIndex(fileIndexes: readonly number[], current: number | undefined, offset: number) {
151
+ if (fileIndexes.length === 0) return undefined
152
+ const index = current === undefined ? -1 : fileIndexes.indexOf(current)
153
+ if (index === -1) return fileIndexes[0]
154
+ return fileIndexes[Math.max(0, Math.min(fileIndexes.length - 1, index + offset))]
155
+ }
156
+
157
+ export function allExpandedFileTreeDirectories(tree: FileTree) {
158
+ return new Set(tree.nodes.filter((node) => node.kind === "directory").map((node) => node.id))
159
+ }
160
+
161
+ export function toggleFileTreeDirectory(tree: FileTree, expanded: ReadonlySet<number>, selected: number | undefined) {
162
+ if (selected === undefined || tree.nodes[selected]?.kind !== "directory") return expanded
163
+ const next = new Set(expanded)
164
+ if (next.has(selected)) next.delete(selected)
165
+ else next.add(selected)
166
+ return next
167
+ }
168
+
169
+ function addFileTreeNode(nodes: FileTreeNode[], roots: number[], input: Omit<FileTreeNode, "id" | "children">) {
170
+ const id = nodes.length
171
+ nodes.push({ ...input, id, children: [] })
172
+ if (input.parent === undefined) roots.push(id)
173
+ else nodes[input.parent]!.children.push(id)
174
+ return id
175
+ }
176
+
177
+ function fileTreeParentDirectories(tree: FileTree, id: number) {
178
+ const result = new Set<number>()
179
+ for (let parent = tree.nodes[id]?.parent; parent !== undefined; parent = tree.nodes[parent]?.parent) {
180
+ result.add(parent)
181
+ }
182
+ return result
183
+ }