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