Open History to see the last commit
1import "../../index.css";
2
3import { EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
4import { act, type ReactNode } from "react";
5import { createRoot, type Root } from "react-dom/client";
6import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7
8import FileBrowserPanel from "./FileBrowserPanel";
9
10const files = vi.hoisted(() => ({
11 directoryEntries: [] as ProjectEntry[],
12 directoryReady: true,
13 directoryPending: false,
14 searchEntries: [] as ProjectEntry[],
15 searchPending: false,
16 searchError: null as string | null,
17 loadingDirectories: new Set<string>() as ReadonlySet<string>,
18 load: vi.fn(async (_directoryPath: string) => {}),
19 refresh: vi.fn(),
20}));
21
22vi.mock("./useDirectoryEntries", () => ({
23 useDirectoryEntries: () => ({
24 entries: files.directoryEntries,
25 loadingDirectories: files.loadingDirectories,
26 load: files.load,
27 refresh: files.refresh,
28 ready: files.directoryReady,
29 error: null,
30 isPending: files.directoryPending,
31 }),
32}));
33vi.mock("~/state/queries", () => ({
34 useProjectPathSearch: () => ({
35 entries: files.searchEntries,
36 isPending: files.searchPending,
37 error: files.searchError,
38 truncated: false,
39 refresh: files.refresh,
40 }),
41}));
42vi.mock("~/hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
43vi.mock("~/hooks/useWorkspaceMutationRefresh", () => ({ useWorkspaceMutationRefresh: vi.fn() }));
44vi.mock("~/composerHandleContext", () => ({ useComposerHandleContext: () => null }));
45vi.mock("~/fileContextMenu", () => ({ useFileContextMenu: () => ({}) }));
46vi.mock("~/localApi", () => ({ readLocalApi: () => undefined }));
47vi.mock("~/components/ui/toast", () => ({ toastManager: { add: vi.fn() } }));
48vi.mock("~/components/MorphIcon", () => ({ MorphIcon: () => null }));
49vi.mock("~/components/ui/tooltip", () => ({
50 Tooltip: ({ children }: { children: ReactNode }) => children,
51 TooltipTrigger: ({ render }: { render: ReactNode }) => render,
52 TooltipPopup: () => null,
53}));
54
55describe("Files panel", () => {
56 let root: Root | undefined;
57 let container: HTMLDivElement | undefined;
58 const props = {
59 environmentId: EnvironmentId.make("test-environment"),
60 cwd: "/workspace",
61 projectName: "Test project",
62 selectedPath: null,
63 selectedPathRevealId: 0,
64 onOpenFile: vi.fn(),
65 workspaceMutationId: null,
66 };
67
68 async function render() {
69 if (!container) {
70 container = document.body.appendChild(document.createElement("div"));
71 // The tree virtualizes its rows, so it needs a real viewport to render any.
72 container.style.cssText =
73 "display: flex; flex-direction: column; width: 320px; height: 480px;";
74 root = createRoot(container);
75 }
76 await act(async () => root!.render(<FileBrowserPanel {...props} />));
77 }
78
79 function searchInput() {
80 const input = container!.querySelector<HTMLInputElement>('input[type="search"]');
81 expect(input).not.toBeNull();
82 return input!;
83 }
84
85 async function search(value: string) {
86 const input = searchInput();
87 // React tracks the last value it saw on the element, so set it through the native setter.
88 Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
89 await act(async () => {
90 input.dispatchEvent(new Event("input", { bubbles: true }));
91 });
92 }
93
94 function visiblePaths() {
95 const tree = container!.querySelector("file-tree-container");
96 if (!tree) return [];
97 return [...tree.shadowRoot!.querySelectorAll("[data-item-path]")].map((row) =>
98 row.getAttribute("data-item-path"),
99 );
100 }
101
102 function hasMessage(message: string) {
103 return [...container!.querySelectorAll("div")].some(
104 (node) => node.childNodes.length === 1 && node.textContent === message,
105 );
106 }
107
108 function expectVisibleLoadingStatus() {
109 const status = container!.querySelector<HTMLElement>('[role="status"]');
110 expect(status?.textContent).toBe("Loading files…");
111 expect(status!.checkVisibility()).toBe(true);
112 const bounds = status!.getBoundingClientRect();
113 expect(bounds.width).toBeGreaterThan(1);
114 expect(bounds.height).toBeGreaterThan(1);
115 }
116
117 function rowTop(path: string) {
118 const row = container!
119 .querySelector("file-tree-container")
120 ?.shadowRoot!.querySelector(`[data-item-path="${CSS.escape(path)}"]`);
121 expect(row, `visible row ${path}`).not.toBeNull();
122 const bounds = row!.getBoundingClientRect();
123 expect(bounds.height).toBeGreaterThan(0);
124 return bounds.top;
125 }
126
127 beforeEach(() => {
128 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
129 files.directoryEntries = [
130 { path: "src", kind: "directory" },
131 { path: "src/app.ts", kind: "file" },
132 { path: "package.json", kind: "file" },
133 ];
134 files.directoryReady = true;
135 files.directoryPending = false;
136 files.searchEntries = [];
137 files.searchPending = false;
138 files.searchError = null;
139 });
140
141 afterEach(async () => {
142 await act(async () => root?.unmount());
143 container?.remove();
144 root = undefined;
145 container = undefined;
146 vi.unstubAllGlobals();
147 });
148
149 it("keeps visible rows stationary during loading while showing initial loading status", async () => {
150 const entries = files.directoryEntries;
151 files.directoryEntries = [];
152 files.directoryReady = false;
153 files.directoryPending = true;
154 await render();
155 expect(visiblePaths()).toEqual([]);
156 expectVisibleLoadingStatus();
157
158 files.directoryEntries = entries;
159 files.directoryReady = true;
160 files.directoryPending = false;
161 await render();
162 expect(visiblePaths()).toEqual(["src/", "package.json"]);
163 const initialTop = rowTop("package.json");
164
165 files.directoryPending = true;
166 await render();
167 expect(rowTop("package.json")).toBe(initialTop);
168
169 files.directoryPending = false;
170 await search("pack");
171 expect(visiblePaths()).toEqual(["package.json"]);
172 const filteredTop = rowTop("package.json");
173
174 files.searchPending = true;
175 await search("package");
176 expect(visiblePaths()).toEqual(["package.json"]);
177 expect(rowTop("package.json")).toBe(filteredTop);
178
179 files.searchPending = false;
180 await render();
181 expect(rowTop("package.json")).toBe(filteredTop);
182 });
183
184 it("shows no matching files instead of the full tree when a filename is absent", async () => {
185 await render();
186 expect(visiblePaths()).toEqual(["src/", "package.json"]);
187
188 await search(".env.local");
189 expect(visiblePaths()).toEqual([]);
190 expect(hasMessage("No matching files.")).toBe(true);
191
192 await search("package");
193 expect(visiblePaths()).toEqual(["package.json"]);
194 expect(hasMessage("No matching files.")).toBe(false);
195
196 await search("");
197 expect(visiblePaths()).toEqual(["src/", "package.json"]);
198 });
199
200 it("still finds ignored files already loaded from a directory", async () => {
201 files.directoryEntries.push({ path: ".env.local", kind: "file", ignored: true });
202 await render();
203 await search(".env.local");
204 expect(visiblePaths()).toEqual([".env.local"]);
205 expect(hasMessage("No matching files.")).toBe(false);
206 });
207
208 it("waits for remote matches without showing unrelated files or a premature empty result", async () => {
209 await render();
210 files.searchPending = true;
211 await search("settings.ts");
212 expect(visiblePaths()).toEqual([]);
213 expectVisibleLoadingStatus();
214 expect(hasMessage("No matching files.")).toBe(false);
215
216 files.searchEntries = [{ path: "config/settings.ts", kind: "file" }];
217 files.searchPending = false;
218 await render();
219 expect(visiblePaths()).toEqual(["config/", "config/settings.ts"]);
220 expect(hasMessage("No matching files.")).toBe(false);
221 });
222
223 it("restores the tree on Escape after an unsuccessful search", async () => {
224 await render();
225 await search("missing-file");
226 expect(visiblePaths()).toEqual([]);
227
228 const input = searchInput();
229 input.focus();
230 await act(async () => {
231 input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
232 });
233 expect(document.activeElement).not.toBe(input);
234 expect(visiblePaths()).toEqual(["src/", "package.json"]);
235 expect(hasMessage("No matching files.")).toBe(false);
236 });
237
238 it("does not report an empty result when the search failed", async () => {
239 await render();
240 files.searchError = "Workspace search failed.";
241 await search("missing-file");
242 expect(visiblePaths()).toEqual([]);
243 expect(hasMessage("No matching files.")).toBe(false);
244 expect(container!.textContent).toContain("Workspace search failed.");
245 });
246
247 describe("expand all", () => {
248 const workspace: Record<string, ProjectEntry[]> = {
249 src: [
250 { path: "src/lib", kind: "directory" },
251 { path: "src/index.ts", kind: "file" },
252 ],
253 "src/lib": [{ path: "src/lib/util.ts", kind: "file" }],
254 node_modules: [
255 { path: "node_modules/react", kind: "directory", ignored: true },
256 { path: "node_modules/.modules.yaml", kind: "file", ignored: true },
257 ],
258 "node_modules/react": [{ path: "node_modules/react/index.js", kind: "file", ignored: true }],
259 };
260 const listed = () => files.load.mock.calls.map(([path]) => path);
261
262 // Answer each listing the panel asks for, as the server would, until it asks for no more.
263 async function answerListings() {
264 const answered = new Set<string>();
265 for (;;) {
266 const path = listed().find((requested) => !answered.has(requested));
267 if (path === undefined) return;
268 answered.add(path);
269 files.directoryEntries = [...files.directoryEntries, ...(workspace[path] ?? [])];
270 await render();
271 }
272 }
273
274 function button(label: "Expand all folders" | "Collapse all folders") {
275 const match = container!.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
276 expect(match, label).not.toBeNull();
277 return match!;
278 }
279
280 async function clickRow(path: string) {
281 const row = container!
282 .querySelector("file-tree-container")!
283 .shadowRoot!.querySelector<HTMLElement>(`[data-item-path="${path}"]`);
284 expect(row, path).not.toBeNull();
285 await act(async () => row!.click());
286 await answerListings();
287 }
288
289 beforeEach(() => {
290 files.load.mockClear();
291 files.directoryEntries = [
292 { path: "src", kind: "directory" },
293 { path: "node_modules", kind: "directory", ignored: true },
294 { path: "README.md", kind: "file" },
295 ];
296 });
297
298 it("opens every folder except ignored ones, which it never lists", async () => {
299 await render();
300 await act(async () => button("Expand all folders").click());
301 await answerListings();
302
303 expect(listed().toSorted()).toEqual(["src", "src/lib"]);
304 expect(visiblePaths()).toContain("src/lib/util.ts");
305 expect(visiblePaths()).not.toContain("node_modules/.modules.yaml");
306 button("Collapse all folders");
307
308 // Collapsing a folder by hand ends expand all; reopening it counts as all expanded again,
309 // with the ignored folder still closed.
310 await clickRow("src/lib/");
311 button("Expand all folders");
312 await clickRow("src/lib/");
313 button("Collapse all folders");
314 });
315
316 it("opens an ignored folder by hand without walking into it, and collapses it with the rest", async () => {
317 await render();
318 await act(async () => button("Expand all folders").click());
319 await answerListings();
320
321 await clickRow("node_modules/");
322 expect(listed()).toContain("node_modules");
323 expect(listed()).not.toContain("node_modules/react");
324 expect(visiblePaths()).toContain("node_modules/react/");
325 expect(visiblePaths()).not.toContain("node_modules/react/index.js");
326
327 await act(async () => button("Collapse all folders").click());
328 expect(visiblePaths()).toEqual(["node_modules/", "src/", "README.md"]);
329 });
330 });
331});