Skip to content

Commit 6a62044

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 f845895 commit 6a62044

4 files changed

Lines changed: 346 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
@@ -16,6 +16,7 @@ import {
1616
buildDiffFileTreeUpdates,
1717
compareDiffFileTreeEntries,
1818
collectDirectoryPaths,
19+
diffFileTreeModel,
1920
diffFileTreePositions,
2021
type DiffFileTreeEntry,
2122
} from "./diffFileTree.logic";
@@ -43,6 +44,9 @@ interface DiffFileTreeProps {
4344
/**
4445
* A directory tree of the files in a diff. Every directory starts open: a diff is a short list
4546
* compared to a workspace, and the reader came for the files, not the folders.
47+
*
48+
* A file replaced by a directory of the same name (or the reverse) is still one tree. Those
49+
* paths are rewritten before they reach Pierre, and selection is translated back.
4650
*/
4751
export function DiffFileTree({
4852
entries,
@@ -56,8 +60,10 @@ export function DiffFileTree({
5660
}: DiffFileTreeProps) {
5761
const { resolvedTheme } = useTheme();
5862
const paths = useMemo(() => entries.map((entry) => entry.path), [entries]);
59-
const directoryPaths = useMemo(() => collectDirectoryPaths(paths), [paths]);
60-
const positions = useMemo(() => diffFileTreePositions(paths), [paths]);
63+
const presented = useMemo(() => diffFileTreeModel(paths), [paths]);
64+
const modelPaths = presented.paths;
65+
const directoryPaths = useMemo(() => collectDirectoryPaths(modelPaths), [modelPaths]);
66+
const positions = useMemo(() => diffFileTreePositions(modelPaths), [modelPaths]);
6167
const [ordering] = useState(() => {
6268
let currentPositions: ReadonlyMap<string, number> = new Map();
6369
return {
@@ -68,21 +74,31 @@ export function DiffFileTree({
6874
};
6975
});
7076
const gitStatus = useMemo<ReadonlyArray<GitStatusEntry>>(
71-
() => entries.map((entry) => ({ path: entry.path, status: entry.status })),
72-
[entries],
77+
() =>
78+
entries.map((entry, index) => ({
79+
path: modelPaths[index] ?? entry.path,
80+
status: entry.status,
81+
})),
82+
[entries, modelPaths],
7383
);
74-
const filePathsRef = useRef<ReadonlySet<string>>(new Set(paths));
84+
const filePathsRef = useRef<ReadonlySet<string>>(new Set(modelPaths));
7585
const onSelectFileRef = useRef(onSelectFile);
86+
const toSelectionPathRef = useRef(presented.selectionPath);
7687
// Selection driven by `selectedPath` below is an echo of a file already on screen, not a
7788
// request to scroll to it again.
7889
const syncingSelectionRef = useRef(false);
79-
const handledRevealRef = useRef<{ path: string; revealRequestId: number } | null>(null);
90+
const handledRevealRef = useRef<{
91+
path: string;
92+
revealRequestId: number;
93+
modelPath: string;
94+
} | null>(null);
8095
const mountedPathsRef = useRef<ReadonlyArray<string> | null>(null);
8196

8297
useEffect(() => {
83-
filePathsRef.current = new Set(paths);
98+
filePathsRef.current = new Set(modelPaths);
8499
onSelectFileRef.current = onSelectFile;
85-
}, [onSelectFile, paths]);
100+
toSelectionPathRef.current = presented.selectionPath;
101+
}, [modelPaths, onSelectFile, presented.selectionPath]);
86102

87103
const { model } = useFileTree({
88104
density: "compact",
@@ -91,8 +107,13 @@ export function DiffFileTree({
91107
icons: T3_PIERRE_ICONS,
92108
onSelectionChange: (selectedPaths) => {
93109
if (syncingSelectionRef.current) return;
94-
const path = selectedPaths.at(-1)?.replace(/\/$/, "");
95-
if (path && filePathsRef.current.has(path)) onSelectFileRef.current(path);
110+
const raw = selectedPaths.at(-1);
111+
if (!raw) return;
112+
// Directory ids end in `/`. A file that shares that directory's name is stored under a
113+
// different model path, so stripping the slash must not select it.
114+
const modelPath = filePathsRef.current.has(raw) ? raw : raw.replace(/\/$/, "");
115+
if (!filePathsRef.current.has(modelPath)) return;
116+
onSelectFileRef.current(toSelectionPathRef.current(modelPath));
96117
},
97118
paths: [],
98119
search: false,
@@ -106,29 +127,30 @@ export function DiffFileTree({
106127
useEffect(() => {
107128
ordering.update(positions);
108129
const mountedPaths = mountedPathsRef.current;
109-
if (mountedPaths === paths) return;
110-
mountedPathsRef.current = paths;
130+
if (mountedPaths === modelPaths) return;
131+
mountedPathsRef.current = modelPaths;
111132
if (mountedPaths === null) {
112-
model.resetPaths(paths);
113-
} else if (mountedPaths.every((path, index) => paths[index] === path)) {
133+
model.resetPaths(modelPaths);
134+
} else if (mountedPaths.every((path, index) => modelPaths[index] === path)) {
114135
// PR slices only append files, so keep the existing tree and its open folders.
115-
const updates = buildDiffFileTreeUpdates(mountedPaths, paths);
136+
const updates = buildDiffFileTreeUpdates(mountedPaths, modelPaths);
116137
if (updates.length > 0) model.batch(updates);
117138
} else {
118-
// A refreshed diff can change the rank of existing siblings. Mutations do not reorder
119-
// those rows, so rebuild while carrying the reader's folder expansion forward.
139+
// A refreshed diff can change the rank of existing siblings. A file that becomes a
140+
// directory prefix also changes its model path, which Pierre cannot rename in place.
141+
// Rebuild while carrying the reader's folder expansion forward.
120142
const collapsedDirectories = directoryPaths.filter((path) => {
121143
const directory = model.getItem(path);
122144
return directory !== null && "isExpanded" in directory && !directory.isExpanded();
123145
});
124-
model.resetPaths(paths);
146+
model.resetPaths(modelPaths);
125147
for (const path of collapsedDirectories) {
126148
const directory = model.getItem(path);
127149
if (directory !== null && "collapse" in directory) directory.collapse();
128150
}
129151
}
130152
model.setGitStatus(gitStatus);
131-
}, [directoryPaths, gitStatus, model, ordering, paths, positions]);
153+
}, [directoryPaths, gitStatus, model, modelPaths, ordering, positions]);
132154

133155
useEffect(() => {
134156
if (selectedPath === null) {
@@ -137,32 +159,39 @@ export function DiffFileTree({
137159
}
138160
// A path list that changes under an already-revealed file (a refresh, a later slice) must
139161
// not pull the tree back to it over whatever the reader has picked since.
140-
const item = model.getItem(selectedPath);
162+
const modelPath = presented.modelPath(selectedPath);
163+
const item = model.getItem(modelPath);
141164
if (item === null || item.isDirectory()) {
142165
// A file that left the diff has to be revealed again when it comes back.
143166
handledRevealRef.current = null;
144167
return;
145168
}
146169
const handled = handledRevealRef.current;
147-
if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) return;
148-
handledRevealRef.current = { path: selectedPath, revealRequestId };
170+
if (
171+
handled?.path === selectedPath &&
172+
handled.revealRequestId === revealRequestId &&
173+
handled.modelPath === modelPath
174+
) {
175+
return;
176+
}
177+
handledRevealRef.current = { path: selectedPath, revealRequestId, modelPath };
149178
syncingSelectionRef.current = true;
150179
for (const path of model.getSelectedPaths()) {
151-
if (path !== selectedPath) model.getItem(path)?.deselect();
180+
if (path !== modelPath) model.getItem(path)?.deselect();
152181
}
153182
let ancestor = "";
154-
for (const segment of selectedPath.split("/").slice(0, -1)) {
183+
for (const segment of modelPath.split("/").slice(0, -1)) {
155184
ancestor += `${segment}/`;
156185
const directory = model.getItem(ancestor);
157186
if (directory !== null && "expand" in directory) directory.expand();
158187
}
159188
item.select();
160-
model.scrollToPath(selectedPath, { offset: "nearest" });
189+
model.scrollToPath(modelPath, { offset: "nearest" });
161190
queueMicrotask(() => {
162191
syncingSelectionRef.current = false;
163192
});
164-
// `paths` is a dependency so a file that arrives after it was asked for is still revealed.
165-
}, [model, paths, revealRequestId, selectedPath]);
193+
// `presented` is a dependency so a file that arrives after it was asked for is still revealed.
194+
}, [model, presented, revealRequestId, selectedPath]);
166195

167196
return (
168197
<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)