@lyrumu/pi-diff 0.0.0-stage → 0.1.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,310 @@
1
+ import { matchesKey, visibleWidth, 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, 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
+ export const FULLSCREEN_OPTIONS = {
15
+ overlay: true,
16
+ overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0, margin: 0 } satisfies OverlayOptions,
17
+ } as const;
18
+
19
+ export interface DiffScreenPreferences {
20
+ language?: Language;
21
+ onLanguageChange?: (language: Language) => void;
22
+ view?: DiffView;
23
+ onViewChange?: (view: DiffView) => void;
24
+ emptyMessage?: LocalizedText;
25
+ notice?: LocalizedText;
26
+ onScopeChange?: (direction: 1 | -1) => void;
27
+ }
28
+
29
+ /** Selected-file view on a fullscreen overlay; all data comes from FilePatch[]. */
30
+ export class DiffScreen implements Component {
31
+ private readonly host: TuiHost;
32
+ private readonly theme: Theme;
33
+ private title: LocalizedText;
34
+ private language: Language;
35
+ private files: readonly FilePatch[];
36
+ private readonly close: () => void;
37
+ private readonly preferences: DiffScreenPreferences;
38
+ private tree: FileTree;
39
+ private emptyMessage: LocalizedText | undefined;
40
+ private notice: LocalizedText | undefined;
41
+ private selected: number | undefined;
42
+ private patch: PatchDiff | undefined;
43
+ private focus: "tree" | "diff" = "diff";
44
+ private viewOverride: DiffView | undefined;
45
+ private top = 0;
46
+ private viewButton = 0;
47
+ private showFilesButton = 0;
48
+ private viewHint: "noFileToSwitch" | "tooNarrow" | undefined;
49
+ private treeWidthOverride: number | undefined;
50
+ private treeCollapsed = false;
51
+ private dividerGesture: "dragging" | "released" | undefined;
52
+ private dividerMoved = false;
53
+ private lastDividerClick = 0;
54
+ private pointer: { x: number; y: number } | undefined;
55
+
56
+ constructor(host: TuiHost, theme: Theme, title: LocalizedText, files: readonly FilePatch[], close: () => void, preferences: DiffScreenPreferences = {}) {
57
+ this.host = host;
58
+ this.theme = theme;
59
+ this.title = title;
60
+ this.files = files;
61
+ this.close = close;
62
+ this.preferences = preferences;
63
+ this.language = preferences.language ?? "en";
64
+ this.emptyMessage = preferences.emptyMessage;
65
+ this.notice = preferences.notice;
66
+ this.viewOverride = preferences.view;
67
+ this.tree = new FileTree(files);
68
+ this.select(this.tree.selectedFile());
69
+ }
70
+
71
+ /** Replace the source inside the existing overlay; never expose the chat between scopes. */
72
+ setData(title: LocalizedText, files: readonly FilePatch[], status: { emptyMessage?: LocalizedText; notice?: LocalizedText } = {}): void {
73
+ this.title = title;
74
+ this.files = files;
75
+ this.emptyMessage = status.emptyMessage;
76
+ this.notice = status.notice;
77
+ this.tree = new FileTree(files);
78
+ this.selected = undefined;
79
+ this.patch = undefined;
80
+ this.top = 0;
81
+ this.focus = "diff";
82
+ this.viewHint = undefined;
83
+ this.pointer = undefined;
84
+ this.lastDividerClick = 0;
85
+ if (this.dividerGesture === "dragging") this.dividerGesture = "released";
86
+ this.select(this.tree.selectedFile());
87
+ this.host.requestRender();
88
+ }
89
+
90
+ private select(index: number | undefined): void {
91
+ if (index === undefined || index === this.selected) return;
92
+ const file = this.files[index];
93
+ if (!file) return;
94
+ this.selected = index;
95
+ this.patch = new PatchDiff(file, this.language);
96
+ this.top = 0;
97
+ this.viewHint = undefined;
98
+ }
99
+
100
+ private layout(width: number) {
101
+ const inset = width < 90 ? 0 : 2;
102
+ const maxTreeWidth = Math.min(Math.floor(width / 4), width - inset * 2 - MIN_PATCH_WIDTH);
103
+ const defaultTreeWidth = Math.max(30, Math.min(FILE_TREE_MAX_WIDTH, Math.floor(width / 4)));
104
+ const treeWidth = width >= 90 && this.files.length > 0 && !this.treeCollapsed
105
+ ? Math.min(maxTreeWidth, Math.max(FILE_TREE_MIN_WIDTH, this.treeWidthOverride ?? defaultTreeWidth)) : 0;
106
+ const patchWidth = Math.max(1, width - treeWidth - inset * 2);
107
+ const view: DiffView = patchWidth >= MIN_SPLIT_WIDTH ? this.viewOverride ?? "split" : "unified";
108
+ const height = Math.max(0, this.host.terminal.rows - 2 - FILE_HEADER_HEIGHT);
109
+ return { inset, treeWidth, maxTreeWidth, patchWidth, view, height };
110
+ }
111
+
112
+ handleInput(data: string): void {
113
+ if (matchesKey(data, "escape") || matchesKey(data, "q")) {
114
+ this.close();
115
+ return;
116
+ }
117
+ if (matchesKey(data, "tab") || matchesKey(data, "shift+tab")) {
118
+ this.preferences.onScopeChange?.(matchesKey(data, "tab") ? 1 : -1);
119
+ return;
120
+ }
121
+ if (matchesKey(data, "l") || matchesKey(data, "shift+l")) {
122
+ this.language = this.language === "en" ? "zh-CN" : "en";
123
+ this.patch?.setLanguage(this.language);
124
+ this.preferences.onLanguageChange?.(this.language);
125
+ this.host.requestRender();
126
+ return;
127
+ }
128
+ const { patchWidth, view, height } = this.layout(this.host.terminal.columns);
129
+ if (matchesKey(data, "[")) {
130
+ // Explicit reopening takes precedence over pending drag/release events.
131
+ if (this.dividerGesture === "dragging") this.dividerGesture = "released";
132
+ this.lastDividerClick = 0;
133
+ this.treeCollapsed = false;
134
+ this.focus = "tree";
135
+ } else if (matchesKey(data, "]")) this.focus = "diff";
136
+ else if (matchesKey(data, "v") || matchesKey(data, "shift+v")) {
137
+ const file = this.selected === undefined ? undefined : this.files[this.selected];
138
+ if (!file) this.viewHint = "noFileToSwitch";
139
+ else if (file.status !== "modified") return;
140
+ else if (patchWidth < MIN_SPLIT_WIDTH) this.viewHint = "tooNarrow";
141
+ else {
142
+ this.viewOverride = view === "split" ? "unified" : "split";
143
+ this.preferences.onViewChange?.(this.viewOverride);
144
+ this.viewHint = undefined;
145
+ }
146
+ } else if (this.focus === "tree" && (matchesKey(data, "j") || matchesKey(data, "k"))) {
147
+ const next = this.tree.moveFile(this.selected, matchesKey(data, "j") ? 1 : -1);
148
+ if (next !== undefined) this.tree.selectFile(next);
149
+ this.select(next);
150
+ } else if (this.focus === "tree") {
151
+ if (matchesKey(data, "up") || matchesKey(data, "down")) this.select(this.tree.move(matchesKey(data, "up") ? -1 : 1));
152
+ else if (matchesKey(data, "pageUp") || matchesKey(data, "pageDown")) this.select(this.tree.move(matchesKey(data, "pageUp") ? -Math.max(1, height) : Math.max(1, height)));
153
+ else if (matchesKey(data, "enter") || matchesKey(data, "space")) {
154
+ const file = this.tree.toggle();
155
+ this.select(file);
156
+ if (file !== undefined) this.focus = "diff";
157
+ }
158
+ } else {
159
+ if (matchesKey(data, "up") || matchesKey(data, "down") || matchesKey(data, "j") || matchesKey(data, "k")) this.top += matchesKey(data, "up") || matchesKey(data, "k") ? -1 : 1;
160
+ else if (matchesKey(data, "pageUp") || matchesKey(data, "pageDown")) this.top += matchesKey(data, "pageUp") ? -Math.max(1, height) : Math.max(1, height);
161
+ else if (matchesKey(data, "home")) this.top = 0;
162
+ else if (matchesKey(data, "end")) this.top = this.patch?.rowCount(patchWidth, view) ?? 0;
163
+ }
164
+ this.host.requestRender();
165
+ }
166
+
167
+ private isOnDivider(treeWidth: number, height: number): boolean {
168
+ return treeWidth > 0 && this.pointer !== undefined && this.pointer.x >= treeWidth - 1 && this.pointer.x <= treeWidth && this.pointer.y >= 1 && this.pointer.y < height - 1;
169
+ }
170
+
171
+ private resizeTree(x: number, maxWidth: number): number {
172
+ this.treeCollapsed = x <= 0;
173
+ if (this.treeCollapsed) {
174
+ this.focus = "diff";
175
+ return 0;
176
+ }
177
+ this.treeWidthOverride = Math.max(FILE_TREE_MIN_WIDTH, Math.min(maxWidth, x + 1));
178
+ return this.treeWidthOverride;
179
+ }
180
+
181
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult {
182
+ // Captured event bounds can predate a terminal resize.
183
+ const { treeWidth, maxTreeWidth, height } = this.layout(this.dividerGesture === "dragging" ? this.host.terminal.columns : event.width);
184
+ const wasHovered = this.isOnDivider(treeWidth, event.height);
185
+ this.pointer = { x: event.x, y: event.y };
186
+ const hovered = this.isOnDivider(treeWidth, event.height);
187
+ if (event.type === "move") return { handled: true, render: wasHovered !== hovered };
188
+ if (event.type === "press") {
189
+ this.dividerGesture = undefined;
190
+ if (event.button === "left" && hovered) {
191
+ if (Date.now() - this.lastDividerClick < 300) {
192
+ this.lastDividerClick = 0;
193
+ this.treeWidthOverride = undefined;
194
+ this.dividerGesture = "released";
195
+ return { handled: true, capture: true };
196
+ }
197
+ this.dividerMoved = false;
198
+ this.dividerGesture = "dragging";
199
+ return { handled: true, capture: true };
200
+ }
201
+ this.lastDividerClick = 0;
202
+ }
203
+ if (this.dividerGesture) {
204
+ if (this.host.terminal.columns < 90 || !this.files.length) {
205
+ this.dividerGesture = "released";
206
+ this.lastDividerClick = 0;
207
+ }
208
+ if (event.type === "release") {
209
+ if (this.dividerGesture === "dragging") {
210
+ if (this.dividerMoved) this.resizeTree(event.x, maxTreeWidth);
211
+ this.lastDividerClick = this.dividerMoved ? 0 : Date.now();
212
+ }
213
+ this.dividerGesture = "released";
214
+ return { handled: true, render: true };
215
+ }
216
+ if (event.type === "click") {
217
+ // pi synthesizes a click after an unmoved press/release.
218
+ this.dividerGesture = undefined;
219
+ return { handled: true, render: false };
220
+ }
221
+ if (event.type === "drag") {
222
+ if (this.dividerGesture !== "dragging" || event.button !== "left") return { handled: true, render: false };
223
+ this.dividerMoved = true;
224
+ this.lastDividerClick = 0;
225
+ return { handled: true, render: this.resizeTree(event.x, maxTreeWidth) !== treeWidth };
226
+ }
227
+ }
228
+ const treeOnly = !treeWidth && this.focus === "tree" && this.files.length > 0;
229
+ const inTree = treeOnly || (treeWidth > 0 && event.x < treeWidth - 1);
230
+ const treeTop = treeOnly ? 2 : 3;
231
+ const treeHeight = treeOnly ? Math.max(0, event.height - 3) : height;
232
+ if (event.type === "wheel") {
233
+ if (event.y >= treeTop && event.y < treeTop + treeHeight && inTree) {
234
+ this.focus = "tree";
235
+ this.tree.scroll(event.wheelDelta ?? 0, treeHeight);
236
+ } else if (!inTree && event.y >= 3 && event.y < event.height - 1) {
237
+ this.focus = "diff";
238
+ this.top += event.wheelDelta ?? 0;
239
+ }
240
+ return { handled: true };
241
+ }
242
+ if (event.type === "click" && event.button === "left") {
243
+ if (event.y === 0 && event.x < this.showFilesButton) this.handleInput("[");
244
+ else if (event.y === 0 && this.viewButton >= 0 && event.x >= this.viewButton && event.x < this.viewButton + visibleWidth(messages[this.language].switchView)) this.handleInput("v");
245
+ else if (inTree && event.y >= treeTop && event.y < treeTop + treeHeight) {
246
+ this.focus = "tree";
247
+ const selected = this.tree.clickRow(event.y - treeTop);
248
+ this.select(selected);
249
+ if (treeOnly && selected !== undefined) this.focus = "diff";
250
+ } else if (!inTree && event.y > 0 && event.y < event.height - 1) this.focus = "diff";
251
+ return { handled: true, focus: true };
252
+ }
253
+ // Consume overlay mouse events so they cannot scroll the conversation underneath.
254
+ return { handled: true, render: wasHovered !== hovered };
255
+ }
256
+
257
+ render(width: number): string[] {
258
+ const rows = Math.max(1, this.host.terminal.rows);
259
+ const { inset, treeWidth, patchWidth, view, height } = this.layout(width);
260
+ if ((width < 90 || !this.files.length) && this.dividerGesture === "dragging") {
261
+ this.dividerGesture = "released";
262
+ this.lastDividerClick = 0;
263
+ }
264
+ const dividerActive = treeWidth > 0 && (this.dividerGesture === "dragging" || this.isOnDivider(treeWidth, rows));
265
+ if (patchWidth >= MIN_SPLIT_WIDTH && this.viewHint === "tooNarrow") this.viewHint = undefined;
266
+ this.top = this.patch?.reflowTop(patchWidth, view, this.top) ?? 0;
267
+ this.top = Math.max(0, Math.min(this.top, (this.patch?.rowCount(patchWidth, view) ?? 0) - Math.max(1, height)));
268
+ const theme = this.theme;
269
+ const text = messages[this.language];
270
+ const file = this.selected === undefined ? undefined : this.files[this.selected];
271
+ const fixedUnified = file !== undefined && file.status !== "modified";
272
+ const totals = this.files.reduce((sum, file) => ({ additions: sum.additions + file.additions, deletions: sum.deletions + file.deletions }), { additions: 0, deletions: 0 });
273
+ const heading = theme.bold(theme.fg("accent", `${displayText(localize(this.title, this.language))}${this.notice ? ` · ${localize(this.notice, this.language)}` : ""} · ${text.fileCount(this.files.length)} `)
274
+ + theme.fg("success", `+${totals.additions}`) + " " + theme.fg("error", `-${totals.deletions}`) + " ");
275
+ const showFiles = this.treeCollapsed && this.files.length ? theme.bold(theme.fg("accent", text.showFiles)) + " " : "";
276
+ this.showFilesButton = showFiles ? visibleWidth(text.showFiles) : 0;
277
+ this.viewButton = fixedUnified ? -1 : visibleWidth(showFiles + heading);
278
+ const header = showFiles + heading + theme.bold(theme.fg("accent", fixedUnified ? text.unifiedOnly : text.switchView));
279
+ const lines = [fit(header, width)];
280
+ const bodyHeight = Math.max(0, rows - 2);
281
+ if (!treeWidth && this.focus === "tree" && this.files.length) {
282
+ lines.push(fit(theme.bold(text.files), width), ...this.tree.render(width, Math.max(0, bodyHeight - 1), theme, true, this.selected));
283
+ } else {
284
+ const label = file ? displayText(file.file) : localize(this.emptyMessage ?? text.noChanges, this.language);
285
+ const note = file?.cumulativeFallback ? text.cumulativeFallback
286
+ : file?.baselineUnknown ? text.baselineUnknown : "";
287
+ const counts = file ? theme.fg("success", `+${file.additions}`) + " " + theme.fg("error", `-${file.deletions}`) : "";
288
+ const effectiveView = this.patch?.effectiveView(view) ?? view;
289
+ const layoutLabel = fixedUnified ? text.fixedUnified : effectiveView === "split" ? text.split : text.unified;
290
+ const hint = this.viewHint ? text[this.viewHint] : note;
291
+ const detail = counts + theme.fg("muted", ` · ${layoutLabel}${hint ? ` · ${hint}` : ""} · ${text.wrap}`);
292
+ const metadata = [fit(theme.bold(label), patchWidth), fit(detail, patchWidth)];
293
+ const content = this.patch?.renderViewport(patchWidth, height, this.top, view, theme) ?? Array.from({ length: height }, () => fit("", patchWidth));
294
+ const pane = [...metadata, ...content];
295
+ const left = treeWidth ? [fit(theme.bold(theme.fg(this.focus === "tree" ? "accent" : "muted", text.files)), treeWidth), fit("", treeWidth), ...this.tree.render(treeWidth - 1, height, theme, this.focus === "tree", this.selected)] : [];
296
+ const divider = theme.fg(dividerActive ? "accent" : "borderMuted", "│");
297
+ const separator = dividerActive ? theme.bg("selectedBg", divider) : divider;
298
+ for (let i = 0; i < bodyHeight; i++) {
299
+ const tree = treeWidth ? fit(left[i] ?? "", treeWidth - 1) + separator : "";
300
+ lines.push(fit(tree + " ".repeat(inset) + fit(pane[i] ?? "", patchWidth) + " ".repeat(inset), width));
301
+ }
302
+ }
303
+ if (rows > 1) lines.push(fit((dividerActive ? theme.fg("accent", `${text.dragDivider} · `) : "") + theme.fg("muted", text.footer(fixedUnified, this.focus)), width));
304
+ return lines.slice(0, rows);
305
+ }
306
+
307
+ invalidate(): void {
308
+ this.patch?.invalidate();
309
+ }
310
+ }
@@ -0,0 +1,174 @@
1
+ export type FileTreeItem = {
2
+ readonly file: string
3
+ readonly status?: "added" | "deleted" | "modified"
4
+ }
5
+
6
+ export type FileTreeNode = {
7
+ readonly id: number
8
+ readonly name: string
9
+ readonly parent: number | undefined
10
+ readonly children: number[]
11
+ readonly depth: number
12
+ readonly kind: "directory" | "file"
13
+ readonly fileIndex?: number
14
+ }
15
+
16
+ export type FileTree = {
17
+ readonly roots: number[]
18
+ readonly nodes: FileTreeNode[]
19
+ }
20
+
21
+ export type FileTreeRow = {
22
+ readonly id: number
23
+ readonly depth: number
24
+ readonly kind: "directory" | "file"
25
+ readonly name: string
26
+ readonly fileIndex?: number
27
+ }
28
+
29
+ export function buildFileTree(files: readonly FileTreeItem[]): FileTree {
30
+ const roots: number[] = []
31
+ const nodes: FileTreeNode[] = []
32
+ const directoryByPath = new Map<string, number>()
33
+
34
+ files.forEach((file, fileIndex) => {
35
+ const segments = file.file.split("/").filter(Boolean)
36
+ if (segments.length === 0) return
37
+
38
+ const parent = segments.slice(0, -1).reduce(
39
+ (state, segment) => {
40
+ const directoryPath = state.path ? `${state.path}/${segment}` : segment
41
+ const existing = directoryByPath.get(directoryPath)
42
+ if (existing !== undefined) return { id: existing, path: directoryPath, depth: state.depth + 1 }
43
+
44
+ const id = addFileTreeNode(nodes, roots, {
45
+ name: segment,
46
+ parent: state.id,
47
+ depth: state.depth,
48
+ kind: "directory",
49
+ })
50
+ directoryByPath.set(directoryPath, id)
51
+ return { id, path: directoryPath, depth: state.depth + 1 }
52
+ },
53
+ { id: undefined as number | undefined, path: "", depth: 0 },
54
+ )
55
+
56
+ addFileTreeNode(nodes, roots, {
57
+ name: segments[segments.length - 1]!,
58
+ parent: parent.id,
59
+ depth: parent.depth,
60
+ kind: "file",
61
+ fileIndex,
62
+ })
63
+ })
64
+
65
+ const tree = { roots, nodes }
66
+ tree.roots.sort((left, right) => compareFileTreeNodes(tree, left, right))
67
+ tree.nodes.forEach((node) => node.children.sort((left, right) => compareFileTreeNodes(tree, left, right)))
68
+ return tree
69
+ }
70
+
71
+ export function flattenFileTree(tree: FileTree, expanded?: ReadonlySet<number>): FileTreeRow[] {
72
+ const rows: FileTreeRow[] = []
73
+ const visit = (id: number, depth: number) => {
74
+ const node = tree.nodes[id]!
75
+ if (node.kind === "file") {
76
+ rows.push({
77
+ id: node.id,
78
+ depth,
79
+ kind: node.kind,
80
+ name: node.name,
81
+ fileIndex: node.fileIndex,
82
+ })
83
+ return
84
+ }
85
+
86
+ const chain = collapsedFileTreeDirectoryChain(tree, node.id)
87
+ const last = chain[chain.length - 1]!
88
+ rows.push({
89
+ id: node.id,
90
+ depth,
91
+ kind: node.kind,
92
+ name: chain.map((item) => item.name).join("/"),
93
+ fileIndex: node.fileIndex,
94
+ })
95
+ if (!expanded || expanded.has(node.id)) last.children.forEach((child) => visit(child, depth + 1))
96
+ }
97
+ tree.roots.forEach((root) => visit(root, 0))
98
+ return rows
99
+ }
100
+
101
+ function collapsedFileTreeDirectoryChain(tree: FileTree, id: number): FileTreeNode[] {
102
+ const node = tree.nodes[id]!
103
+ const child = node.children.length === 1 ? tree.nodes[node.children[0]!] : undefined
104
+ if (child?.kind !== "directory") return [node]
105
+ return [node, ...collapsedFileTreeDirectoryChain(tree, child.id)]
106
+ }
107
+
108
+ export function compareFileTreeNodes(tree: FileTree, left: number, right: number) {
109
+ const leftNode = tree.nodes[left]!
110
+ const rightNode = tree.nodes[right]!
111
+ if (leftNode.kind !== rightNode.kind) return leftNode.kind === "directory" ? -1 : 1
112
+ if (leftNode.name < rightNode.name) return -1
113
+ if (leftNode.name > rightNode.name) return 1
114
+ return left - right
115
+ }
116
+
117
+ export function fileTreeFileSelection(tree: FileTree, fileIndex: number) {
118
+ const node = tree.nodes.find((item) => item.kind === "file" && item.fileIndex === fileIndex)
119
+ if (!node) return undefined
120
+ return {
121
+ expandedNodes: fileTreeParentDirectories(tree, node.id),
122
+ }
123
+ }
124
+
125
+ export function singlePatchFileIndex(
126
+ selected: number | undefined,
127
+ current: number | undefined,
128
+ first: number | undefined,
129
+ ) {
130
+ return selected ?? current ?? first
131
+ }
132
+
133
+ export function orderedPatchFileIndexes(rows: readonly FileTreeRow[]) {
134
+ return rows.flatMap((row) => (row.fileIndex === undefined ? [] : [row.fileIndex]))
135
+ }
136
+
137
+ export function showDiffViewerFileTree(showFileTree: boolean, fileCount: number) {
138
+ return showFileTree && fileCount > 0
139
+ }
140
+
141
+ export function movePatchFileIndex(fileIndexes: readonly number[], current: number | undefined, offset: number) {
142
+ if (fileIndexes.length === 0) return undefined
143
+ const index = current === undefined ? -1 : fileIndexes.indexOf(current)
144
+ if (index === -1) return fileIndexes[0]
145
+ return fileIndexes[Math.max(0, Math.min(fileIndexes.length - 1, index + offset))]
146
+ }
147
+
148
+ export function allExpandedFileTreeDirectories(tree: FileTree) {
149
+ return new Set(tree.nodes.filter((node) => node.kind === "directory").map((node) => node.id))
150
+ }
151
+
152
+ export function toggleFileTreeDirectory(tree: FileTree, expanded: ReadonlySet<number>, selected: number | undefined) {
153
+ if (selected === undefined || tree.nodes[selected]?.kind !== "directory") return expanded
154
+ const next = new Set(expanded)
155
+ if (next.has(selected)) next.delete(selected)
156
+ else next.add(selected)
157
+ return next
158
+ }
159
+
160
+ function addFileTreeNode(nodes: FileTreeNode[], roots: number[], input: Omit<FileTreeNode, "id" | "children">) {
161
+ const id = nodes.length
162
+ nodes.push({ ...input, id, children: [] })
163
+ if (input.parent === undefined) roots.push(id)
164
+ else nodes[input.parent]!.children.push(id)
165
+ return id
166
+ }
167
+
168
+ function fileTreeParentDirectories(tree: FileTree, id: number) {
169
+ const result = new Set<number>()
170
+ for (let parent = tree.nodes[id]?.parent; parent !== undefined; parent = tree.nodes[parent]?.parent) {
171
+ result.add(parent)
172
+ }
173
+ return result
174
+ }
@@ -0,0 +1,99 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import type { FilePatch } from "../diff-engine.ts";
3
+ import {
4
+ allExpandedFileTreeDirectories, buildFileTree, fileTreeFileSelection,
5
+ flattenFileTree, movePatchFileIndex, orderedPatchFileIndexes, toggleFileTreeDirectory, type FileTreeRow,
6
+ } from "./file-tree-utils.ts";
7
+ import { displayText, fit } from "./text.ts";
8
+
9
+ /** Tree state and rendering; patch selection remains owned by DiffScreen. */
10
+ export class FileTree {
11
+ private readonly files: readonly FilePatch[];
12
+ private readonly tree: ReturnType<typeof buildFileTree>;
13
+ private expanded: ReadonlySet<number>;
14
+ private rows: FileTreeRow[];
15
+ private readonly fileIndexes: number[];
16
+ private selected = 0;
17
+ private top = 0;
18
+ private revealSelection = true;
19
+
20
+ constructor(files: readonly FilePatch[]) {
21
+ this.files = files;
22
+ this.tree = buildFileTree(files);
23
+ this.expanded = allExpandedFileTreeDirectories(this.tree);
24
+ this.rows = flattenFileTree(this.tree, this.expanded);
25
+ this.fileIndexes = orderedPatchFileIndexes(this.rows);
26
+ this.selected = Math.max(0, this.rows.findIndex((row) => row.fileIndex !== undefined));
27
+ }
28
+
29
+ selectedFile(): number | undefined {
30
+ return this.rows[this.selected]?.fileIndex;
31
+ }
32
+
33
+ moveFile(current: number | undefined, offset: number): number | undefined {
34
+ return movePatchFileIndex(this.fileIndexes, current, offset);
35
+ }
36
+
37
+ move(offset: number): number | undefined {
38
+ this.selected = Math.max(0, Math.min(this.rows.length - 1, this.selected + offset));
39
+ this.revealSelection = true;
40
+ return this.selectedFile();
41
+ }
42
+
43
+ toggle(): number | undefined {
44
+ const row = this.rows[this.selected];
45
+ if (!row) return undefined;
46
+ this.expanded = toggleFileTreeDirectory(this.tree, this.expanded, row.id);
47
+ this.rows = flattenFileTree(this.tree, this.expanded);
48
+ this.selected = Math.max(0, this.rows.findIndex((item) => item.id === row.id));
49
+ this.revealSelection = true;
50
+ return this.selectedFile();
51
+ }
52
+
53
+ selectFile(index: number): void {
54
+ const selection = fileTreeFileSelection(this.tree, index);
55
+ if (!selection) return;
56
+ this.expanded = new Set([...this.expanded, ...selection.expandedNodes]);
57
+ this.rows = flattenFileTree(this.tree, this.expanded);
58
+ this.selected = Math.max(0, this.rows.findIndex((row) => row.fileIndex === index));
59
+ this.revealSelection = true;
60
+ }
61
+
62
+ clickRow(offset: number): number | undefined {
63
+ const index = this.top + offset;
64
+ if (offset < 0 || !this.rows[index]) return undefined;
65
+ this.selected = index;
66
+ this.revealSelection = true;
67
+ return this.rows[index]!.kind === "directory" ? this.toggle() : this.selectedFile();
68
+ }
69
+
70
+ scroll(offset: number, height: number): void {
71
+ this.top = Math.max(0, Math.min(this.rows.length - Math.max(1, height), this.top + offset));
72
+ this.revealSelection = false;
73
+ }
74
+
75
+ render(width: number, height: number, theme: Theme, focused: boolean, fileIndex: number | undefined): string[] {
76
+ this.top = Math.max(0, Math.min(this.top, this.rows.length - height));
77
+ if (this.revealSelection) {
78
+ this.top = Math.min(this.top, this.selected);
79
+ if (this.selected >= this.top + height) this.top = this.selected - height + 1;
80
+ this.revealSelection = false;
81
+ }
82
+ return Array.from({ length: height }, (_, offset) => {
83
+ const index = this.top + offset;
84
+ const row = this.rows[index];
85
+ if (!row) return fit("", width);
86
+ const status = row.fileIndex === undefined ? undefined : this.files[row.fileIndex]?.status;
87
+ const color = status === "added" ? "success" : status === "deleted" ? "error" : "muted";
88
+ const selected = focused ? index === this.selected : row.fileIndex !== undefined && row.fileIndex === fileIndex;
89
+ const prefix = theme.fg(selected ? "accent" : "muted", selected ? "› " : " ");
90
+ const indent = "│ ".repeat(Math.max(0, Math.min(row.depth, Math.floor((width - 8) / 2))));
91
+ const marker = row.kind === "directory" ? (this.expanded.has(row.id) ? "▾ " : "▸ ") : "≡ ";
92
+ const label = `${indent}${marker}${displayText(row.name)}${row.kind === "directory" ? "/" : ""}`;
93
+ const name = selected ? theme.bold(theme.fg("accent", label)) : label;
94
+ const badge = theme.fg(color, status === "added" ? "A" : status === "deleted" ? "D" : status === "modified" ? "M" : " ");
95
+ const line = fit(prefix + badge + " " + name, width);
96
+ return selected ? theme.bg("selectedBg", line) : line;
97
+ });
98
+ }
99
+ }