Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FileBrowserPanel.browser.test.tsx

501 lines19.1 KB

1import { EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
2import { describe, expect, it, vi } from "vite-plus/test";
3import { 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;
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;
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 );
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;
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 };
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 await vi.waitFor(() => expect(findTreeRow("README.md")).not.toBeNull());
114 findTreeRow("README.md")!.dispatchEvent(
115 new MouseEvent("contextmenu", {
116 bubbles: true,
117 cancelable: true,
118 composed: true,
119 button: 2,
120 }),
121 );
122 const action = page.getByRole("menuitem", { name: "Copy mention", exact: true });
123 await expect.element(action).toBeVisible();
124 await userEvent.click(action);
125 await vi.waitFor(() => expect(clipboard).toHaveBeenCalledWith("[README.md](README.md)"));
126​
127 const row = findTreeRow("README.md")!;
128 await userEvent.keyboard("{Tab}");
129 row.focus();
130 await userEvent.keyboard("{Shift>}{F10}{/Shift}");
131 await expect.element(action).toHaveFocus();
132 await userEvent.keyboard("{Escape}");
133 await vi.waitFor(() => expect((row.getRootNode() as ShadowRoot).activeElement).toBe(row));
134 });
135​
136 it("dragging a file row carries a composer mention without opening it, and dragend releases it", async () => {
137 const onOpenFile = vi.fn();
138 await using _screen = await render(
139 <FileBrowserPanel
140 environmentId={EnvironmentId.make("env-files")}
141 cwd="/repo"
142 projectName="repo"
143 selectedPath={null}
144 selectedPathRevealId={0}
145 onOpenFile={onOpenFile}
146 workspaceMutationId={null}
147 />,
148 );
149 await vi.waitFor(() => expect(findTreeRow("README.md")).not.toBeNull());
150 const row = findTreeRow("README.md")!;
151​
152 const dataTransfer = new DataTransfer();
153 row.dispatchEvent(
154 new DragEvent("dragstart", { bubbles: true, cancelable: true, composed: true, dataTransfer }),
155 );
156 // The tree selects the row the drag picked up; mid-drag that must not open it.
157 row.click();
158 await vi.waitFor(() => expect(row.getAttribute("aria-selected")).toBe("true"));
159​
160 expect(dataTransfer.getData(COMPOSER_MENTION_DRAG_TYPE)).toContain("README.md");
161 expect(onOpenFile).not.toHaveBeenCalled();
162​
163 row.dispatchEvent(new DragEvent("dragend", { bubbles: true, composed: true, dataTransfer }));
164 await vi.waitFor(() => expect(row.getAttribute("aria-selected")).not.toBe("true"));
165​
166 row.click();
167 await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(1));
168​
169 // The selection stays put, so reopening the selected file must not depend on a selection change.
170 row.click();
171 await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(2));
172 });
173​
174 it("keeps an expanded folder open when a very large listing rebuilds the tree", async () => {
175 using _listing = withDirectoryListing(entries);
176 const renderPanel = () => (
177 <FileBrowserPanel
178 environmentId={EnvironmentId.make("env-files")}
179 cwd="/repo-large-folder-1"
180 projectName="repo"
181 selectedPath={null}
182 selectedPathRevealId={0}
183 onOpenFile={() => {}}
184 workspaceMutationId={null}
185 />
186 );
187 await using screen = await render(renderPanel());
188 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
189 findTreeRow("src/")!.click();
190 await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
191​
192 directory.entries = [
193 ...entries,
194 // Out of sort order, because inserting in order hides the cost of each insert.
195 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
196 const name = String((index * 7_919) % 2_000).padStart(4, "0");
197 return { path: `src/generated-${name}`, kind: "directory" };
198 }),
199 ];
200 await screen.rerender(renderPanel());
201​
202 await vi.waitFor(() => expect(findTreeRow("src/generated-0000/")).not.toBeNull());
203 expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true");
204 });
205​
206 it("keeps the selected file through a very large listing without reopening it", async () => {
207 const onOpenFile = vi.fn();
208 const renderPanel = () => (
209 <FileBrowserPanel
210 environmentId={EnvironmentId.make("env-files")}
211 cwd="/repo-large-folder-2"
212 projectName="repo"
213 selectedPath="src/aaa.ts"
214 selectedPathRevealId={1}
215 onOpenFile={onOpenFile}
216 workspaceMutationId={null}
217 />
218 );
219 using _listing = withDirectoryListing([...entries, { path: "src/aaa.ts", kind: "file" }]);
220 await using screen = await render(renderPanel());
221 await vi.waitFor(() =>
222 expect(findTreeRow("src/aaa.ts")?.getAttribute("aria-selected")).toBe("true"),
223 );
224​
225 directory.entries = [
226 ...directory.entries,
227 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
228 const name = String((index * 7_919) % 2_000).padStart(4, "0");
229 return { path: `src/generated-${name}.ts`, kind: "file" };
230 }),
231 ];
232 await screen.rerender(renderPanel());
233​
234 await vi.waitFor(() => expect(findTreeRow("src/generated-0000.ts")).not.toBeNull());
235 expect(findTreeRow("src/aaa.ts")?.getAttribute("aria-selected")).toBe("true");
236 expect(findTreeRow("src/")?.getAttribute("aria-expanded")).toBe("true");
237 expect(onOpenFile).not.toHaveBeenCalled();
238 });
239​
240 it("keeps an open search accurate when a very large folder listing arrives", async () => {
241 const renderPanel = () => (
242 <FileBrowserPanel
243 environmentId={EnvironmentId.make("env-files")}
244 cwd="/repo-large-folder-3"
245 projectName="repo"
246 selectedPath={null}
247 selectedPathRevealId={0}
248 onOpenFile={() => {}}
249 workspaceMutationId={null}
250 />
251 );
252 using _listing = withDirectoryListing([
253 ...entries,
254 { path: "lib", kind: "directory" },
255 { path: "lib/generated-existing.ts", kind: "file" },
256 ]);
257 await using screen = await render(renderPanel());
258 const search = page.getByRole("searchbox", { name: "Search repo files" });
259 await userEvent.fill(search, "generated-");
260 await vi.waitFor(() => expect(findTreeRow("lib/generated-existing.ts")).not.toBeNull());
261​
262 directory.entries = [
263 ...directory.entries,
264 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
265 const name = String((index * 7_919) % 2_000).padStart(4, "0");
266 return { path: `src/generated-${name}.ts`, kind: "file" };
267 }),
268 ];
269 await screen.rerender(renderPanel());
270​
271 await vi.waitFor(() => expect(findTreeRow("src/generated-0000.ts")).not.toBeNull());
272 expect(findTreeRow("lib/generated-existing.ts")).not.toBeNull();
273 await expect.element(search).toHaveValue("generated-");
274 });
275​
276 it("mod+f from a tree row, or the panel find command, focuses the file search", async () => {
277 await using _screen = await render(
278 <FileBrowserPanel
279 environmentId={EnvironmentId.make("env-files")}
280 cwd="/repo"
281 projectName="repo"
282 selectedPath={null}
283 selectedPathRevealId={0}
284 onOpenFile={() => {}}
285 workspaceMutationId={null}
286 answersPanelFind
287 />,
288 );
289 await vi.waitFor(() => expect(findTreeRow("README.md")).not.toBeNull());
290 findTreeRow("README.md")!.focus();
291​
292 const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
293 await userEvent.keyboard(`{${modifier}>}f{/${modifier}}`);
294​
295 const search = page.getByRole("searchbox", { name: "Search repo files" });
296 await expect.element(search).toHaveFocus();
297​
298 (search.element() as HTMLElement).blur();
299 dispatchPreviewAction("find");
300 await expect.element(search).toHaveFocus();
301 });
302​
303 it("Escape in the file search clears it without closing the panel sheet", async () => {
304 const onCloseSheet = vi.fn();
305 await using _screen = await render(
306 <RightPanelSheet animationDurationMs={0} open onClose={onCloseSheet}>
307 <FileBrowserPanel
308 environmentId={EnvironmentId.make("env-files")}
309 cwd="/repo"
310 projectName="repo"
311 selectedPath={null}
312 selectedPathRevealId={0}
313 onOpenFile={() => {}}
314 workspaceMutationId={null}
315 />
316 </RightPanelSheet>,
317 );
318 const search = page.getByRole("searchbox", { name: "Search repo files" });
319 await userEvent.fill(search, "read");
320 for (const composition of [
321 { key: "Escape", isComposing: true, keyCode: 27 },
322 { key: "Escape", isComposing: false, keyCode: 229 },
323 ]) {
324 // Safari ends the composition just before the Escape keydown.
325 await act(() => {
326 search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true }));
327 search
328 .element()
329 .dispatchEvent(new KeyboardEvent("keydown", { ...composition, bubbles: true }));
330 });
331 await expect.element(search).toHaveValue("read");
332 }
333 expect(search.element().getAttribute("type")).toBe("text");
334​
335 await userEvent.keyboard("{Escape}");
336 await expect.element(search).toHaveValue("");
337 await expect.element(search).toHaveFocus();
338 await act(() => {
339 document.activeElement?.dispatchEvent(
340 new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true }),
341 );
342 });
343 expect(onCloseSheet).not.toHaveBeenCalled();
344​
345 await userEvent.keyboard("{Escape}");
346 await vi.waitFor(() => expect(onCloseSheet).toHaveBeenCalledOnce());
347 });
348​
349 it("keeps expanded folders when the panel remounts", async () => {
350 const panel = () => (
351 <FileBrowserPanel
352 environmentId={EnvironmentId.make("env-files")}
353 cwd="/repo"
354 projectName="repo"
355 selectedPath={null}
356 selectedPathRevealId={0}
357 onOpenFile={() => {}}
358 workspaceMutationId={null}
359 />
360 );
361 {
362 await using _first = await render(panel());
363 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
364 findTreeRow("src/")!.click();
365 await vi.waitFor(() =>
366 expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"),
367 );
368 }
369​
370 using revalidate = vi.spyOn(directory, "revalidate");
371 await using _second = await render(panel());
372 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
373 await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
374​
375 // Refresh revalidates the folders behind the rows on screen: the open one and the root.
376 // The tree can render its rows again at any time, so compare folders, not calls.
377 revalidate.mockClear();
378 await userEvent.click(page.getByRole("button", { name: "Refresh workspace files" }));
379 expect(new Set(revalidate.mock.calls.flat())).toEqual(new Set(["src", ""]));
380 });
381​
382 it("opens a chain of single folders from one click and keeps it closed once closed", async () => {
383 const chain: readonly ProjectEntry[] = [
384 { path: "tests", kind: "directory" },
385 { path: "tests/edit", kind: "directory" },
386 { path: "tests/edit/unit", kind: "directory" },
387 { path: "tests/edit/unit/a.ts", kind: "file" },
388 ];
389 const panel = () => (
390 <FileBrowserPanel
391 environmentId={EnvironmentId.make("env-files")}
392 cwd="/repo-single-folder-chain"
393 projectName="repo"
394 selectedPath={null}
395 selectedPathRevealId={0}
396 onOpenFile={() => {}}
397 workspaceMutationId={null}
398 />
399 );
400 using _listing = withDirectoryListing(chain.slice(0, 1));
401 {
402 await using screen = await render(panel());
403 await vi.waitFor(() => expect(findTreeRow("tests/")).not.toBeNull());
404 findTreeRow("tests/")!.click();
405 await vi.waitFor(() =>
406 expect(findTreeRow("tests/")!.getAttribute("aria-expanded")).toBe("true"),
407 );
408 for (const listed of [2, 3, 4]) {
409 directory.entries = chain.slice(0, listed);
410 await screen.rerender(panel());
411 }
412 await vi.waitFor(() => expect(findTreeRow("tests/edit/unit/a.ts")).not.toBeNull());
413​
414 findTreeRow("tests/edit/unit/")!.click();
415 await vi.waitFor(() => expect(findTreeRow("tests/edit/unit/a.ts")).toBeNull());
416 directory.entries = [...chain, { path: "tests/edit/unit/b.ts", kind: "file" }];
417 await screen.rerender(panel());
418 expect(findTreeRow("tests/edit/unit/")!.getAttribute("aria-expanded")).toBe("false");
419 }
420​
421 directory.entries = [...chain, { path: "pkg", kind: "directory" }];
422 await using remounted = await render(panel());
423 await vi.waitFor(() => expect(findTreeRow("tests/edit/unit/")).not.toBeNull());
424 expect(findTreeRow("tests/edit/unit/")!.getAttribute("aria-expanded")).toBe("false");
425​
426 // An ignored folder can hold tens of thousands of entries, so it still opens by hand.
427 findTreeRow("pkg/")!.click();
428 await vi.waitFor(() => expect(findTreeRow("pkg/")!.getAttribute("aria-expanded")).toBe("true"));
429 directory.entries = [
430 ...directory.entries,
431 { path: "pkg/node_modules", kind: "directory", ignored: true },
432 ];
433 await remounted.rerender(panel());
434 await vi.waitFor(() => expect(findTreeRow("pkg/node_modules/")).not.toBeNull());
435 expect(findTreeRow("pkg/node_modules/")!.getAttribute("aria-expanded")).toBe("false");
436 });
437​
438 describe("revealing a folder while folders above it are still loading", () => {
439 const roots = Array.from({ length: 12 }, (_, index): ProjectEntry => {
440 return { path: `d${String(index).padStart(2, "0")}`, kind: "directory" };
441 });
442 const listing = (parent: string, count: number) =>
443 Array.from({ length: count }, (_, index): ProjectEntry => {
444 return { path: `${parent}/f${String(index).padStart(3, "0")}.ts`, kind: "file" };
445 });
446 const renderPanel = (cwd: string) => (
447 <FileBrowserPanel
448 environmentId={EnvironmentId.make("env-files")}
449 cwd={cwd}
450 projectName="repo"
451 selectedPath="d09"
452 selectedPathRevealId={1}
453 onOpenFile={() => {}}
454 workspaceMutationId={null}
455 />
456 );
457 // The tree mounts empty and measures itself before the first listing arrives, as it does for real.
458 async function renderRevealedPanel(cwd: string) {
459 writeExpandedDirectories(`env-files:${cwd}`, ["d01/", "d01/sub/"]);
460 directory.ready = false;
461 await using stack = new AsyncDisposableStack();
462 const screen = stack.use(await render(renderPanel(cwd), { container: sizedContainer() }));
463 directory.entries = roots;
464 directory.ready = true;
465 await screen.rerender(renderPanel(cwd));
466 await vi.waitFor(() => expect(isTreeRowInView("d09/")).toBe(true));
467 stack.move();
468 return screen;
469 }
470​
471 it("keeps the revealed folder in view as restored folders above it load", async () => {
472 const cwd = "/repo-reveal-follows-loading";
473 using _listing = withDirectoryListing([]);
474 await using screen = await renderRevealedPanel(cwd);
475​
476 // d01 lists after the reveal and holds another restored folder, which lists in turn.
477 directory.entries = [...roots, ...listing("d01", 60), { path: "d01/sub", kind: "directory" }];
478 await screen.rerender(renderPanel(cwd));
479 await vi.waitFor(() => expect(findTreeScroller()!.scrollHeight).toBeGreaterThan(60 * 24));
480 directory.entries = [...directory.entries, ...listing("d01/sub", 60)];
481 await screen.rerender(renderPanel(cwd));
482​
483 await vi.waitFor(() => expect(isTreeRowInView("d09/")).toBe(true));
484 });
485​
486 it("leaves the scroll position alone once the user scrolls the tree", async () => {
487 const cwd = "/repo-reveal-user-scroll";
488 using _listing = withDirectoryListing([]);
489 await using screen = await renderRevealedPanel(cwd);
490​
491 const scroller = findTreeScroller()!;
492 scroller.dispatchEvent(new WheelEvent("wheel", { bubbles: true, composed: true }));
493 scroller.scrollTop = 0;
494 directory.entries = [...roots, ...listing("d01", 60)];
495 await screen.rerender(renderPanel(cwd));
496 await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(60 * 24));
497​
498 expect(scroller.scrollTop).toBe(0);
499 });
500 });
501});