Preserve diff tree order and collapsed folders (#11931)
This commit is contained in:
1 parent
7235701de0
commit
3efdcc5296
4 files changed
+107
-4
No files matched your search
@@ -178,6 +178,23 @@ describe("diff tree file activation", () => {
|
||||
expect(targets).toEqual([]);
|
||||
});
|
||||
|
||||
it("reorders refreshed files without reopening a collapsed folder", async () => {
|
||||
const files: DiffFileTreeEntry[] = [
|
||||
{ path: "src/state/shell.ts", status: "modified" },
|
||||
{ path: "src/features/route.ts", status: "added" },
|
||||
];
|
||||
await mount({ files });
|
||||
const initialFolder = model().getItem("src/features/")!;
|
||||
if (!("collapse" in initialFolder)) throw new Error("Expected the directory handle");
|
||||
await act(async () => initialFolder.collapse());
|
||||
await act(async () => {
|
||||
renderer!.update(<Panel files={[files[1]!, files[0]!]} />);
|
||||
});
|
||||
const folder = model().getItem("src/features/")!;
|
||||
if (!("isExpanded" in folder)) throw new Error("Expected the directory handle");
|
||||
expect(folder.isExpanded()).toBe(false);
|
||||
});
|
||||
|
||||
it("does not echo controlled selection, but lets the reader activate it", async () => {
|
||||
await mount({ selectedPath: "02-short.ts" });
|
||||
expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { GitStatusEntry } from "@pierre/trees";
|
||||
import { FileTree, useFileTree, useFileTreeSelector } from "@pierre/trees/react";
|
||||
import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, type ReactNode } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
|
||||
import { useTheme } from "~/hooks/useTheme";
|
||||
import { cn } from "~/lib/utils";
|
||||
@@ -13,7 +13,9 @@ import { Button } from "../ui/button";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import {
|
||||
buildDiffFileTreeUpdates,
|
||||
compareDiffFileTreeEntries,
|
||||
collectDirectoryPaths,
|
||||
diffFileTreePositions,
|
||||
type DiffFileTreeEntry,
|
||||
} from "./diffFileTree.logic";
|
||||
|
||||
@@ -54,6 +56,16 @@ export function DiffFileTree({
|
||||
const { resolvedTheme } = useTheme();
|
||||
const paths = useMemo(() => entries.map((entry) => entry.path), [entries]);
|
||||
const directoryPaths = useMemo(() => collectDirectoryPaths(paths), [paths]);
|
||||
const positions = useMemo(() => diffFileTreePositions(paths), [paths]);
|
||||
const [ordering] = useState(() => {
|
||||
let currentPositions: ReadonlyMap<string, number> = new Map();
|
||||
return {
|
||||
sort: compareDiffFileTreeEntries(() => currentPositions),
|
||||
update: (nextPositions: ReadonlyMap<string, number>) => {
|
||||
currentPositions = nextPositions;
|
||||
},
|
||||
};
|
||||
});
|
||||
const gitStatus = useMemo<ReadonlyArray<GitStatusEntry>>(
|
||||
() => entries.map((entry) => ({ path: entry.path, status: entry.status })),
|
||||
[entries],
|
||||
@@ -83,6 +95,7 @@ export function DiffFileTree({
|
||||
},
|
||||
paths: [],
|
||||
search: false,
|
||||
sort: ordering.sort,
|
||||
unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
|
||||
});
|
||||
const allDirectoriesExpanded = useFileTreeSelector(model, (currentModel) =>
|
||||
@@ -90,17 +103,31 @@ export function DiffFileTree({
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
ordering.update(positions);
|
||||
const mountedPaths = mountedPathsRef.current;
|
||||
if (mountedPaths === paths) return;
|
||||
mountedPathsRef.current = paths;
|
||||
if (mountedPaths === null) {
|
||||
model.resetPaths(paths);
|
||||
} else {
|
||||
} else if (mountedPaths.every((path, index) => paths[index] === path)) {
|
||||
// PR slices only append files, so keep the existing tree and its open folders.
|
||||
const updates = buildDiffFileTreeUpdates(mountedPaths, paths);
|
||||
if (updates.length > 0) model.batch(updates);
|
||||
} else {
|
||||
// A refreshed diff can change the rank of existing siblings. Mutations do not reorder
|
||||
// those rows, so rebuild while carrying the reader's folder expansion forward.
|
||||
const collapsedDirectories = directoryPaths.filter((path) => {
|
||||
const directory = model.getItem(path);
|
||||
return directory !== null && "isExpanded" in directory && !directory.isExpanded();
|
||||
});
|
||||
model.resetPaths(paths);
|
||||
for (const path of collapsedDirectories) {
|
||||
const directory = model.getItem(path);
|
||||
if (directory !== null && "collapse" in directory) directory.collapse();
|
||||
}
|
||||
}
|
||||
model.setGitStatus(gitStatus);
|
||||
}, [gitStatus, model, paths]);
|
||||
}, [directoryPaths, gitStatus, model, ordering, paths, positions]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedPath === null) {
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import type { FileDiffMetadata } from "@pierre/diffs";
|
||||
import { preloadFileTree } from "@pierre/trees";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildDiffFileTreeUpdates,
|
||||
compareDiffFileTreeEntries,
|
||||
collectDirectoryPaths,
|
||||
diffFileTreePositions,
|
||||
diffFileTreeEntries,
|
||||
} from "./diffFileTree.logic";
|
||||
|
||||
@@ -41,6 +44,34 @@ describe("collectDirectoryPaths", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("diff tree reading order", () => {
|
||||
it("places folders and files where their first diff appears", () => {
|
||||
const paths = [
|
||||
"apps/mobile/src/state/shell.ts",
|
||||
"apps/mobile/src/features/threads/route.ts",
|
||||
"apps/mobile/src/features/threads/screen.tsx",
|
||||
];
|
||||
const positions = diffFileTreePositions(paths);
|
||||
const tree = preloadFileTree({
|
||||
paths,
|
||||
initialExpansion: "open",
|
||||
flattenEmptyDirectories: true,
|
||||
sort: compareDiffFileTreeEntries(() => positions),
|
||||
});
|
||||
const rows = [...tree.shadowHtml.matchAll(/data-item-path="([^"]+)"/g)].map(
|
||||
(match) => match[1],
|
||||
);
|
||||
expect(rows).toEqual([
|
||||
"apps/mobile/src/",
|
||||
"apps/mobile/src/state/",
|
||||
"apps/mobile/src/state/shell.ts",
|
||||
"apps/mobile/src/features/threads/",
|
||||
"apps/mobile/src/features/threads/route.ts",
|
||||
"apps/mobile/src/features/threads/screen.tsx",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildDiffFileTreeUpdates", () => {
|
||||
it("adds a new file's directories before the file", () => {
|
||||
expect(buildDiffFileTreeUpdates(["README.md"], ["README.md", "src/lib/a.ts"])).toEqual([
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { FileDiffMetadata } from "@pierre/diffs";
|
||||
import type { FileTreeBatchOperation, GitStatus } from "@pierre/trees";
|
||||
import type { FileTreeBatchOperation, FileTreeSortComparator, GitStatus } from "@pierre/trees";
|
||||
|
||||
import { resolveFileDiffPath } from "~/lib/diffRendering";
|
||||
|
||||
@@ -47,6 +47,34 @@ export function collectDirectoryPaths(paths: ReadonlyArray<string>): ReadonlyArr
|
||||
return [...directories];
|
||||
}
|
||||
|
||||
/** A folder takes the position of its first file in the diff. */
|
||||
export function diffFileTreePositions(paths: ReadonlyArray<string>): ReadonlyMap<string, number> {
|
||||
const positions = new Map<string, number>();
|
||||
paths.forEach((path, index) => {
|
||||
positions.set(path, index);
|
||||
let directory = "";
|
||||
for (const segment of path.split("/").slice(0, -1)) {
|
||||
directory += `${segment}/`;
|
||||
if (!positions.has(directory)) positions.set(directory, index);
|
||||
}
|
||||
});
|
||||
return positions;
|
||||
}
|
||||
|
||||
export function compareDiffFileTreeEntries(
|
||||
getPositions: () => ReadonlyMap<string, number>,
|
||||
): FileTreeSortComparator {
|
||||
return (left, right) => {
|
||||
const positions = getPositions();
|
||||
return (
|
||||
(positions.get(left.path) ?? Number.MAX_SAFE_INTEGER) -
|
||||
(positions.get(right.path) ?? Number.MAX_SAFE_INTEGER) ||
|
||||
left.depth - right.depth ||
|
||||
left.path.localeCompare(right.path)
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
function pathDepth(path: string): number {
|
||||
return path.split("/").filter(Boolean).length;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user