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