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

DiffFileTree.browser.test.tsx

347 lines13.9 KB

1import type { CodeViewScrollTarget } from "@pierre/diffs";
2import type { FileTree as FileTreeModel } from "@pierre/trees";
3import type { ComponentProps } from "react";
4import { describe, expect, it, vi } from "vite-plus/test";
5​
6import type { FileDiffMetadata } from "@pierre/diffs";
7​
8import { act, render } from "../../../test/render";
9​
10import { DiffFileTree, type DiffFileTreeEntry } from "./DiffFileTree";
11import { diffFileTreeEntries } from "./diffFileTree.logic";
12import { useCodeViewFileReveal } from "./useCodeViewFileReveal";
13​
14const captured = vi.hoisted(() => ({ model: null as unknown }));
15// Read the tree model the component builds, so tests can assert its selection and expansion.
16vi.mock(import("@pierre/trees/react"), async (original) => {
17 const actual = await original();
18 const RealFileTree = actual.FileTree;
19 return {
20 ...actual,
21 FileTree: ((props: ComponentProps<typeof RealFileTree>) => {
22 captured.model = props.model;
23 return <RealFileTree {...props} />;
24 }) as typeof RealFileTree,
25 };
26});
27​
28const entries: DiffFileTreeEntry[] = [
29 { path: "01-tall.ts", status: "modified" },
30 { path: "02-short.ts", status: "modified" },
31 { path: "03-medium.ts", status: "modified" },
32];
33​
34describe("diff tree file activation", () => {
35 let container: HTMLDivElement;
36 const targets: CodeViewScrollTarget[] = [];
37 const viewer = {
38 getInstance: () => viewer,
39 scrollTo: (target: CodeViewScrollTarget) => targets.push(target),
40 };
41​
42 function Panel({
43 files = entries,
44 selectedPath = null,
45 revealRequestId = 0,
46 }: {
47 files?: DiffFileTreeEntry[];
48 selectedPath?: string | null;
49 revealRequestId?: number;
50 }) {
51 const reveal = useCodeViewFileReveal(viewer, "working-tree");
52 return (
53 <DiffFileTree
54 entries={files}
55 ariaLabel="Working tree files"
56 selectedPath={selectedPath}
57 revealRequestId={revealRequestId}
58 onSelectFile={(path) => reveal(`${path}\0${path}`)}
59 />
60 );
61 }
62​
63 const model = (): FileTreeModel => captured.model as FileTreeModel;
64​
65 function setup() {
66 targets.length = 0;
67 container = document.createElement("div");
68 container.style.cssText = "display: flex; flex-direction: column; width: 320px; height: 480px";
69 }
70​
71 function row(path: string): HTMLElement {
72 const host = container.querySelector("file-tree-container");
73 const element = (host?.shadowRoot ?? container).querySelector<HTMLElement>(
74 `[data-item-path="${CSS.escape(path)}"]`,
75 );
76 expect(element, `row ${path}`).not.toBeNull();
77 return element!;
78 }
79​
80 function fileRows(): HTMLElement[] {
81 const host = container.querySelector("file-tree-container");
82 return [
83 ...(host?.shadowRoot ?? container).querySelectorAll<HTMLElement>(
84 '[role="treeitem"][data-item-type="file"]',
85 ),
86 ];
87 }
88​
89 async function activate(target: string | HTMLElement, modifiers: MouseEventInit = {}) {
90 await act(async () => {
91 (typeof target === "string" ? row(target) : target).dispatchEvent(
92 new MouseEvent("click", {
93 bubbles: true,
94 composed: true,
95 button: 0,
96 detail: 1,
97 ...modifiers,
98 }),
99 );
100 });
101 }
102​
103 it("mounts a file-to-symlink type change as one tree row", async () => {
104 setup();
105 const typeChange = diffFileTreeEntries([
106 { type: "deleted", name: "AGENTS.md", prevName: "AGENTS.md" } as FileDiffMetadata,
107 { type: "new", name: "AGENTS.md", prevName: "AGENTS.md" } as FileDiffMetadata,
108 { type: "change", name: "CLAUDE.md", prevName: "CLAUDE.md" } as FileDiffMetadata,
109 ]);
110 await using _screen = await render(<Panel files={[...typeChange]} />, { container });
111​
112 const tree = model();
113 expect(tree.getItem("AGENTS.md")?.isDirectory()).toBe(false);
114 expect(tree.getItem("CLAUDE.md")?.isDirectory()).toBe(false);
115 await activate("AGENTS.md");
116 expect(targets).toEqual([{ type: "item", id: "AGENTS.md\u0000AGENTS.md", align: "start" }]);
117 });
118​
119 it("reissues the reveal when the sole selected file is activated again", async () => {
120 setup();
121 await using _screen = await render(<Panel />, { container });
122 await activate("02-short.ts");
123 expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);
124 await activate("02-short.ts");
125 expect(targets).toEqual([
126 { type: "item", id: "02-short.ts\u000002-short.ts", align: "start" },
127 { type: "item", id: "02-short.ts\u000002-short.ts", align: "start" },
128 ]);
129 });
130​
131 it("reveals newly selected files once in either direction", async () => {
132 setup();
133 await using _screen = await render(<Panel />, { container });
134 await activate("02-short.ts");
135 await activate("01-tall.ts");
136 await activate("03-medium.ts");
137 expect(targets.map((target) => ("id" in target ? target.id : null))).toEqual(
138 ["02-short.ts", "01-tall.ts", "03-medium.ts"].map((path) => `${path}\0${path}`),
139 );
140 });
141​
142 it("keeps focus-only navigation separate from button activation", async () => {
143 setup();
144 await using _screen = await render(<Panel />, { container });
145 await activate("02-short.ts");
146 await act(async () => model().getItem("01-tall.ts")!.focus());
147 expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);
148 expect(targets).toHaveLength(1);
149 await activate("01-tall.ts", { detail: 0 });
150 await activate("01-tall.ts", { detail: 0 });
151 expect(targets).toHaveLength(3);
152 });
153​
154 it.each(["ctrlKey", "metaKey"] as const)(
155 "does not reveal a selected file that a %s click deselects",
156 async (modifier) => {
157 setup();
158 await using _screen = await render(<Panel />, { container });
159 await activate("02-short.ts");
160 await activate("02-short.ts", { [modifier]: true });
161 expect(model().getSelectedPaths()).toEqual([]);
162 expect(targets).toHaveLength(1);
163 },
164 );
165​
166 it("lets a click narrow multiple selected files without a second reveal", async () => {
167 setup();
168 await using _screen = await render(<Panel />, { container });
169 await activate("02-short.ts");
170 await act(async () => model().getItem("01-tall.ts")!.select());
171 expect(model().getSelectedPaths()).toHaveLength(2);
172 targets.length = 0;
173 await activate("02-short.ts");
174 expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);
175 expect(targets).toHaveLength(1);
176 });
177​
178 it("leaves directory selection and expansion to the tree", async () => {
179 setup();
180 await using _screen = await render(
181 <Panel files={[{ path: "src/app.ts", status: "modified" }]} />,
182 { container },
183 );
184 const directory = model().getItem("src/")!;
185 if (!("isExpanded" in directory)) throw new Error("Expected the directory handle");
186 expect(directory.isExpanded()).toBe(true);
187 await activate("src/");
188 expect(directory.isExpanded()).toBe(false);
189 await activate("src/");
190 expect(directory.isExpanded()).toBe(true);
191 expect(targets).toEqual([]);
192 });
193​
194 it("reorders refreshed files without reopening a collapsed folder", async () => {
195 setup();
196 const files: DiffFileTreeEntry[] = [
197 { path: "src/state/shell.ts", status: "modified" },
198 { path: "src/features/route.ts", status: "added" },
199 ];
200 await using screen = await render(<Panel files={files} />, { container });
201 const initialFolder = model().getItem("src/features/")!;
202 if (!("collapse" in initialFolder)) throw new Error("Expected the directory handle");
203 await act(async () => initialFolder.collapse());
204 await screen.rerender(<Panel files={[files[1]!, files[0]!]} />);
205 const folder = model().getItem("src/features/")!;
206 if (!("isExpanded" in folder)) throw new Error("Expected the directory handle");
207 expect(folder.isExpanded()).toBe(false);
208 });
209​
210 it("reveals real diff paths and statuses when a directory is replaced by a file", async () => {
211 setup();
212 const files: DiffFileTreeEntry[] = [
213 { path: "office/config.ts", status: "deleted" },
214 { path: "office", status: "added" },
215 ];
216 await using screen = await render(<Panel files={files} selectedPath="office" />, { container });
217 expect(fileRows().map((row) => row.getAttribute("data-item-git-status"))).toEqual([
218 "deleted",
219 "added",
220 ]);
221 expect(fileRows()[1]!.getAttribute("aria-selected")).toBe("true");
222 expect(targets).toEqual([]);
223 await activate(fileRows()[1]!);
224 await activate(fileRows()[0]!);
225 await activate("office/");
226 expect(targets).toEqual([
227 { type: "item", id: "office\0office", align: "start" },
228 { type: "item", id: "office/config.ts\0office/config.ts", align: "start" },
229 ]);
230 expect(row("office/").getAttribute("aria-expanded")).toBe("false");
231 await screen.rerender(<Panel files={files} selectedPath="office/config.ts" />);
232 expect(row("office/").getAttribute("aria-expanded")).toBe("true");
233 expect(fileRows()[0]!.getAttribute("aria-selected")).toBe("true");
234 expect(targets).toHaveLength(2);
235 });
236​
237 it("keeps selection, focus, and collapsed folders through a colliding slice and refresh", async () => {
238 setup();
239 const files: DiffFileTreeEntry[] = [
240 { path: "office", status: "deleted" },
241 { path: "src/route.ts", status: "modified" },
242 ];
243 await using screen = await render(<Panel files={files} />, { container });
244 await activate("src/");
245 await activate("office");
246 await act(async () => model().focusPath("office"));
247 expect(model().getFocusedPath()).toBe("office");
248 expect(row("office").getAttribute("aria-selected")).toBe("true");
249 const appended: DiffFileTreeEntry[] = [...files, { path: "office/config.ts", status: "added" }];
250 await screen.rerender(<Panel files={appended} />);
251 expect(row("src/").getAttribute("aria-expanded")).toBe("false");
252 expect(fileRows()[0]!.getAttribute("aria-selected")).toBe("true");
253 expect(row("office/").getAttribute("aria-selected")).toBe("false");
254 expect.soft(model().getFocusedPath()).toBe("office\u200b");
255 expect(targets).toEqual([{ type: "item", id: "office\0office", align: "start" }]);
256 await activate(fileRows()[0]!);
257 await activate(fileRows()[1]!);
258 expect(targets).toEqual([
259 { type: "item", id: "office\0office", align: "start" },
260 { type: "item", id: "office\0office", align: "start" },
261 { type: "item", id: "office/config.ts\0office/config.ts", align: "start" },
262 ]);
263 await activate("office/");
264 await screen.rerender(<Panel files={appended.map((file) => ({ ...file }))} />);
265 expect(row("src/").getAttribute("aria-expanded")).toBe("false");
266 expect(row("office/").getAttribute("aria-expanded")).toBe("false");
267 await activate(fileRows()[0]!);
268 expect(targets.at(-1)).toEqual({ type: "item", id: "office\0office", align: "start" });
269 expect(targets).toHaveLength(4);
270 });
271​
272 it("preserves filename and extension icons when files become directory prefixes", async () => {
273 setup();
274 const files: DiffFileTreeEntry[] = [
275 { path: "AGENTS.md", status: "deleted" },
276 { path: "config.ts", status: "deleted" },
277 ];
278 const rootFileIcons = () =>
279 fileRows()
280 .filter((row) => row.getAttribute("aria-level") === "1")
281 .map((row) => row.querySelector('[data-item-section="icon"] use')?.getAttribute("href"));
282 await using screen = await render(<Panel files={files} />, { container });
283 const icons = rootFileIcons();
284 expect(icons).toEqual(["#t3-file-icon-agents", "#file-tree-builtin-typescript"]);
285 await screen.rerender(
286 <Panel
287 files={[
288 ...files,
289 { path: "AGENTS.md/note.txt", status: "added" },
290 { path: "config.ts/note.txt", status: "added" },
291 ]}
292 />,
293 );
294 expect(rootFileIcons()).toEqual(icons);
295 });
296​
297 it("preserves a collapsed controlled selection through paging until explicitly revealed", async () => {
298 setup();
299 const files: DiffFileTreeEntry[] = [
300 { path: "src/office", status: "deleted" },
301 { path: "src/route.ts", status: "modified" },
302 ];
303 await using screen = await render(<Panel files={files} selectedPath="src/office" />, {
304 container,
305 });
306 expect(model().getSelectedPaths()).toEqual(["src/office"]);
307 expect(targets).toEqual([]);
308 await activate("src/office");
309 expect(targets).toEqual([{ type: "item", id: "src/office\0src/office", align: "start" }]);
310​
311 const folder = model().getItem("src/")!;
312 if (!("collapse" in folder)) throw new Error("Expected the directory handle");
313 await act(async () => folder.collapse());
314 expect(row("src/").getAttribute("aria-expanded")).toBe("false");
315 using scroll = vi.spyOn(model(), "scrollToPath");
316 const appended: DiffFileTreeEntry[] = [...files, { path: "src/office/x.ts", status: "added" }];
317 await screen.rerender(<Panel files={appended} selectedPath="src/office" />);
318 expect.soft(row("src/").getAttribute("aria-expanded")).toBe("false");
319 expect.soft(scroll).not.toHaveBeenCalled();
320 const selected = model().getSelectedPaths();
321 expect(selected).toHaveLength(1);
322 expect(model().getItem(selected[0]!)?.isDirectory()).toBe(false);
323 expect(targets).toHaveLength(1);
324​
325 await act(async () => folder.collapse());
326 scroll.mockClear();
327 await screen.rerender(<Panel files={appended} selectedPath="src/office" revealRequestId={1} />);
328 expect(row("src/").getAttribute("aria-expanded")).toBe("true");
329 expect(model().getSelectedPaths()).toEqual(selected);
330 expect(row(selected[0]!).getAttribute("aria-selected")).toBe("true");
331 expect(scroll).toHaveBeenCalledOnce();
332 expect(targets).toHaveLength(1);
333 await activate(selected[0]!);
334 expect(targets).toEqual([
335 { type: "item", id: "src/office\0src/office", align: "start" },
336 { type: "item", id: "src/office\0src/office", align: "start" },
337 ]);
338​
339 await act(async () => folder.collapse());
340 await screen.rerender(
341 <Panel files={appended} selectedPath="src/route.ts" revealRequestId={1} />,
342 );
343 expect(row("src/").getAttribute("aria-expanded")).toBe("true");
344 expect(model().getSelectedPaths()).toEqual(["src/route.ts"]);
345 expect(targets).toHaveLength(2);
346 });
347});