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

FileBrowserPanel.browser.test.tsx

292 lines10.5 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 { dismissContextMenu } from "~/contextMenuFallback";
7import { isMacPlatform } from "~/lib/utils";
8import { render } from "../../../test/render";
9import FileBrowserPanel from "./FileBrowserPanel";
10import { dispatchPreviewAction } from "../preview/previewActionBus";
11​
12const entries: readonly ProjectEntry[] = [
13 { path: "src", kind: "directory" },
14 { path: "README.md", kind: "file" },
15];
16const loadingDirectories: ReadonlySet<string> = new Set();
17const directory: {
18 entries: readonly ProjectEntry[];
19 load: () => Promise<void>;
20 refresh: () => void;
21 ready: boolean;
22 error: null;
23 isPending: boolean;
24 loadingDirectories: ReadonlySet<string>;
25} = {
26 entries,
27 load: () => Promise.resolve(),
28 refresh: () => {},
29 ready: true,
30 error: null,
31 isPending: false,
32 loadingDirectories,
33};
34const pathSearch = {
35 entries: [],
36 isPending: false,
37 error: null,
38 truncated: false,
39 refresh: () => {},
40};
41​
42vi.mock("./useDirectoryEntries", () => ({ useDirectoryEntries: () => directory }));
43vi.mock("~/state/queries", () => ({ useProjectPathSearch: () => pathSearch }));
44vi.mock("~/fileContextMenu", () => ({
45 useFileContextMenu: () => ({ buildItems: () => [], activate: () => Promise.resolve() }),
46}));
47vi.mock("~/hooks/useWorkspaceMutationRefresh", () => ({ useWorkspaceMutationRefresh: () => {} }));
48​
49function findTreeRow(path: string): HTMLElement | null {
50 for (const host of document.querySelectorAll("*")) {
51 const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${path}"]`);
52 if (row) return row;
53 }
54 return null;
56​
57function withDirectoryListing(listing: readonly ProjectEntry[]): Disposable {
58 directory.entries = listing;
59 return {
60 [Symbol.dispose]: () => {
61 directory.entries = entries;
62 },
63 };
65​
66describe("FileBrowserPanel", () => {
67 it("copies with the pointer and returns to the row after keyboard dismissal", async () => {
68 await using _screen = await render(
69 <FileBrowserPanel
70 environmentId={EnvironmentId.make("env-files")}
71 cwd="/repo"
72 projectName="repo"
73 selectedPath={null}
74 selectedPathRevealId={0}
75 onOpenFile={() => {}}
76 workspaceMutationId={null}
77 />,
78 );
79 using _menu = { [Symbol.dispose]: () => dismissContextMenu() };
80 using clipboard = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined);
81 await vi.waitFor(() => expect(findTreeRow("README.md")).not.toBeNull());
82 findTreeRow("README.md")!.dispatchEvent(
83 new MouseEvent("contextmenu", {
84 bubbles: true,
85 cancelable: true,
86 composed: true,
87 button: 2,
88 }),
89 );
90 const action = page.getByRole("menuitem", { name: "Copy mention", exact: true });
91 await expect.element(action).toBeVisible();
92 await userEvent.click(action);
93 await vi.waitFor(() => expect(clipboard).toHaveBeenCalledWith("[README.md](README.md)"));
94​
95 const row = findTreeRow("README.md")!;
96 await userEvent.keyboard("{Tab}");
97 row.focus();
98 await userEvent.keyboard("{Shift>}{F10}{/Shift}");
99 await expect.element(action).toHaveFocus();
100 await userEvent.keyboard("{Escape}");
101 await vi.waitFor(() => expect((row.getRootNode() as ShadowRoot).activeElement).toBe(row));
102 });
103​
104 it("dragging a file row carries a composer mention without opening it, and dragend releases it", async () => {
105 const onOpenFile = vi.fn();
106 await using _screen = await render(
107 <FileBrowserPanel
108 environmentId={EnvironmentId.make("env-files")}
109 cwd="/repo"
110 projectName="repo"
111 selectedPath={null}
112 selectedPathRevealId={0}
113 onOpenFile={onOpenFile}
114 workspaceMutationId={null}
115 />,
116 );
117 await vi.waitFor(() => expect(findTreeRow("README.md")).not.toBeNull());
118 const row = findTreeRow("README.md")!;
119​
120 const dataTransfer = new DataTransfer();
121 row.dispatchEvent(
122 new DragEvent("dragstart", { bubbles: true, cancelable: true, composed: true, dataTransfer }),
123 );
124 // The tree selects the row the drag picked up; mid-drag that must not open it.
125 row.click();
126 await vi.waitFor(() => expect(row.getAttribute("aria-selected")).toBe("true"));
127​
128 expect(dataTransfer.getData(COMPOSER_MENTION_DRAG_TYPE)).toContain("README.md");
129 expect(onOpenFile).not.toHaveBeenCalled();
130​
131 row.dispatchEvent(new DragEvent("dragend", { bubbles: true, composed: true, dataTransfer }));
132 await vi.waitFor(() => expect(row.getAttribute("aria-selected")).not.toBe("true"));
133​
134 row.click();
135 await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(1));
136 });
137​
138 it("keeps an expanded folder open when a very large listing rebuilds the tree", async () => {
139 using _listing = withDirectoryListing(entries);
140 const renderPanel = () => (
141 <FileBrowserPanel
142 environmentId={EnvironmentId.make("env-files")}
143 cwd="/repo-large-folder-1"
144 projectName="repo"
145 selectedPath={null}
146 selectedPathRevealId={0}
147 onOpenFile={() => {}}
148 workspaceMutationId={null}
149 />
150 );
151 await using screen = await render(renderPanel());
152 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
153 findTreeRow("src/")!.click();
154 await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
155​
156 directory.entries = [
157 ...entries,
158 // Out of sort order, because inserting in order hides the cost of each insert.
159 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
160 const name = String((index * 7_919) % 2_000).padStart(4, "0");
161 return { path: `src/generated-${name}`, kind: "directory" };
162 }),
163 ];
164 await screen.rerender(renderPanel());
165​
166 await vi.waitFor(() => expect(findTreeRow("src/generated-0000/")).not.toBeNull());
167 expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true");
168 });
169​
170 it("keeps the selected file through a very large listing without reopening it", async () => {
171 const onOpenFile = vi.fn();
172 const renderPanel = () => (
173 <FileBrowserPanel
174 environmentId={EnvironmentId.make("env-files")}
175 cwd="/repo-large-folder-2"
176 projectName="repo"
177 selectedPath="src/aaa.ts"
178 selectedPathRevealId={1}
179 onOpenFile={onOpenFile}
180 workspaceMutationId={null}
181 />
182 );
183 using _listing = withDirectoryListing([...entries, { path: "src/aaa.ts", kind: "file" }]);
184 await using screen = await render(renderPanel());
185 await vi.waitFor(() =>
186 expect(findTreeRow("src/aaa.ts")?.getAttribute("aria-selected")).toBe("true"),
187 );
188​
189 directory.entries = [
190 ...directory.entries,
191 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
192 const name = String((index * 7_919) % 2_000).padStart(4, "0");
193 return { path: `src/generated-${name}.ts`, kind: "file" };
194 }),
195 ];
196 await screen.rerender(renderPanel());
197​
198 await vi.waitFor(() => expect(findTreeRow("src/generated-0000.ts")).not.toBeNull());
199 expect(findTreeRow("src/aaa.ts")?.getAttribute("aria-selected")).toBe("true");
200 expect(findTreeRow("src/")?.getAttribute("aria-expanded")).toBe("true");
201 expect(onOpenFile).not.toHaveBeenCalled();
202 });
203​
204 it("keeps an open search accurate when a very large folder listing arrives", async () => {
205 const renderPanel = () => (
206 <FileBrowserPanel
207 environmentId={EnvironmentId.make("env-files")}
208 cwd="/repo-large-folder-3"
209 projectName="repo"
210 selectedPath={null}
211 selectedPathRevealId={0}
212 onOpenFile={() => {}}
213 workspaceMutationId={null}
214 />
215 );
216 using _listing = withDirectoryListing([
217 ...entries,
218 { path: "lib", kind: "directory" },
219 { path: "lib/generated-existing.ts", kind: "file" },
220 ]);
221 await using screen = await render(renderPanel());
222 const search = page.getByRole("searchbox", { name: "Search repo files" });
223 await userEvent.fill(search, "generated-");
224 await vi.waitFor(() => expect(findTreeRow("lib/generated-existing.ts")).not.toBeNull());
225​
226 directory.entries = [
227 ...directory.entries,
228 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
229 const name = String((index * 7_919) % 2_000).padStart(4, "0");
230 return { path: `src/generated-${name}.ts`, kind: "file" };
231 }),
232 ];
233 await screen.rerender(renderPanel());
234​
235 await vi.waitFor(() => expect(findTreeRow("src/generated-0000.ts")).not.toBeNull());
236 expect(findTreeRow("lib/generated-existing.ts")).not.toBeNull();
237 await expect.element(search).toHaveValue("generated-");
238 });
239​
240 it("mod+f from a tree row, or the panel find command, focuses the file search", async () => {
241 await using _screen = await render(
242 <FileBrowserPanel
243 environmentId={EnvironmentId.make("env-files")}
244 cwd="/repo"
245 projectName="repo"
246 selectedPath={null}
247 selectedPathRevealId={0}
248 onOpenFile={() => {}}
249 workspaceMutationId={null}
250 answersPanelFind
251 />,
252 );
253 await vi.waitFor(() => expect(findTreeRow("README.md")).not.toBeNull());
254 findTreeRow("README.md")!.focus();
255​
256 const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
257 await userEvent.keyboard(`{${modifier}>}f{/${modifier}}`);
258​
259 const search = page.getByRole("searchbox", { name: "Search repo files" });
260 await expect.element(search).toHaveFocus();
261​
262 (search.element() as HTMLElement).blur();
263 dispatchPreviewAction("find");
264 await expect.element(search).toHaveFocus();
265 });
266​
267 it("keeps expanded folders when the panel remounts", async () => {
268 const panel = () => (
269 <FileBrowserPanel
270 environmentId={EnvironmentId.make("env-files")}
271 cwd="/repo"
272 projectName="repo"
273 selectedPath={null}
274 selectedPathRevealId={0}
275 onOpenFile={() => {}}
276 workspaceMutationId={null}
277 />
278 );
279 {
280 await using _first = await render(panel());
281 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
282 findTreeRow("src/")!.click();
283 await vi.waitFor(() =>
284 expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"),
285 );
286 }
287​
288 await using _second = await render(panel());
289 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
290 await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
291 });
292});