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

FileBrowserPanel.browser.test.tsx

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