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

DiffFileTree.browser.test.tsx

215 lines7.7 KB

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 }: {
46 files?: DiffFileTreeEntry[];
47 selectedPath?: string | null;
48 }) {
49 const reveal = useCodeViewFileReveal(viewer, "working-tree");
50 return (
51 <DiffFileTree
52 entries={files}
53 ariaLabel="Working tree files"
54 selectedPath={selectedPath}
55 onSelectFile={(path) => reveal(`${path}\0${path}`)}
56 />
57 );
58 }
59​
60 const model = (): FileTreeModel => captured.model as FileTreeModel;
61​
62 async function mount(props: Parameters<typeof Panel>[0] = {}) {
63 root ??= createRoot(container);
64 await act(async () => root!.render(<Panel {...props} />));
65 }
66​
67 function row(path: string): HTMLElement {
68 const host = container.querySelector("file-tree-container");
69 const element = (host?.shadowRoot ?? container).querySelector<HTMLElement>(
70 `[data-item-path="${CSS.escape(path)}"]`,
71 );
72 expect(element, `row ${path}`).not.toBeNull();
73 return element!;
74 }
75​
76 async function activate(path: string, modifiers: MouseEventInit = {}) {
77 await act(async () => {
78 row(path).dispatchEvent(
79 new MouseEvent("click", {
80 bubbles: true,
81 composed: true,
82 button: 0,
83 detail: 1,
84 ...modifiers,
85 }),
86 );
87 });
88 }
89​
90 beforeEach(() => {
91 targets.length = 0;
92 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
93 container = document.createElement("div");
94 container.style.cssText = "display: flex; flex-direction: column; width: 320px; height: 480px";
95 document.body.append(container);
96 });
97​
98 afterEach(async () => {
99 await act(async () => root?.unmount());
100 root = undefined;
101 container.remove();
102 vi.unstubAllGlobals();
103 });
104​
105 it("mounts a file-to-symlink type change as one tree row", async () => {
106 const typeChange = diffFileTreeEntries([
107 { type: "deleted", name: "AGENTS.md", prevName: "AGENTS.md" } as FileDiffMetadata,
108 { type: "new", name: "AGENTS.md", prevName: "AGENTS.md" } as FileDiffMetadata,
109 { type: "change", name: "CLAUDE.md", prevName: "CLAUDE.md" } as FileDiffMetadata,
110 ]);
111 await mount({ files: [...typeChange] });
112​
113 const tree = model();
114 expect(tree.getItem("AGENTS.md")?.isDirectory()).toBe(false);
115 expect(tree.getItem("CLAUDE.md")?.isDirectory()).toBe(false);
116 await activate("AGENTS.md");
117 expect(targets).toEqual([{ type: "item", id: "AGENTS.md\u0000AGENTS.md", align: "start" }]);
118 });
119​
120 it("reissues the reveal when the sole selected file is activated again", async () => {
121 await mount();
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 await mount();
133 await activate("02-short.ts");
134 await activate("01-tall.ts");
135 await activate("03-medium.ts");
136 expect(targets.map((target) => ("id" in target ? target.id : null))).toEqual(
137 ["02-short.ts", "01-tall.ts", "03-medium.ts"].map((path) => `${path}\0${path}`),
138 );
139 });
140​
141 it("keeps focus-only navigation separate from button activation", async () => {
142 await mount();
143 await activate("02-short.ts");
144 await act(async () => model().getItem("01-tall.ts")!.focus());
145 expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);
146 expect(targets).toHaveLength(1);
147 await activate("01-tall.ts", { detail: 0 });
148 await activate("01-tall.ts", { detail: 0 });
149 expect(targets).toHaveLength(3);
150 });
151​
152 it.each(["ctrlKey", "metaKey"] as const)(
153 "does not reveal a selected file that a %s click deselects",
154 async (modifier) => {
155 await mount();
156 await activate("02-short.ts");
157 await activate("02-short.ts", { [modifier]: true });
158 expect(model().getSelectedPaths()).toEqual([]);
159 expect(targets).toHaveLength(1);
160 },
161 );
162​
163 it("lets a click narrow multiple selected files without a second reveal", async () => {
164 await mount();
165 await activate("02-short.ts");
166 await act(async () => model().getItem("01-tall.ts")!.select());
167 expect(model().getSelectedPaths()).toHaveLength(2);
168 targets.length = 0;
169 await activate("02-short.ts");
170 expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);
171 expect(targets).toHaveLength(1);
172 });
173​
174 it("leaves directory selection and expansion to the tree", async () => {
175 await mount({ files: [{ path: "src/app.ts", status: "modified" }] });
176 const directory = model().getItem("src/")!;
177 if (!("isExpanded" in directory)) throw new Error("Expected the directory handle");
178 expect(directory.isExpanded()).toBe(true);
179 await activate("src/");
180 expect(directory.isExpanded()).toBe(false);
181 await activate("src/");
182 expect(directory.isExpanded()).toBe(true);
183 expect(targets).toEqual([]);
184 });
185​
186 it("reorders refreshed files without reopening a collapsed folder", async () => {
187 const files: DiffFileTreeEntry[] = [
188 { path: "src/state/shell.ts", status: "modified" },
189 { path: "src/features/route.ts", status: "added" },
190 ];
191 await mount({ files });
192 const initialFolder = model().getItem("src/features/")!;
193 if (!("collapse" in initialFolder)) throw new Error("Expected the directory handle");
194 await act(async () => initialFolder.collapse());
195 await act(async () => {
196 root!.render(<Panel files={[files[1]!, files[0]!]} />);
197 });
198 const folder = model().getItem("src/features/")!;
199 if (!("isExpanded" in folder)) throw new Error("Expected the directory handle");
200 expect(folder.isExpanded()).toBe(false);
201 });
202​
203 it("does not echo controlled selection, but lets the reader activate it", async () => {
204 await mount({ selectedPath: "02-short.ts" });
205 expect(model().getSelectedPaths()).toEqual(["02-short.ts"]);
206 expect(targets).toEqual([]);
207 await activate("02-short.ts");
208 expect(targets).toHaveLength(1);
209 await act(async () => {
210 root!.render(<Panel selectedPath="03-medium.ts" />);
211 });
212 expect(model().getSelectedPaths()).toEqual(["03-medium.ts"]);
213 expect(targets).toHaveLength(1);
214 });
215});