@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 384 lines 14.2 KB
Raw
1 import { EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
2 import { describe, expect, it, vi } from "vite-plus/test";
3 import { page, userEvent } from "vite-plus/test/browser";
4
5 import { COMPOSER_MENTION_DRAG_TYPE } from "~/components/chat/composerMentionDrag";
6 import { dismissContextMenu } from "~/contextMenuFallback";
7 import { isMacPlatform } from "~/lib/utils";
8 import { render } from "../../../test/render";
9 import FileBrowserPanel from "./FileBrowserPanel";
10 import { dispatchPreviewAction } from "../preview/previewActionBus";
11 import { writeExpandedDirectories } from "./fileTreeExpansion";
12
13 const entries: readonly ProjectEntry[] = [
14 { path: "src", kind: "directory" },
15 { path: "README.md", kind: "file" },
16 ];
17 const loadingDirectories: ReadonlySet<string> = new Set();
18 const 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 };
35 const pathSearch = {
36 entries: [],
37 isPending: false,
38 error: null,
39 truncated: false,
40 refresh: () => {},
41 };
42
43 vi.mock("./useDirectoryEntries", () => ({ useDirectoryEntries: () => directory }));
44 vi.mock("~/state/queries", () => ({ useProjectPathSearch: () => pathSearch }));
45 vi.mock("~/fileContextMenu", () => ({
46 useFileContextMenu: () => ({ buildItems: () => [], activate: () => Promise.resolve() }),
47 }));
48 vi.mock("~/hooks/useWorkspaceMutationRefresh", () => ({ useWorkspaceMutationRefresh: () => {} }));
49
50 function 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
58 function 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
68 function 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
79 function 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
85 function 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
95 describe("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
167 it("keeps an expanded folder open when a very large listing rebuilds the tree", async () => {
168 using _listing = withDirectoryListing(entries);
169 const renderPanel = () => (
170 <FileBrowserPanel
171 environmentId={EnvironmentId.make("env-files")}
172 cwd="/repo-large-folder-1"
173 projectName="repo"
174 selectedPath={null}
175 selectedPathRevealId={0}
176 onOpenFile={() => {}}
177 workspaceMutationId={null}
178 />
179 );
180 await using screen = await render(renderPanel());
181 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
182 findTreeRow("src/")!.click();
183 await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
184
185 directory.entries = [
186 ...entries,
187 // Out of sort order, because inserting in order hides the cost of each insert.
188 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
189 const name = String((index * 7_919) % 2_000).padStart(4, "0");
190 return { path: `src/generated-${name}`, kind: "directory" };
191 }),
192 ];
193 await screen.rerender(renderPanel());
194
195 await vi.waitFor(() => expect(findTreeRow("src/generated-0000/")).not.toBeNull());
196 expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true");
197 });
198
199 it("keeps the selected file through a very large listing without reopening it", async () => {
200 const onOpenFile = vi.fn();
201 const renderPanel = () => (
202 <FileBrowserPanel
203 environmentId={EnvironmentId.make("env-files")}
204 cwd="/repo-large-folder-2"
205 projectName="repo"
206 selectedPath="src/aaa.ts"
207 selectedPathRevealId={1}
208 onOpenFile={onOpenFile}
209 workspaceMutationId={null}
210 />
211 );
212 using _listing = withDirectoryListing([...entries, { path: "src/aaa.ts", kind: "file" }]);
213 await using screen = await render(renderPanel());
214 await vi.waitFor(() =>
215 expect(findTreeRow("src/aaa.ts")?.getAttribute("aria-selected")).toBe("true"),
216 );
217
218 directory.entries = [
219 ...directory.entries,
220 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
221 const name = String((index * 7_919) % 2_000).padStart(4, "0");
222 return { path: `src/generated-${name}.ts`, kind: "file" };
223 }),
224 ];
225 await screen.rerender(renderPanel());
226
227 await vi.waitFor(() => expect(findTreeRow("src/generated-0000.ts")).not.toBeNull());
228 expect(findTreeRow("src/aaa.ts")?.getAttribute("aria-selected")).toBe("true");
229 expect(findTreeRow("src/")?.getAttribute("aria-expanded")).toBe("true");
230 expect(onOpenFile).not.toHaveBeenCalled();
231 });
232
233 it("keeps an open search accurate when a very large folder listing arrives", async () => {
234 const renderPanel = () => (
235 <FileBrowserPanel
236 environmentId={EnvironmentId.make("env-files")}
237 cwd="/repo-large-folder-3"
238 projectName="repo"
239 selectedPath={null}
240 selectedPathRevealId={0}
241 onOpenFile={() => {}}
242 workspaceMutationId={null}
243 />
244 );
245 using _listing = withDirectoryListing([
246 ...entries,
247 { path: "lib", kind: "directory" },
248 { path: "lib/generated-existing.ts", kind: "file" },
249 ]);
250 await using screen = await render(renderPanel());
251 const search = page.getByRole("searchbox", { name: "Search repo files" });
252 await userEvent.fill(search, "generated-");
253 await vi.waitFor(() => expect(findTreeRow("lib/generated-existing.ts")).not.toBeNull());
254
255 directory.entries = [
256 ...directory.entries,
257 ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
258 const name = String((index * 7_919) % 2_000).padStart(4, "0");
259 return { path: `src/generated-${name}.ts`, kind: "file" };
260 }),
261 ];
262 await screen.rerender(renderPanel());
263
264 await vi.waitFor(() => expect(findTreeRow("src/generated-0000.ts")).not.toBeNull());
265 expect(findTreeRow("lib/generated-existing.ts")).not.toBeNull();
266 await expect.element(search).toHaveValue("generated-");
267 });
268
269 it("mod+f from a tree row, or the panel find command, focuses the file search", async () => {
270 await using _screen = await render(
271 <FileBrowserPanel
272 environmentId={EnvironmentId.make("env-files")}
273 cwd="/repo"
274 projectName="repo"
275 selectedPath={null}
276 selectedPathRevealId={0}
277 onOpenFile={() => {}}
278 workspaceMutationId={null}
279 answersPanelFind
280 />,
281 );
282 await vi.waitFor(() => expect(findTreeRow("README.md")).not.toBeNull());
283 findTreeRow("README.md")!.focus();
284
285 const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
286 await userEvent.keyboard(`{${modifier}>}f{/${modifier}}`);
287
288 const search = page.getByRole("searchbox", { name: "Search repo files" });
289 await expect.element(search).toHaveFocus();
290
291 (search.element() as HTMLElement).blur();
292 dispatchPreviewAction("find");
293 await expect.element(search).toHaveFocus();
294 });
295
296 it("keeps expanded folders when the panel remounts", async () => {
297 const panel = () => (
298 <FileBrowserPanel
299 environmentId={EnvironmentId.make("env-files")}
300 cwd="/repo"
301 projectName="repo"
302 selectedPath={null}
303 selectedPathRevealId={0}
304 onOpenFile={() => {}}
305 workspaceMutationId={null}
306 />
307 );
308 {
309 await using _first = await render(panel());
310 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
311 findTreeRow("src/")!.click();
312 await vi.waitFor(() =>
313 expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"),
314 );
315 }
316
317 await using _second = await render(panel());
318 await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
319 await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
320 });
321 describe("revealing a folder while folders above it are still loading", () => {
322 const roots = Array.from({ length: 12 }, (_, index): ProjectEntry => {
323 return { path: `d${String(index).padStart(2, "0")}`, kind: "directory" };
324 });
325 const listing = (parent: string, count: number) =>
326 Array.from({ length: count }, (_, index): ProjectEntry => {
327 return { path: `${parent}/f${String(index).padStart(3, "0")}.ts`, kind: "file" };
328 });
329 const renderPanel = (cwd: string) => (
330 <FileBrowserPanel
331 environmentId={EnvironmentId.make("env-files")}
332 cwd={cwd}
333 projectName="repo"
334 selectedPath="d09"
335 selectedPathRevealId={1}
336 onOpenFile={() => {}}
337 workspaceMutationId={null}
338 />
339 );
340 // The tree mounts empty and measures itself before the first listing arrives, as it does for real.
341 async function renderRevealedPanel(cwd: string) {
342 writeExpandedDirectories(`env-files:${cwd}`, ["d01/", "d01/sub/"]);
343 directory.ready = false;
344 await using stack = new AsyncDisposableStack();
345 const screen = stack.use(await render(renderPanel(cwd), { container: sizedContainer() }));
346 directory.entries = roots;
347 directory.ready = true;
348 await screen.rerender(renderPanel(cwd));
349 await vi.waitFor(() => expect(isTreeRowInView("d09/")).toBe(true));
350 stack.move();
351 return screen;
352 }
353
354 it("keeps the revealed folder in view as restored folders above it load", async () => {
355 const cwd = "/repo-reveal-follows-loading";
356 using _listing = withDirectoryListing([]);
357 await using screen = await renderRevealedPanel(cwd);
358
359 // d01 lists after the reveal and holds another restored folder, which lists in turn.
360 directory.entries = [...roots, ...listing("d01", 60), { path: "d01/sub", kind: "directory" }];
361 await screen.rerender(renderPanel(cwd));
362 await vi.waitFor(() => expect(findTreeScroller()!.scrollHeight).toBeGreaterThan(60 * 24));
363 directory.entries = [...directory.entries, ...listing("d01/sub", 60)];
364 await screen.rerender(renderPanel(cwd));
365
366 await vi.waitFor(() => expect(isTreeRowInView("d09/")).toBe(true));
367 });
368
369 it("leaves the scroll position alone once the user scrolls the tree", async () => {
370 const cwd = "/repo-reveal-user-scroll";
371 using _listing = withDirectoryListing([]);
372 await using screen = await renderRevealedPanel(cwd);
373
374 const scroller = findTreeScroller()!;
375 scroller.dispatchEvent(new WheelEvent("wheel", { bubbles: true, composed: true }));
376 scroller.scrollTop = 0;
377 directory.entries = [...roots, ...listing("d01", 60)];
378 await screen.rerender(renderPanel(cwd));
379 await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(60 * 24));
380
381 expect(scroller.scrollTop).toBe(0);
382 });
383 });
384 });