Skip to content

Commit d551642

Browse files
fix(web): preserve diff tree order and collapsed folders
- Sort folders by first diff appearance - Preserve collapsed state when refreshed files reorder
1 parent d1790aa commit d551642

4 files changed

Lines changed: 107 additions & 4 deletions

File tree

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,23 @@ describe("diff tree file activation", () => {
178178
expect(targets).toEqual([]);
179179
});
180180

181+
it("reorders refreshed files without reopening a collapsed folder", async () => {
182+
const files: DiffFileTreeEntry[] = [
183+
{ path: "src/state/shell.ts", status: "modified" },
184+
{ path: "src/features/route.ts", status: "added" },
185+
];
186+
await mount({ files });
187+
const initialFolder = model().getItem("src/features/")!;
188+
if (!("collapse" in initialFolder)) throw new Error("Expected the directory handle");
189+
await act(async () => initialFolder.collapse());
190+
await act(async () => {
191+
renderer!.update(<Panel files={[files[1]!, files[0]!]} />);
192+
});
193+
const folder = model().getItem("src/features/")!;
194+
if (!("isExpanded" in folder)) throw new Error("Expected the directory handle");
195+
expect(folder.isExpanded()).toBe(false);
196+
});
197+
181198
it("does not echo controlled selection, but lets the reader activate it", async () => {
182199
await mount({ selectedPath: "02-short.ts" });
183200
expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);

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

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { GitStatusEntry } from "@pierre/trees";
22
import { FileTree, useFileTree, useFileTreeSelector } from "@pierre/trees/react";
33
import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";
4-
import { useEffect, useMemo, useRef, type ReactNode } from "react";
4+
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
55

66
import { useTheme } from "~/hooks/useTheme";
77
import { cn } from "~/lib/utils";
@@ -13,7 +13,9 @@ import { Button } from "../ui/button";
1313
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
1414
import {
1515
buildDiffFileTreeUpdates,
16+
compareDiffFileTreeEntries,
1617
collectDirectoryPaths,
18+
diffFileTreePositions,
1719
type DiffFileTreeEntry,
1820
} from "./diffFileTree.logic";
1921

@@ -54,6 +56,16 @@ export function DiffFileTree({
5456
const { resolvedTheme } = useTheme();
5557
const paths = useMemo(() => entries.map((entry) => entry.path), [entries]);
5658
const directoryPaths = useMemo(() => collectDirectoryPaths(paths), [paths]);
59+
const positions = useMemo(() => diffFileTreePositions(paths), [paths]);
60+
const [ordering] = useState(() => {
61+
let currentPositions: ReadonlyMap<string, number> = new Map();
62+
return {
63+
sort: compareDiffFileTreeEntries(() => currentPositions),
64+
update: (nextPositions: ReadonlyMap<string, number>) => {
65+
currentPositions = nextPositions;
66+
},
67+
};
68+
});
5769
const gitStatus = useMemo<ReadonlyArray<GitStatusEntry>>(
5870
() => entries.map((entry) => ({ path: entry.path, status: entry.status })),
5971
[entries],
@@ -83,24 +95,39 @@ export function DiffFileTree({
8395
},
8496
paths: [],
8597
search: false,
98+
sort: ordering.sort,
8699
unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
87100
});
88101
const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
89102
areAllDirectoriesExpanded(currentModel, directoryPaths),
90103
);
91104

92105
useEffect(() => {
106+
ordering.update(positions);
93107
const mountedPaths = mountedPathsRef.current;
94108
if (mountedPaths === paths) return;
95109
mountedPathsRef.current = paths;
96110
if (mountedPaths === null) {
97111
model.resetPaths(paths);
98-
} else {
112+
} else if (mountedPaths.every((path, index) => paths[index] === path)) {
113+
// PR slices only append files, so keep the existing tree and its open folders.
99114
const updates = buildDiffFileTreeUpdates(mountedPaths, paths);
100115
if (updates.length > 0) model.batch(updates);
116+
} 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.
119+
const collapsedDirectories = directoryPaths.filter((path) => {
120+
const directory = model.getItem(path);
121+
return directory !== null && "isExpanded" in directory && !directory.isExpanded();
122+
});
123+
model.resetPaths(paths);
124+
for (const path of collapsedDirectories) {
125+
const directory = model.getItem(path);
126+
if (directory !== null && "collapse" in directory) directory.collapse();
127+
}
101128
}
102129
model.setGitStatus(gitStatus);
103-
}, [gitStatus, model, paths]);
130+
}, [directoryPaths, gitStatus, model, ordering, paths, positions]);
104131

105132
useEffect(() => {
106133
if (selectedPath === null) {

‎apps/web/src/components/diffs/diffFileTree.logic.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import type { FileDiffMetadata } from "@pierre/diffs";
2+
import { preloadFileTree } from "@pierre/trees";
23
import { describe, expect, it } from "vite-plus/test";
34

45
import {
56
buildDiffFileTreeUpdates,
7+
compareDiffFileTreeEntries,
68
collectDirectoryPaths,
9+
diffFileTreePositions,
710
diffFileTreeEntries,
811
} from "./diffFileTree.logic";
912

@@ -41,6 +44,34 @@ describe("collectDirectoryPaths", () => {
4144
});
4245
});
4346

47+
describe("diff tree reading order", () => {
48+
it("places folders and files where their first diff appears", () => {
49+
const paths = [
50+
"apps/mobile/src/state/shell.ts",
51+
"apps/mobile/src/features/threads/route.ts",
52+
"apps/mobile/src/features/threads/screen.tsx",
53+
];
54+
const positions = diffFileTreePositions(paths);
55+
const tree = preloadFileTree({
56+
paths,
57+
initialExpansion: "open",
58+
flattenEmptyDirectories: true,
59+
sort: compareDiffFileTreeEntries(() => positions),
60+
});
61+
const rows = [...tree.shadowHtml.matchAll(/data-item-path="([^"]+)"/g)].map(
62+
(match) => match[1],
63+
);
64+
expect(rows).toEqual([
65+
"apps/mobile/src/",
66+
"apps/mobile/src/state/",
67+
"apps/mobile/src/state/shell.ts",
68+
"apps/mobile/src/features/threads/",
69+
"apps/mobile/src/features/threads/route.ts",
70+
"apps/mobile/src/features/threads/screen.tsx",
71+
]);
72+
});
73+
});
74+
4475
describe("buildDiffFileTreeUpdates", () => {
4576
it("adds a new file's directories before the file", () => {
4677
expect(buildDiffFileTreeUpdates(["README.md"], ["README.md", "src/lib/a.ts"])).toEqual([

‎apps/web/src/components/diffs/diffFileTree.logic.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { FileDiffMetadata } from "@pierre/diffs";
2-
import type { FileTreeBatchOperation, GitStatus } from "@pierre/trees";
2+
import type { FileTreeBatchOperation, FileTreeSortComparator, GitStatus } from "@pierre/trees";
33

44
import { resolveFileDiffPath } from "~/lib/diffRendering";
55

@@ -47,6 +47,34 @@ export function collectDirectoryPaths(paths: ReadonlyArray<string>): ReadonlyArr
4747
return [...directories];
4848
}
4949

50+
/** A folder takes the position of its first file in the diff. */
51+
export function diffFileTreePositions(paths: ReadonlyArray<string>): ReadonlyMap<string, number> {
52+
const positions = new Map<string, number>();
53+
paths.forEach((path, index) => {
54+
positions.set(path, index);
55+
let directory = "";
56+
for (const segment of path.split("/").slice(0, -1)) {
57+
directory += `${segment}/`;
58+
if (!positions.has(directory)) positions.set(directory, index);
59+
}
60+
});
61+
return positions;
62+
}
63+
64+
export function compareDiffFileTreeEntries(
65+
getPositions: () => ReadonlyMap<string, number>,
66+
): FileTreeSortComparator {
67+
return (left, right) => {
68+
const positions = getPositions();
69+
return (
70+
(positions.get(left.path) ?? Number.MAX_SAFE_INTEGER) -
71+
(positions.get(right.path) ?? Number.MAX_SAFE_INTEGER) ||
72+
left.depth - right.depth ||
73+
left.path.localeCompare(right.path)
74+
);
75+
};
76+
}
77+
5078
function pathDepth(path: string): number {
5179
return path.split("/").filter(Boolean).length;
5280
}

0 commit comments

Comments
 (0)