Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,63 @@ describe("FileBrowserPanel", () => {
await userEvent.click(page.getByRole("button", { name: "Refresh workspace files" }));
expect(new Set(revalidate.mock.calls.flat())).toEqual(new Set(["src", ""]));
});

it("opens a chain of single folders from one click and keeps it closed once closed", async () => {
const chain: readonly ProjectEntry[] = [
{ path: "tests", kind: "directory" },
{ path: "tests/edit", kind: "directory" },
{ path: "tests/edit/unit", kind: "directory" },
{ path: "tests/edit/unit/a.ts", kind: "file" },
];
const panel = () => (
<FileBrowserPanel
environmentId={EnvironmentId.make("env-files")}
cwd="/repo-single-folder-chain"
projectName="repo"
selectedPath={null}
selectedPathRevealId={0}
onOpenFile={() => {}}
workspaceMutationId={null}
/>
);
using _listing = withDirectoryListing(chain.slice(0, 1));
{
await using screen = await render(panel());
await vi.waitFor(() => expect(findTreeRow("tests/")).not.toBeNull());
findTreeRow("tests/")!.click();
await vi.waitFor(() =>
expect(findTreeRow("tests/")!.getAttribute("aria-expanded")).toBe("true"),
);
for (const listed of [2, 3, 4]) {
directory.entries = chain.slice(0, listed);
await screen.rerender(panel());
}
await vi.waitFor(() => expect(findTreeRow("tests/edit/unit/a.ts")).not.toBeNull());

findTreeRow("tests/edit/unit/")!.click();
await vi.waitFor(() => expect(findTreeRow("tests/edit/unit/a.ts")).toBeNull());
directory.entries = [...chain, { path: "tests/edit/unit/b.ts", kind: "file" }];
await screen.rerender(panel());
expect(findTreeRow("tests/edit/unit/")!.getAttribute("aria-expanded")).toBe("false");
}

directory.entries = [...chain, { path: "pkg", kind: "directory" }];
await using remounted = await render(panel());
await vi.waitFor(() => expect(findTreeRow("tests/edit/unit/")).not.toBeNull());
expect(findTreeRow("tests/edit/unit/")!.getAttribute("aria-expanded")).toBe("false");

// An ignored folder can hold tens of thousands of entries, so it still opens by hand.
findTreeRow("pkg/")!.click();
await vi.waitFor(() => expect(findTreeRow("pkg/")!.getAttribute("aria-expanded")).toBe("true"));
directory.entries = [
...directory.entries,
{ path: "pkg/node_modules", kind: "directory", ignored: true },
];
await remounted.rerender(panel());
await vi.waitFor(() => expect(findTreeRow("pkg/node_modules/")).not.toBeNull());
expect(findTreeRow("pkg/node_modules/")!.getAttribute("aria-expanded")).toBe("false");
});

describe("revealing a folder while folders above it are still loading", () => {
const roots = Array.from({ length: 12 }, (_, index): ProjectEntry => {
return { path: `d${String(index).padStart(2, "0")}`, kind: "directory" };
Expand Down
46 changes: 42 additions & 4 deletions apps/web/src/components/files/FileBrowserPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { createFileTreeDragMentionController } from "./fileTreeDragMention";
import {
areAllDirectoriesExpanded,
coalesceReentrantCalls,
onlyChildren,
readExpandedDirectories,
setAllDirectoriesExpanded,
writeExpandedDirectories,
Expand Down Expand Up @@ -165,6 +166,9 @@ function buildTreeEntries(
return { entries, entryKinds, treePaths, directoryPaths, expandableDirectoryPaths };
}

// A symlink to its own parent lists itself as an only child without end.
const MAX_FOLDERS_OPENED_WITH_PARENT = 16;

export default function FileBrowserPanel({
environmentId,
cwd,
Expand Down Expand Up @@ -390,29 +394,63 @@ export default function FileBrowserPanel({
const expansionRoot = `${environmentId}:${cwd}`;
// Folders expanded when the panel last unmounted; each reopens once lazy loading lists it.
const [pendingExpandedPaths] = useState(() => new Set(readExpandedDirectories(expansionRoot)));
// Folders just opened and not listed yet, with how many only-child folders may open below each.
// Pierre merges such a chain into one row that takes its open state from the last folder.
const openingPathsRef = useRef(new Map<string, number>());
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the Pierre tree model to load directories as they are expanded
useEffect(() => {
const currentPaths = new Set(directoryPaths);
for (const path of expandedPathsRef.current) {
if (!currentPaths.has(path)) expandedPathsRef.current.delete(path);
}
for (const path of openingPathsRef.current.keys()) {
if (!currentPaths.has(path)) openingPathsRef.current.delete(path);
}
let childrenByParent: ReadonlyMap<string, ProjectEntry | null> | null = null;
const openOnlyChild = (path: string) => {
const remaining = openingPathsRef.current.get(path);
if (remaining === undefined) return;
if (childrenByParent === null) childrenByParent = onlyChildren(directoryEntries);
const child = childrenByParent.get(path.replace(/\/$/, ""));
if (child === undefined) return;
// Like expand all, leave an ignored folder such as `node_modules` to open by hand.
const opensChild =
child?.kind === "directory" &&
(!child.ignored ||
directoryEntries.some((entry) => entry.ignored && treePath(entry) === path));
if (!opensChild || remaining === 0) {
openingPathsRef.current.delete(path);
return;
}
const childItem = model.getItem(treePath(child));
// The listing reaches the tree after this effect, which notifies again.
if (!childItem || !("expand" in childItem)) return;
openingPathsRef.current.delete(path);
if (childItem.isExpanded()) return;
openingPathsRef.current.set(treePath(child), remaining - 1);
childItem.expand();
};
// Restoring calls item.expand(), which notifies subscribers synchronously.
const loadExpanded = coalesceReentrantCalls(() => {
if (model.isSearchOpen()) return;
let changed = false;
for (const path of directoryPaths) {
const item = model.getItem(path);
if (item?.isDirectory() && pendingExpandedPaths.delete(path) && "expand" in item) {
item.expand();
}
const restored = item?.isDirectory() && pendingExpandedPaths.delete(path);
if (restored && item && "expand" in item) item.expand();
if (item?.isDirectory() && "isExpanded" in item && item.isExpanded()) {
if (!expandedPathsRef.current.has(path)) {
expandedPathsRef.current.add(path);
changed = true;
if (!restored && !openingPathsRef.current.has(path)) {
openingPathsRef.current.set(path, MAX_FOLDERS_OPENED_WITH_PARENT);
}
void load(path.replace(/\/$/, ""));
}
openOnlyChild(path);
} else {
if (item?.isDirectory() && expandedPathsRef.current.has(path)) setExpandAll(false);
openingPathsRef.current.delete(path);
if (expandedPathsRef.current.delete(path)) changed = true;
}
}
Expand All @@ -425,7 +463,7 @@ export default function FileBrowserPanel({
});
loadExpanded();
return model.subscribe(loadExpanded);
}, [directoryPaths, expansionRoot, load, model, pendingExpandedPaths]);
}, [directoryEntries, directoryPaths, expansionRoot, load, model, pendingExpandedPaths]);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes ignored-file status into the imperative Pierre tree model
useEffect(() => {
model.setGitStatus(
Expand Down
13 changes: 13 additions & 0 deletions apps/web/src/components/files/fileTreeExpansion.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ProjectEntry } from "@t3tools/contracts";
import * as Schema from "effect/Schema";

import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
Expand Down Expand Up @@ -82,6 +83,18 @@ export function setAllDirectoriesExpanded(
}
}

/** Maps each listed parent path to its only child, or to null when it holds several entries. */
export function onlyChildren(
entries: readonly ProjectEntry[],
): ReadonlyMap<string, ProjectEntry | null> {
const result = new Map<string, ProjectEntry | null>();
for (const entry of entries) {
const parent = entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/")));
result.set(parent, result.has(parent) ? null : entry);
}
return result;
}

/** Calls made while `run` is running rerun it once it returns, instead of nesting. */
export function coalesceReentrantCalls(run: () => void): () => void {
let running = false;
Expand Down
Loading