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

FileBrowserPanel.browser.test.tsx

186 lines6.4 KB

1import { EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
2import { act, type ReactNode } from "react";
3import { createRoot, type Root } from "react-dom/client";
4import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5​
6import FileBrowserPanel from "./FileBrowserPanel";
7​
8const files = vi.hoisted(() => ({
9 directoryEntries: [] as ProjectEntry[],
10 searchEntries: [] as ProjectEntry[],
11 searchPending: false,
12 searchError: null as string | null,
13 loadingDirectories: new Set<string>() as ReadonlySet<string>,
14 load: vi.fn(async () => {}),
15 refresh: vi.fn(),
16}));
17​
18vi.mock("./useDirectoryEntries", () => ({
19 useDirectoryEntries: () => ({
20 entries: files.directoryEntries,
21 loadingDirectories: files.loadingDirectories,
22 load: files.load,
23 refresh: files.refresh,
24 ready: true,
25 error: null,
26 isPending: false,
27 }),
28}));
29vi.mock("~/state/queries", () => ({
30 useProjectPathSearch: () => ({
31 entries: files.searchEntries,
32 isPending: files.searchPending,
33 error: files.searchError,
34 truncated: false,
35 refresh: files.refresh,
36 }),
37}));
38vi.mock("~/hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
39vi.mock("~/hooks/useWorkspaceMutationRefresh", () => ({ useWorkspaceMutationRefresh: vi.fn() }));
40vi.mock("~/composerHandleContext", () => ({ useComposerHandleContext: () => null }));
41vi.mock("~/fileContextMenu", () => ({ useFileContextMenu: () => ({}) }));
42vi.mock("~/localApi", () => ({ readLocalApi: () => undefined }));
43vi.mock("~/components/ui/toast", () => ({ toastManager: { add: vi.fn() } }));
44vi.mock("~/components/MorphIcon", () => ({ MorphIcon: () => null }));
45vi.mock("~/components/ui/tooltip", () => ({
46 Tooltip: ({ children }: { children: ReactNode }) => children,
47 TooltipTrigger: ({ render }: { render: ReactNode }) => render,
48 TooltipPopup: () => null,
49}));
50​
51describe("Files panel search", () => {
52 let root: Root | undefined;
53 let container: HTMLDivElement | undefined;
54 const props = {
55 environmentId: EnvironmentId.make("test-environment"),
56 cwd: "/workspace",
57 projectName: "Test project",
58 selectedPath: null,
59 selectedPathRevealId: 0,
60 onOpenFile: vi.fn(),
61 workspaceMutationId: null,
62 };
63​
64 async function render() {
65 if (!container) {
66 container = document.body.appendChild(document.createElement("div"));
67 // The tree virtualizes its rows, so it needs a real viewport to render any.
68 container.style.cssText =
69 "display: flex; flex-direction: column; width: 320px; height: 480px;";
70 root = createRoot(container);
71 }
72 await act(async () => root!.render(<FileBrowserPanel {...props} />));
73 }
74​
75 function searchInput() {
76 const input = container!.querySelector<HTMLInputElement>('input[type="search"]');
77 expect(input).not.toBeNull();
78 return input!;
79 }
80​
81 async function search(value: string) {
82 const input = searchInput();
83 // React tracks the last value it saw on the element, so set it through the native setter.
84 Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
85 await act(async () => {
86 input.dispatchEvent(new Event("input", { bubbles: true }));
87 });
88 }
89​
90 function visiblePaths() {
91 const tree = container!.querySelector("file-tree-container");
92 if (!tree) return [];
93 return [...tree.shadowRoot!.querySelectorAll("[data-item-path]")].map((row) =>
94 row.getAttribute("data-item-path"),
95 );
96 }
97​
98 function hasMessage(message: string) {
99 return [...container!.querySelectorAll("div")].some(
100 (node) => node.childNodes.length === 1 && node.textContent === message,
101 );
102 }
103​
104 beforeEach(() => {
105 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
106 files.directoryEntries = [
107 { path: "src", kind: "directory" },
108 { path: "src/app.ts", kind: "file" },
109 { path: "package.json", kind: "file" },
110 ];
111 files.searchEntries = [];
112 files.searchPending = false;
113 files.searchError = null;
114 });
115​
116 afterEach(async () => {
117 await act(async () => root?.unmount());
118 container?.remove();
119 root = undefined;
120 container = undefined;
121 vi.unstubAllGlobals();
122 });
123​
124 it("shows no matching files instead of the full tree when a filename is absent", async () => {
125 await render();
126 expect(visiblePaths()).toEqual(["src/", "package.json"]);
127​
128 await search(".env.local");
129 expect(visiblePaths()).toEqual([]);
130 expect(hasMessage("No matching files.")).toBe(true);
131​
132 await search("package");
133 expect(visiblePaths()).toEqual(["package.json"]);
134 expect(hasMessage("No matching files.")).toBe(false);
135​
136 await search("");
137 expect(visiblePaths()).toEqual(["src/", "package.json"]);
138 });
139​
140 it("still finds ignored files already loaded from a directory", async () => {
141 files.directoryEntries.push({ path: ".env.local", kind: "file", ignored: true });
142 await render();
143 await search(".env.local");
144 expect(visiblePaths()).toEqual([".env.local"]);
145 expect(hasMessage("No matching files.")).toBe(false);
146 });
147​
148 it("waits for remote matches without showing unrelated files or a premature empty result", async () => {
149 await render();
150 files.searchPending = true;
151 await search("settings.ts");
152 expect(visiblePaths()).toEqual([]);
153 expect(hasMessage("Loading files…")).toBe(true);
154 expect(hasMessage("No matching files.")).toBe(false);
155​
156 files.searchEntries = [{ path: "config/settings.ts", kind: "file" }];
157 files.searchPending = false;
158 await render();
159 expect(visiblePaths()).toEqual(["config/", "config/settings.ts"]);
160 expect(hasMessage("No matching files.")).toBe(false);
161 });
162​
163 it("restores the tree on Escape after an unsuccessful search", async () => {
164 await render();
165 await search("missing-file");
166 expect(visiblePaths()).toEqual([]);
167​
168 const input = searchInput();
169 input.focus();
170 await act(async () => {
171 input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
172 });
173 expect(document.activeElement).not.toBe(input);
174 expect(visiblePaths()).toEqual(["src/", "package.json"]);
175 expect(hasMessage("No matching files.")).toBe(false);
176 });
177​
178 it("does not report an empty result when the search failed", async () => {
179 await render();
180 files.searchError = "Workspace search failed.";
181 await search("missing-file");
182 expect(visiblePaths()).toEqual([]);
183 expect(hasMessage("No matching files.")).toBe(false);
184 expect(container!.textContent).toContain("Workspace search failed.");
185 });
186});