Open History to see the last commit
1import { EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
2import { describe, expect, it, vi } from "vite-plus/test";
3import { commands, page, userEvent } from "vite-plus/test/browser";
4
5import { COMPOSER_MENTION_DRAG_TYPE } from "~/components/chat/composerMentionDrag";
6import { RightPanelSheet } from "~/components/RightPanelSheet";
7import { dismissContextMenu } from "~/contextMenuFallback";
8import { isMacPlatform } from "~/lib/utils";
9import { act, render } from "../../../test/render";
10import FileBrowserPanel from "./FileBrowserPanel";
11import { dispatchPreviewAction } from "../preview/previewActionBus";
12import { writeExpandedDirectories } from "./fileTreeExpansion";
13
14const entries: readonly ProjectEntry[] = [
15 { path: "src", kind: "directory" },
16 { path: "README.md", kind: "file" },
17];
18const loadingDirectories: ReadonlySet<string> = new Set();
19const directory: {
20 entries: readonly ProjectEntry[];
21 load: () => Promise<void>;
22 refresh: () => void;
23 revalidate: (directoryPath: string) => void;
24 ready: boolean;
25 error: null;
26 isPending: boolean;
27 loadingDirectories: ReadonlySet<string>;
28} = {
29 entries,
30 load: () => Promise.resolve(),
31 refresh: () => {},
32 revalidate: () => {},
33 ready: true,
34 error: null,
35 isPending: false,
36 loadingDirectories,
37};
38const pathSearch = {
39 entries: [],
40 isPending: false,
41 error: null,
42 truncated: false,
43 refresh: () => {},
44};
45
46vi.mock("./useDirectoryEntries", () => ({ useDirectoryEntries: () => directory }));
47vi.mock("~/state/queries", () => ({ useProjectPathSearch: () => pathSearch }));
48vi.mock("~/fileContextMenu", () => ({
49 useFileContextMenu: () => ({ buildItems: () => [], activate: () => Promise.resolve() }),
50}));
51vi.mock("~/hooks/useWorkspaceMutationRefresh", () => ({ useWorkspaceMutationRefresh: () => {} }));
52
53function findTreeRow(path: string): HTMLElement | null {
54 for (const host of document.querySelectorAll("*")) {
55 const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${path}"]`);
56 if (row) return row;
57 }
58 return null;
59}
60
61function findTreeScroller(): HTMLElement | null {
62 for (const host of document.querySelectorAll("*")) {
63 const scroller = host.shadowRoot?.querySelector<HTMLElement>(
64 "[data-file-tree-virtualized-scroll]",
65 );
66 if (scroller) return scroller;
67 }
68 return null;
69}
70
71function isTreeRowInView(path: string): boolean {
72 const rowRect = findTreeRow(path)?.getBoundingClientRect();
73 const scrollerRect = findTreeScroller()?.getBoundingClientRect();
74 return (
75 rowRect !== undefined &&
76 scrollerRect !== undefined &&
77 rowRect.top >= scrollerRect.top &&
78 rowRect.bottom <= scrollerRect.bottom
79 );
80}
81
82function sizedContainer(): HTMLElement {
83 const container = document.createElement("div");
84 container.style.cssText = "display:flex;flex-direction:column;height:300px;width:300px";
85 return container;
86}
87
88function withDirectoryListing(listing: readonly ProjectEntry[]): Disposable {
89 directory.entries = listing;
90 return {
91 [Symbol.dispose]: () => {
92 directory.entries = entries;
93 directory.ready = true;
94 },
95 };
96}
97
98describe("FileBrowserPanel", () => {
99 it("copies with the pointer and returns to the row after keyboard dismissal", async () => {
100 await using _screen = await render(
101 <FileBrowserPanel
102 environmentId={EnvironmentId.make("env-files")}
103 cwd="/repo"
104 projectName="repo"
105 selectedPath={null}
106 selectedPathRevealId={0}
107 onOpenFile={() => {}}
108 workspaceMutationId={null}
109 />,
110 );
111 using _menu = { [Symbol.dispose]: () => dismissContextMenu() };
112 using clipboard = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined);
113
114 async function openRowMenu(path: string) {
115 await vi.waitFor(() => expect(findTreeRow(path)).not.toBeNull());
116 findTreeRow(path)!.dispatchEvent(
117 new MouseEvent("contextmenu", {
118 bubbles: true,
119 cancelable: true,
120 composed: true,
121 button: 2,
122 }),
123 );
124 }
125
126 await openRowMenu("src/");
127 const copyPath = page.getByRole("menuitem", { name: "Copy path", exact: true });
128 await userEvent.click(copyPath);
129 await vi.waitFor(() => expect(clipboard).toHaveBeenCalledWith("/repo/src"));
130
131 await openRowMenu("README.md");
132 const copyMention = page.getByRole("menuitem", { name: "Copy mention", exact: true });
133 await expect.element(copyMention).toBeVisible();
134 await userEvent.click(copyMention);
135 await vi.waitFor(() => expect(clipboard).toHaveBeenCalledWith("[README.md](README.md)"));
136
137 // Hover can take focus when the keyboard menu reopens under the pointer.
138 await commands.resetPointer();
139 const row = findTreeRow("README.md")!;
140 await userEvent.keyboard("{Tab}");
141 row.focus();
142 await userEvent.keyboard("{Shift>}{F10}{/Shift}");
143 await expect.element(copyPath).toHaveFocus();
144 await userEvent.keyboard("{Escape}");
145 await vi.waitFor(() => expect((row.getRootNode() as ShadowRoot).activeElement).toBe(row));
146 });
147
148 it("dragging a file row carries a composer mention without opening it, and dragend releases it", async () => {
149 const onOpenFile = vi.fn();
150 await using _screen = await render(
151 <FileBrowserPanel
152 environmentId={EnvironmentId.make("env-files")}
153 cwd="/repo"
154 projectName="repo"
155 selectedPath={null}
156 selectedPathRevealId={0}
157 onOpenFile={onOpenFile}
158 workspaceMutationId={null}
159 />,
160 );
161 await vi.waitFor(() => expect(findTreeRow("README.md")).not.toBeNull());
162 const row = findTreeRow("README.md")!;
163
164 const dataTransfer = new DataTransfer();
165 row.dispatchEvent(
166 new DragEvent("dragstart", { bubbles: true, cancelable: true, composed: true, dataTransfer }),
167 );
168 // The tree selects the row the drag picked up; mid-drag that must not open it.
169 row.click();
170 await vi.waitFor(() => expect(row.getAttribute("aria-selected")).toBe("true"));
171
172 expect(dataTransfer.getData(COMPOSER_MENTION_DRAG_TYPE)).toContain("README.md");
173 expect(onOpenFile).not.toHaveBeenCalled();
174
175 row.dispatchEvent(new DragEvent("dragend", { bubbles: true, composed: true, dataTransfer }));
176 await vi.waitFor(() => expect(row.getAttribute("aria-selected")).not.toBe("true"));
177
178 row.click();
179 await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(1));
180
181 // The selection stays put, so reopening the selected file must not depend on a selection change.
182 row.click();
183 await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(2));
184 });
185
186 it("keeps an expanded folder open when a very large listing rebuilds the tree", async () => {
187 using _listing = withDirectoryListing(entries);
188 const renderPanel = () => (
189 <FileBrowserPanel
190 environmentId={EnvironmentId.make("env-files")}
191 cwd="/repo-large-folder-1"
192 projectName="repo"
193 selectedPath={null}
194 selectedPathRevealId={0}
195 onOpenFile={() => {}}
196 workspaceMutationId={null}
197 />
198 );
199 await using screen = await render(renderPanel());
200 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
201 findTreeRow("src/")!.click();
202 await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
203
204 directory.entries = [
205 ...entries,
206 // Out of sort order, because inserting in order hides the cost of each insert.
207 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
208 const name = String((index * 7_919) % 2_000).padStart(4, "0");
209 return { path: `src/generated-${name}`, kind: "directory" };
210 }),
211 ];
212 await screen.rerender(renderPanel());
213
214 await vi.waitFor(() => expect(findTreeRow("src/generated-0000/")).not.toBeNull());
215 expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true");
216 });
217
218 it("keeps the selected file through a very large listing without reopening it", async () => {
219 const onOpenFile = vi.fn();
220 const renderPanel = () => (
221 <FileBrowserPanel
222 environmentId={EnvironmentId.make("env-files")}
223 cwd="/repo-large-folder-2"
224 projectName="repo"
225 selectedPath="src/aaa.ts"
226 selectedPathRevealId={1}
227 onOpenFile={onOpenFile}
228 workspaceMutationId={null}
229 />
230 );
231 using _listing = withDirectoryListing([...entries, { path: "src/aaa.ts", kind: "file" }]);
232 await using screen = await render(renderPanel());
233 await vi.waitFor(() =>
234 expect(findTreeRow("src/aaa.ts")?.getAttribute("aria-selected")).toBe("true"),
235 );
236
237 directory.entries = [
238 ...directory.entries,
239 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
240 const name = String((index * 7_919) % 2_000).padStart(4, "0");
241 return { path: `src/generated-${name}.ts`, kind: "file" };
242 }),
243 ];
244 await screen.rerender(renderPanel());
245
246 await vi.waitFor(() => expect(findTreeRow("src/generated-0000.ts")).not.toBeNull());
247 expect(findTreeRow("src/aaa.ts")?.getAttribute("aria-selected")).toBe("true");
248 expect(findTreeRow("src/")?.getAttribute("aria-expanded")).toBe("true");
249 expect(onOpenFile).not.toHaveBeenCalled();
250 });
251
252 it("keeps an open search accurate when a very large folder listing arrives", async () => {
253 const renderPanel = () => (
254 <FileBrowserPanel
255 environmentId={EnvironmentId.make("env-files")}
256 cwd="/repo-large-folder-3"
257 projectName="repo"
258 selectedPath={null}
259 selectedPathRevealId={0}
260 onOpenFile={() => {}}
261 workspaceMutationId={null}
262 />
263 );
264 using _listing = withDirectoryListing([
265 ...entries,
266 { path: "lib", kind: "directory" },
267 { path: "lib/generated-existing.ts", kind: "file" },
268 ]);
269 await using screen = await render(renderPanel());
270 const search = page.getByRole("searchbox", { name: "Search repo files" });
271 await userEvent.fill(search, "generated-");
272 await vi.waitFor(() => expect(findTreeRow("lib/generated-existing.ts")).not.toBeNull());
273
274 directory.entries = [
275 ...directory.entries,
276 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
277 const name = String((index * 7_919) % 2_000).padStart(4, "0");
278 return { path: `src/generated-${name}.ts`, kind: "file" };
279 }),
280 ];
281 await screen.rerender(renderPanel());
282
283 await vi.waitFor(() => expect(findTreeRow("src/generated-0000.ts")).not.toBeNull());
284 expect(findTreeRow("lib/generated-existing.ts")).not.toBeNull();
285 await expect.element(search).toHaveValue("generated-");
286 });
287
288 it("mod+f from a tree row, or the panel find command, focuses the file search", async () => {
289 await using _screen = await render(
290 <FileBrowserPanel
291 environmentId={EnvironmentId.make("env-files")}
292 cwd="/repo"
293 projectName="repo"
294 selectedPath={null}
295 selectedPathRevealId={0}
296 onOpenFile={() => {}}
297 workspaceMutationId={null}
298 answersPanelFind
299 />,
300 );
301 await vi.waitFor(() => expect(findTreeRow("README.md")).not.toBeNull());
302 findTreeRow("README.md")!.focus();
303
304 const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
305 await userEvent.keyboard(`{${modifier}>}f{/${modifier}}`);
306
307 const search = page.getByRole("searchbox", { name: "Search repo files" });
308 await expect.element(search).toHaveFocus();
309
310 (search.element() as HTMLElement).blur();
311 dispatchPreviewAction("find");
312 await expect.element(search).toHaveFocus();
313 });
314
315 it("Escape in the file search clears it without closing the panel sheet", async () => {
316 const onCloseSheet = vi.fn();
317 await using _screen = await render(
318 <RightPanelSheet animationDurationMs={0} open onClose={onCloseSheet}>
319 <FileBrowserPanel
320 environmentId={EnvironmentId.make("env-files")}
321 cwd="/repo"
322 projectName="repo"
323 selectedPath={null}
324 selectedPathRevealId={0}
325 onOpenFile={() => {}}
326 workspaceMutationId={null}
327 />
328 </RightPanelSheet>,
329 );
330 const search = page.getByRole("searchbox", { name: "Search repo files" });
331 await userEvent.fill(search, "read");
332 for (const composition of [
333 { key: "Escape", isComposing: true, keyCode: 27 },
334 { key: "Escape", isComposing: false, keyCode: 229 },
335 ]) {
336 // Safari ends the composition just before the Escape keydown.
337 await act(() => {
338 search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true }));
339 search
340 .element()
341 .dispatchEvent(new KeyboardEvent("keydown", { ...composition, bubbles: true }));
342 });
343 await expect.element(search).toHaveValue("read");
344 }
345 expect(search.element().getAttribute("type")).toBe("text");
346
347 await userEvent.keyboard("{Escape}");
348 await expect.element(search).toHaveValue("");
349 await expect.element(search).toHaveFocus();
350 await act(() => {
351 document.activeElement?.dispatchEvent(
352 new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true }),
353 );
354 });
355 expect(onCloseSheet).not.toHaveBeenCalled();
356
357 await userEvent.keyboard("{Escape}");
358 await vi.waitFor(() => expect(onCloseSheet).toHaveBeenCalledOnce());
359 });
360
361 it("keeps expanded folders when the panel remounts", async () => {
362 const panel = () => (
363 <FileBrowserPanel
364 environmentId={EnvironmentId.make("env-files")}
365 cwd="/repo"
366 projectName="repo"
367 selectedPath={null}
368 selectedPathRevealId={0}
369 onOpenFile={() => {}}
370 workspaceMutationId={null}
371 />
372 );
373 {
374 await using _first = await render(panel());
375 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
376 findTreeRow("src/")!.click();
377 await vi.waitFor(() =>
378 expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"),
379 );
380 }
381
382 using revalidate = vi.spyOn(directory, "revalidate");
383 await using _second = await render(panel());
384 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
385 await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
386
387 // Refresh revalidates the folders behind the rows on screen: the open one and the root.
388 // The tree can render its rows again at any time, so compare folders, not calls.
389 revalidate.mockClear();
390 await userEvent.click(page.getByRole("button", { name: "Refresh workspace files" }));
391 expect(new Set(revalidate.mock.calls.flat())).toEqual(new Set(["src", ""]));
392 });
393
394 it("opens a chain of single folders from one click and keeps it closed once closed", async () => {
395 const chain: readonly ProjectEntry[] = [
396 { path: "tests", kind: "directory" },
397 { path: "tests/edit", kind: "directory" },
398 { path: "tests/edit/unit", kind: "directory" },
399 { path: "tests/edit/unit/a.ts", kind: "file" },
400 ];
401 const panel = () => (
402 <FileBrowserPanel
403 environmentId={EnvironmentId.make("env-files")}
404 cwd="/repo-single-folder-chain"
405 projectName="repo"
406 selectedPath={null}
407 selectedPathRevealId={0}
408 onOpenFile={() => {}}
409 workspaceMutationId={null}
410 />
411 );
412 using _listing = withDirectoryListing(chain.slice(0, 1));
413 {
414 await using screen = await render(panel());
415 await vi.waitFor(() => expect(findTreeRow("tests/")).not.toBeNull());
416 findTreeRow("tests/")!.click();
417 await vi.waitFor(() =>
418 expect(findTreeRow("tests/")!.getAttribute("aria-expanded")).toBe("true"),
419 );
420 for (const listed of [2, 3, 4]) {
421 directory.entries = chain.slice(0, listed);
422 await screen.rerender(panel());
423 }
424 await vi.waitFor(() => expect(findTreeRow("tests/edit/unit/a.ts")).not.toBeNull());
425
426 findTreeRow("tests/edit/unit/")!.click();
427 await vi.waitFor(() => expect(findTreeRow("tests/edit/unit/a.ts")).toBeNull());
428 directory.entries = [...chain, { path: "tests/edit/unit/b.ts", kind: "file" }];
429 await screen.rerender(panel());
430 expect(findTreeRow("tests/edit/unit/")!.getAttribute("aria-expanded")).toBe("false");
431 }
432
433 directory.entries = [...chain, { path: "pkg", kind: "directory" }];
434 await using remounted = await render(panel());
435 await vi.waitFor(() => expect(findTreeRow("tests/edit/unit/")).not.toBeNull());
436 expect(findTreeRow("tests/edit/unit/")!.getAttribute("aria-expanded")).toBe("false");
437
438 // An ignored folder can hold tens of thousands of entries, so it still opens by hand.
439 findTreeRow("pkg/")!.click();
440 await vi.waitFor(() => expect(findTreeRow("pkg/")!.getAttribute("aria-expanded")).toBe("true"));
441 directory.entries = [
442 ...directory.entries,
443 { path: "pkg/node_modules", kind: "directory", ignored: true },
444 ];
445 await remounted.rerender(panel());
446 await vi.waitFor(() => expect(findTreeRow("pkg/node_modules/")).not.toBeNull());
447 expect(findTreeRow("pkg/node_modules/")!.getAttribute("aria-expanded")).toBe("false");
448 });
449
450 describe("revealing a folder while folders above it are still loading", () => {
451 const roots = Array.from({ length: 12 }, (_, index): ProjectEntry => {
452 return { path: `d${String(index).padStart(2, "0")}`, kind: "directory" };
453 });
454 const listing = (parent: string, count: number) =>
455 Array.from({ length: count }, (_, index): ProjectEntry => {
456 return { path: `${parent}/f${String(index).padStart(3, "0")}.ts`, kind: "file" };
457 });
458 const renderPanel = (cwd: string) => (
459 <FileBrowserPanel
460 environmentId={EnvironmentId.make("env-files")}
461 cwd={cwd}
462 projectName="repo"
463 selectedPath="d09"
464 selectedPathRevealId={1}
465 onOpenFile={() => {}}
466 workspaceMutationId={null}
467 />
468 );
469 // The tree mounts empty and measures itself before the first listing arrives, as it does for real.
470 async function renderRevealedPanel(cwd: string) {
471 writeExpandedDirectories(`env-files:${cwd}`, ["d01/", "d01/sub/"]);
472 directory.ready = false;
473 await using stack = new AsyncDisposableStack();
474 const screen = stack.use(await render(renderPanel(cwd), { container: sizedContainer() }));
475 directory.entries = roots;
476 directory.ready = true;
477 await screen.rerender(renderPanel(cwd));
478 await vi.waitFor(() => expect(isTreeRowInView("d09/")).toBe(true));
479 stack.move();
480 return screen;
481 }
482
483 it("keeps the revealed folder in view as restored folders above it load", async () => {
484 const cwd = "/repo-reveal-follows-loading";
485 using _listing = withDirectoryListing([]);
486 await using screen = await renderRevealedPanel(cwd);
487
488 // d01 lists after the reveal and holds another restored folder, which lists in turn.
489 directory.entries = [...roots, ...listing("d01", 60), { path: "d01/sub", kind: "directory" }];
490 await screen.rerender(renderPanel(cwd));
491 await vi.waitFor(() => expect(findTreeScroller()!.scrollHeight).toBeGreaterThan(60 * 24));
492 directory.entries = [...directory.entries, ...listing("d01/sub", 60)];
493 await screen.rerender(renderPanel(cwd));
494
495 await vi.waitFor(() => expect(isTreeRowInView("d09/")).toBe(true));
496 });
497
498 it("leaves the scroll position alone once the user scrolls the tree", async () => {
499 const cwd = "/repo-reveal-user-scroll";
500 using _listing = withDirectoryListing([]);
501 await using screen = await renderRevealedPanel(cwd);
502
503 const scroller = findTreeScroller()!;
504 scroller.dispatchEvent(new WheelEvent("wheel", { bubbles: true, composed: true }));
505 scroller.scrollTop = 0;
506 directory.entries = [...roots, ...listing("d01", 60)];
507 await screen.rerender(renderPanel(cwd));
508 await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(60 * 24));
509
510 expect(scroller.scrollTop).toBe(0);
511 });
512 });
513});