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