Skip to content

Commit fa8c556

Browse files
committed
fix(web): handle file/directory path collision when opening PR diff
Git can delete a file and add a directory of the same name in one diff. Pierre's tree throws if both paths are inserted. Give that file a distinct tree path and translate selection back to the diff path. Fixes #12887.
1 parent 99e0852 commit fa8c556

4 files changed

Lines changed: 327 additions & 32 deletions

File tree

‎apps/web/src/components/diffs/DiffFileTree.test.tsx‎

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
88
import type { FileDiffMetadata } from "@pierre/diffs";
99

1010
import { DiffFileTree, type DiffFileTreeEntry } from "./DiffFileTree";
11-
import { diffFileTreeEntries } from "./diffFileTree.logic";
11+
import { diffFileTreeEntries, diffFileTreeModel } from "./diffFileTree.logic";
1212
import { useCodeViewFileReveal } from "./useCodeViewFileReveal";
1313

1414
vi.mock("../../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
@@ -214,6 +214,83 @@ describe("diff tree file activation", () => {
214214
expect(folder.isExpanded()).toBe(false);
215215
});
216216

217+
it("keeps a file and its replacement directory selectable", async () => {
218+
const files: DiffFileTreeEntry[] = [
219+
{ path: "office", status: "deleted" },
220+
{ path: "office/config.ts", status: "added" },
221+
];
222+
const presented = diffFileTreeModel(files.map((file) => file.path));
223+
await mount({ files, selectedPath: "office" });
224+
expect(model().getSelectedPaths()).toEqual([presented.modelPath("office")]);
225+
await activate(presented.modelPath("office"));
226+
await activate(presented.modelPath("office/config.ts"));
227+
expect(targets.map((target) => ("id" in target ? target.id : null))).toEqual([
228+
"office\u0000office",
229+
"office/config.ts\u0000office/config.ts",
230+
]);
231+
targets.length = 0;
232+
await activate("office/");
233+
expect(targets).toEqual([]);
234+
});
235+
236+
it("keeps the reverse directory-to-file pair selectable", async () => {
237+
const files: DiffFileTreeEntry[] = [
238+
{ path: "office/config.ts", status: "deleted" },
239+
{ path: "office", status: "added" },
240+
];
241+
const presented = diffFileTreeModel(files.map((file) => file.path));
242+
await mount({ files });
243+
await activate(presented.modelPath("office/config.ts"));
244+
await activate(presented.modelPath("office"));
245+
expect(targets.map((target) => ("id" in target ? target.id : null))).toEqual([
246+
"office/config.ts\u0000office/config.ts",
247+
"office\u0000office",
248+
]);
249+
});
250+
251+
it("survives a later slice that turns an existing file into a directory prefix", async () => {
252+
await mount({ files: [{ path: "office", status: "deleted" }] });
253+
const files: DiffFileTreeEntry[] = [
254+
{ path: "office", status: "deleted" },
255+
{ path: "office/config.ts", status: "added" },
256+
];
257+
await act(async () => {
258+
renderer!.update(<Panel files={files} />);
259+
});
260+
const presented = diffFileTreeModel(files.map((file) => file.path));
261+
await activate(presented.modelPath("office"));
262+
await activate(presented.modelPath("office/config.ts"));
263+
expect(targets.map((target) => ("id" in target ? target.id : null))).toEqual([
264+
"office\u0000office",
265+
"office/config.ts\u0000office/config.ts",
266+
]);
267+
});
268+
269+
it("keeps both colliding files selectable after a refresh of the same set", async () => {
270+
const files: DiffFileTreeEntry[] = [
271+
{ path: "office", status: "deleted" },
272+
{ path: "office/config.ts", status: "added" },
273+
{ path: "src/features/route.ts", status: "modified" },
274+
];
275+
const presented = diffFileTreeModel(files.map((file) => file.path));
276+
await mount({ files });
277+
const folder = model().getItem("src/features/")!;
278+
if (!("collapse" in folder)) throw new Error("Expected the directory handle");
279+
await act(async () => folder.collapse());
280+
await act(async () => {
281+
renderer!.update(<Panel files={files.map((file) => ({ ...file }))} />);
282+
});
283+
const refreshed = model().getItem("src/features/")!;
284+
if (!("isExpanded" in refreshed)) throw new Error("Expected the directory handle");
285+
expect(refreshed.isExpanded()).toBe(false);
286+
await activate(presented.modelPath("office"));
287+
await activate(presented.modelPath("office/config.ts"));
288+
expect(targets.map((target) => ("id" in target ? target.id : null))).toEqual([
289+
"office\u0000office",
290+
"office/config.ts\u0000office/config.ts",
291+
]);
292+
});
293+
217294
it("does not echo controlled selection, but lets the reader activate it", async () => {
218295
await mount({ selectedPath: "02-short.ts" });
219296
expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);

‎apps/web/src/components/diffs/DiffFileTree.tsx‎

Lines changed: 61 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
buildDiffFileTreeUpdates,
1616
compareDiffFileTreeEntries,
1717
collectDirectoryPaths,
18+
diffFileTreeModel,
1819
diffFileTreePositions,
1920
type DiffFileTreeEntry,
2021
} from "./diffFileTree.logic";
@@ -42,6 +43,9 @@ interface DiffFileTreeProps {
4243
/**
4344
* A directory tree of the files in a diff. Every directory starts open: a diff is a short list
4445
* compared to a workspace, and the reader came for the files, not the folders.
46+
*
47+
* A file replaced by a directory of the same name (or the reverse) is still one tree. Those
48+
* paths are rewritten before they reach Pierre, and selection is translated back.
4549
*/
4650
export function DiffFileTree({
4751
entries,
@@ -55,8 +59,10 @@ export function DiffFileTree({
5559
}: DiffFileTreeProps) {
5660
const { resolvedTheme } = useTheme();
5761
const paths = useMemo(() => entries.map((entry) => entry.path), [entries]);
58-
const directoryPaths = useMemo(() => collectDirectoryPaths(paths), [paths]);
59-
const positions = useMemo(() => diffFileTreePositions(paths), [paths]);
62+
const presented = useMemo(() => diffFileTreeModel(paths), [paths]);
63+
const modelPaths = presented.paths;
64+
const directoryPaths = useMemo(() => collectDirectoryPaths(modelPaths), [modelPaths]);
65+
const positions = useMemo(() => diffFileTreePositions(modelPaths), [modelPaths]);
6066
const [ordering] = useState(() => {
6167
let currentPositions: ReadonlyMap<string, number> = new Map();
6268
return {
@@ -67,21 +73,31 @@ export function DiffFileTree({
6773
};
6874
});
6975
const gitStatus = useMemo<ReadonlyArray<GitStatusEntry>>(
70-
() => entries.map((entry) => ({ path: entry.path, status: entry.status })),
71-
[entries],
76+
() =>
77+
entries.map((entry, index) => ({
78+
path: modelPaths[index] ?? entry.path,
79+
status: entry.status,
80+
})),
81+
[entries, modelPaths],
7282
);
73-
const filePathsRef = useRef<ReadonlySet<string>>(new Set(paths));
83+
const filePathsRef = useRef<ReadonlySet<string>>(new Set(modelPaths));
7484
const onSelectFileRef = useRef(onSelectFile);
85+
const toSelectionPathRef = useRef(presented.selectionPath);
7586
// Selection driven by `selectedPath` below is an echo of a file already on screen, not a
7687
// request to scroll to it again.
7788
const syncingSelectionRef = useRef(false);
78-
const handledRevealRef = useRef<{ path: string; revealRequestId: number } | null>(null);
89+
const handledRevealRef = useRef<{
90+
path: string;
91+
revealRequestId: number;
92+
modelPath: string;
93+
} | null>(null);
7994
const mountedPathsRef = useRef<ReadonlyArray<string> | null>(null);
8095

8196
useEffect(() => {
82-
filePathsRef.current = new Set(paths);
97+
filePathsRef.current = new Set(modelPaths);
8398
onSelectFileRef.current = onSelectFile;
84-
}, [onSelectFile, paths]);
99+
toSelectionPathRef.current = presented.selectionPath;
100+
}, [modelPaths, onSelectFile, presented.selectionPath]);
85101

86102
const { model } = useFileTree({
87103
density: "compact",
@@ -90,8 +106,13 @@ export function DiffFileTree({
90106
icons: T3_PIERRE_ICONS,
91107
onSelectionChange: (selectedPaths) => {
92108
if (syncingSelectionRef.current) return;
93-
const path = selectedPaths.at(-1)?.replace(/\/$/, "");
94-
if (path && filePathsRef.current.has(path)) onSelectFileRef.current(path);
109+
const raw = selectedPaths.at(-1);
110+
if (!raw) return;
111+
// Directory ids end in `/`. A file that shares that directory's name is stored under a
112+
// different model path, so stripping the slash must not select it.
113+
const modelPath = filePathsRef.current.has(raw) ? raw : raw.replace(/\/$/, "");
114+
if (!filePathsRef.current.has(modelPath)) return;
115+
onSelectFileRef.current(toSelectionPathRef.current(modelPath));
95116
},
96117
paths: [],
97118
search: false,
@@ -105,29 +126,30 @@ export function DiffFileTree({
105126
useEffect(() => {
106127
ordering.update(positions);
107128
const mountedPaths = mountedPathsRef.current;
108-
if (mountedPaths === paths) return;
109-
mountedPathsRef.current = paths;
129+
if (mountedPaths === modelPaths) return;
130+
mountedPathsRef.current = modelPaths;
110131
if (mountedPaths === null) {
111-
model.resetPaths(paths);
112-
} else if (mountedPaths.every((path, index) => paths[index] === path)) {
132+
model.resetPaths(modelPaths);
133+
} else if (mountedPaths.every((path, index) => modelPaths[index] === path)) {
113134
// PR slices only append files, so keep the existing tree and its open folders.
114-
const updates = buildDiffFileTreeUpdates(mountedPaths, paths);
135+
const updates = buildDiffFileTreeUpdates(mountedPaths, modelPaths);
115136
if (updates.length > 0) model.batch(updates);
116137
} else {
117-
// A refreshed diff can change the rank of existing siblings. Mutations do not reorder
118-
// those rows, so rebuild while carrying the reader's folder expansion forward.
138+
// A refreshed diff can change the rank of existing siblings. A file that becomes a
139+
// directory prefix also changes its model path, which Pierre cannot rename in place.
140+
// Rebuild while carrying the reader's folder expansion forward.
119141
const collapsedDirectories = directoryPaths.filter((path) => {
120142
const directory = model.getItem(path);
121143
return directory !== null && "isExpanded" in directory && !directory.isExpanded();
122144
});
123-
model.resetPaths(paths);
145+
model.resetPaths(modelPaths);
124146
for (const path of collapsedDirectories) {
125147
const directory = model.getItem(path);
126148
if (directory !== null && "collapse" in directory) directory.collapse();
127149
}
128150
}
129151
model.setGitStatus(gitStatus);
130-
}, [directoryPaths, gitStatus, model, ordering, paths, positions]);
152+
}, [directoryPaths, gitStatus, model, modelPaths, ordering, positions]);
131153

132154
useEffect(() => {
133155
if (selectedPath === null) {
@@ -136,32 +158,39 @@ export function DiffFileTree({
136158
}
137159
// A path list that changes under an already-revealed file (a refresh, a later slice) must
138160
// not pull the tree back to it over whatever the reader has picked since.
139-
const item = model.getItem(selectedPath);
161+
const modelPath = presented.modelPath(selectedPath);
162+
const item = model.getItem(modelPath);
140163
if (item === null || item.isDirectory()) {
141164
// A file that left the diff has to be revealed again when it comes back.
142165
handledRevealRef.current = null;
143166
return;
144167
}
145168
const handled = handledRevealRef.current;
146-
if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) return;
147-
handledRevealRef.current = { path: selectedPath, revealRequestId };
169+
if (
170+
handled?.path === selectedPath &&
171+
handled.revealRequestId === revealRequestId &&
172+
handled.modelPath === modelPath
173+
) {
174+
return;
175+
}
176+
handledRevealRef.current = { path: selectedPath, revealRequestId, modelPath };
148177
syncingSelectionRef.current = true;
149178
for (const path of model.getSelectedPaths()) {
150-
if (path !== selectedPath) model.getItem(path)?.deselect();
179+
if (path !== modelPath) model.getItem(path)?.deselect();
151180
}
152181
let ancestor = "";
153-
for (const segment of selectedPath.split("/").slice(0, -1)) {
182+
for (const segment of modelPath.split("/").slice(0, -1)) {
154183
ancestor += `${segment}/`;
155184
const directory = model.getItem(ancestor);
156185
if (directory !== null && "expand" in directory) directory.expand();
157186
}
158187
item.select();
159-
model.scrollToPath(selectedPath, { offset: "nearest" });
188+
model.scrollToPath(modelPath, { offset: "nearest" });
160189
queueMicrotask(() => {
161190
syncingSelectionRef.current = false;
162191
});
163-
// `paths` is a dependency so a file that arrives after it was asked for is still revealed.
164-
}, [model, paths, revealRequestId, selectedPath]);
192+
// `presented` is a dependency so a file that arrives after it was asked for is still revealed.
193+
}, [model, presented, revealRequestId, selectedPath]);
165194

166195
return (
167196
<div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>
@@ -218,14 +247,16 @@ export function DiffFileTree({
218247
// Pierre does not emit a selection change for its sole selected row.
219248
// Read selection before the row handles the click so new selections reveal only once.
220249
const selected = model.getSelectedPaths();
221-
const path = selected.length === 1 ? selected[0] : undefined;
222-
if (!path || !filePathsRef.current.has(path)) return;
250+
const raw = selected.length === 1 ? selected[0] : undefined;
251+
if (!raw) return;
252+
const path = filePathsRef.current.has(raw) ? raw : raw.replace(/\/$/, "");
253+
if (!filePathsRef.current.has(path)) return;
223254
const clickedSelectedRow = event.nativeEvent
224255
.composedPath()
225256
.some(
226257
(node) => node instanceof HTMLElement && node.getAttribute("data-item-path") === path,
227258
);
228-
if (clickedSelectedRow) onSelectFileRef.current(path);
259+
if (clickedSelectedRow) onSelectFileRef.current(toSelectionPathRef.current(path));
229260
}}
230261
className="min-h-0 flex-1 overflow-hidden"
231262
style={pierreTreeStyle(resolvedTheme)}

0 commit comments

Comments
 (0)