Skip to content

Commit f10a502

Browse files
fix(web): Files tree keeps expanded folders across remounts (pingdotgg#35067)
1 parent dd9c2f8 commit f10a502

3 files changed

Lines changed: 111 additions & 5 deletions

File tree

‎apps/web/src/components/files/FileBrowserPanel.browser.test.tsx‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,30 @@ describe("FileBrowserPanel", () => {
144144
dispatchPreviewAction("find");
145145
await expect.element(search).toHaveFocus();
146146
});
147+
148+
it("keeps expanded folders when the panel remounts", async () => {
149+
const panel = () => (
150+
<FileBrowserPanel
151+
environmentId={EnvironmentId.make("env-files")}
152+
cwd="/repo"
153+
projectName="repo"
154+
selectedPath={null}
155+
selectedPathRevealId={0}
156+
onOpenFile={() => {}}
157+
workspaceMutationId={null}
158+
/>
159+
);
160+
{
161+
await using _first = await render(panel());
162+
await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
163+
findTreeRow("src/")!.click();
164+
await vi.waitFor(() =>
165+
expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"),
166+
);
167+
}
168+
169+
await using _second = await render(panel());
170+
await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
171+
await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
172+
});
147173
});

‎apps/web/src/components/files/FileBrowserPanel.tsx‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,13 @@ import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";
2828

2929
import { joinHostPath } from "./filePath";
3030
import { createFileTreeDragMentionController } from "./fileTreeDragMention";
31-
import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "./fileTreeExpansion";
31+
import {
32+
areAllDirectoriesExpanded,
33+
coalesceReentrantCalls,
34+
readExpandedDirectories,
35+
setAllDirectoriesExpanded,
36+
writeExpandedDirectories,
37+
} from "./fileTreeExpansion";
3238
import { buildFileTreePathUpdates } from "./fileTreePathReconciliation";
3339
import { loadFileAncestors } from "./loadFileAncestors";
3440
import { useDirectoryEntries } from "./useDirectoryEntries";
@@ -344,30 +350,45 @@ export default function FileBrowserPanel({
344350
return subscribePreviewAction(onPanelAction);
345351
}, [answersPanelFind]);
346352
const expandedPathsRef = useRef(new Set<string>());
353+
const expansionRoot = `${environmentId}:${cwd}`;
354+
// Folders expanded when the panel last unmounted; each reopens once lazy loading lists it.
355+
const [pendingExpandedPaths] = useState(() => new Set(readExpandedDirectories(expansionRoot)));
347356
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the Pierre tree model to load directories as they are expanded
348357
useEffect(() => {
349358
const currentPaths = new Set(directoryPaths);
350359
for (const path of expandedPathsRef.current) {
351360
if (!currentPaths.has(path)) expandedPathsRef.current.delete(path);
352361
}
353-
const loadExpanded = () => {
362+
// Restoring calls item.expand(), which notifies subscribers synchronously.
363+
const loadExpanded = coalesceReentrantCalls(() => {
354364
if (model.isSearchOpen()) return;
365+
let changed = false;
355366
for (const path of directoryPaths) {
356367
const item = model.getItem(path);
368+
if (item?.isDirectory() && pendingExpandedPaths.delete(path) && "expand" in item) {
369+
item.expand();
370+
}
357371
if (item?.isDirectory() && "isExpanded" in item && item.isExpanded()) {
358372
if (!expandedPathsRef.current.has(path)) {
359373
expandedPathsRef.current.add(path);
374+
changed = true;
360375
void load(path.replace(/\/$/, ""));
361376
}
362377
} else {
363378
if (item?.isDirectory() && expandedPathsRef.current.has(path)) setExpandAll(false);
364-
expandedPathsRef.current.delete(path);
379+
if (expandedPathsRef.current.delete(path)) changed = true;
365380
}
366381
}
367-
};
382+
if (changed) {
383+
writeExpandedDirectories(expansionRoot, [
384+
...expandedPathsRef.current,
385+
...pendingExpandedPaths,
386+
]);
387+
}
388+
});
368389
loadExpanded();
369390
return model.subscribe(loadExpanded);
370-
}, [directoryPaths, load, model]);
391+
}, [directoryPaths, expansionRoot, load, model, pendingExpandedPaths]);
371392
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes ignored-file status into the imperative Pierre tree model
372393
useEffect(() => {
373394
model.setGitStatus(

‎apps/web/src/components/files/fileTreeExpansion.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import * as Schema from "effect/Schema";
2+
3+
import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
4+
15
export interface FileTreeExpansionModel {
26
getItem(path: string): unknown;
37
}
@@ -53,3 +57,58 @@ export function setAllDirectoriesExpanded(
5357
else item.collapse();
5458
}
5559
}
60+
61+
/** Calls made while `run` is running rerun it once it returns, instead of nesting. */
62+
export function coalesceReentrantCalls(run: () => void): () => void {
63+
let running = false;
64+
let calledAgain = false;
65+
return () => {
66+
if (running) {
67+
calledAgain = true;
68+
return;
69+
}
70+
running = true;
71+
try {
72+
do {
73+
calledAgain = false;
74+
run();
75+
} while (calledAgain);
76+
} finally {
77+
running = false;
78+
}
79+
};
80+
}
81+
82+
const EXPANDED_DIRECTORIES_STORAGE_KEY = "t3code.fileTreeExpandedDirectories";
83+
// Roots are kept most recent first and capped so worktrees that come and go do not grow storage.
84+
const MAX_STORED_ROOTS = 20;
85+
const StoredExpandedDirectories = Schema.Array(
86+
Schema.Struct({ root: Schema.String, paths: Schema.Array(Schema.String) }),
87+
);
88+
89+
function readStoredExpandedDirectories() {
90+
try {
91+
return getLocalStorageItem(EXPANDED_DIRECTORIES_STORAGE_KEY, StoredExpandedDirectories) ?? [];
92+
} catch (error) {
93+
console.error(error);
94+
return [];
95+
}
96+
}
97+
98+
export function readExpandedDirectories(root: string): readonly string[] {
99+
return readStoredExpandedDirectories().find((entry) => entry.root === root)?.paths ?? [];
100+
}
101+
102+
export function writeExpandedDirectories(root: string, paths: readonly string[]): void {
103+
const others = readStoredExpandedDirectories().filter((entry) => entry.root !== root);
104+
const next = paths.length > 0 ? [{ root, paths }, ...others] : others;
105+
try {
106+
setLocalStorageItem(
107+
EXPANDED_DIRECTORIES_STORAGE_KEY,
108+
next.slice(0, MAX_STORED_ROOTS),
109+
StoredExpandedDirectories,
110+
);
111+
} catch (error) {
112+
console.error(error);
113+
}
114+
}

0 commit comments

Comments
 (0)