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

DiffPanel.browser.test.tsx

234 lines8.7 KB

1import "~/index.css";
2​
3import { RegistryContext, useAtomValue } from "@effect/atom-react";
4import { scopeThreadRef } from "@t3tools/client-runtime/environment";
5import {
6 EnvironmentId,
7 RunId,
8 ThreadId,
9 type ReviewDiffPreviewResult,
10 type ReviewDiffPreviewSource,
11} from "@t3tools/contracts";
12import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
13import * as DateTime from "effect/DateTime";
14import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
15import { act } from "react";
16import { createRoot, type Root } from "react-dom/client";
17import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
18import { page } from "vite-plus/test/browser";
19​
20vi.mock("../hooks/useThreadRouteTarget", () => ({
21 useThreadRouteRef: () => threadRef,
22 useThreadRouteTarget: () => ({ ...threadRef, kind: "thread" }),
23}));
24vi.mock("../state/entities", () => ({
25 useQuietThreadShell: () => thread,
26 useThreadCheckpointSummaries: () => turns,
27 useProject: () => null,
28}));
29vi.mock("../state/filesystem", () => ({ useFilesystemReadAccess: () => ({ canReadFiles: true }) }));
30vi.mock("../state/server", () => ({ serverEnvironment: { configValueAtom: () => configAtom } }));
31vi.mock("../state/vcs", () => ({ vcsEnvironment: { status: () => null, listRefs: () => null } }));
32vi.mock("../state/review", () => ({
33 reviewEnvironment: {
34 diffPreview: () => previewAtom,
35 diffFilePatch: ({ input }: { input: { request: { file: { path: string } } } }) =>
36 patchAtoms(input.request.file.path),
37 },
38}));
39vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
40vi.mock("../hooks/useSettings", () => ({
41 useClientSettings: () => ({
42 ...DEFAULT_CLIENT_SETTINGS,
43 diffFilesCollapsed: useAtomValue(collapsedAtom),
44 }),
45 updateClientSettings: vi.fn(),
46}));
47vi.mock("../hooks/useTheme", () => ({
48 useRenderedAppearance: () => "dark",
49 useTheme: () => ({ resolvedTheme: "dark" }),
50}));
51vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => vi.fn() }));
52vi.mock("../fileContextMenu", () => ({ useFileContextMenuHandler: () => vi.fn() }));
53vi.mock("../lib/checkpointDiffState", () => ({
54 useCheckpointDiff: () => {
55 const diff = useAtomValue(checkpointAtom);
56 return { data: diff === null ? null : { diff }, isPending: diff === null, error: null };
57 },
58}));
59​
60import DiffPanel from "./DiffPanel";
61import { useDiffPanelStore } from "../diffPanelStore";
62​
63const threadRef = scopeThreadRef(EnvironmentId.make("environment"), ThreadId.make("thread"));
64const thread = { ...threadRef, worktreePath: "/repo" };
65const turns = [1, 2].map((ordinal) => ({
66 runId: RunId.make(`turn-${ordinal}`),
67 checkpointTurnCount: ordinal,
68 completedAt: "2026-10-16T00:00:00Z",
69}));
70const paths = ["a.txt", "b.txt", "c.txt", "d.txt", "e.txt"];
71function filePatch(path: string) {
72 const count = path === "e.txt" ? 30 : 4;
73 const lines = Array.from({ length: count }, (_, index) => `+after ${index}`).join("\n");
74 return `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1,${count} @@\n-before\n${lines}\n`;
76const source: ReviewDiffPreviewSource = {
77 id: "branch",
78 kind: "branch-range",
79 title: "Changes",
80 baseRef: "main",
81 headRef: "HEAD",
82 diff: "",
83 diffHash: "branch-diff",
84 truncated: true,
85 files: paths.map((path) => ({
86 path,
87 previousPath: null,
88 additions: path === "e.txt" ? 30 : 4,
89 deletions: 1,
90 })),
91};
92const configAtom = Atom.make(null);
93const collapsedAtom = Atom.make(true);
94const checkpointAtom = Atom.make<string | null>(null);
95const previewAtom = Atom.make(
96 AsyncResult.success<ReviewDiffPreviewResult>({
97 cwd: "/repo",
98 generatedAt: DateTime.makeUnsafe("2026-10-16T00:00:00Z"),
99 sources: [source, { ...source, id: "working", kind: "working-tree" }],
100 }),
101);
102function loadedPatch(path: string): ReviewDiffPreviewSource {
103 return {
104 ...source,
105 diff: filePatch(path),
106 files: source.files?.filter((file) => file.path === path) ?? [],
107 truncated: false,
108 };
110const patchAtoms = Atom.family((path: string) =>
111 Atom.make<AsyncResult.AsyncResult<ReviewDiffPreviewSource>>(
112 path === "e.txt" ? AsyncResult.initial() : AsyncResult.success(loadedPatch(path)),
113 ),
114);
115let registry: AtomRegistry.AtomRegistry;
116let container: HTMLDivElement;
117let root: Root;
118​
119beforeEach(() => {
120 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
121 localStorage.setItem("t3code.diffFileTreeOpen", "true");
122 useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {} });
123 registry = AtomRegistry.make();
124 container = document.createElement("div");
125 container.style.cssText = "width: 1000px; height: 300px";
126 document.body.append(container);
127 root = createRoot(container);
128});
129afterEach(async () => {
130 await act(async () => root.unmount());
131 container.remove();
132 registry.dispose();
133 localStorage.clear();
134 vi.unstubAllGlobals();
135});
136async function render() {
137 await act(async () =>
138 root.render(
139 <RegistryContext.Provider value={registry}>
140 <DiffPanel
141 visible
142 mode="embedded"
143 composerDraftTarget={threadRef}
144 workspaceMutationId={null}
145 />
146 </RegistryContext.Provider>,
147 ),
148 );
150const toggle = (path: string, expanded: boolean) =>
151 page.getByRole("button", { name: `${expanded ? "Collapse" : "Expand"} ${path}`, exact: true });
152const viewport = () => container.querySelector<HTMLElement>(".diff-render-surface")!;
153async function selectTurn(path?: string, turn = turns[0]!) {
154 await act(async () => useDiffPanelStore.getState().selectTurn(threadRef, turn.runId, path));
156async function expectRevealed(path: string) {
157 await expect.element(toggle(path, true)).toBeInTheDocument();
158 await expect
159 .poll(() => {
160 const bounds = viewport().getBoundingClientRect();
161 const header = toggle(path, true).element().getBoundingClientRect();
162 return viewport().scrollTop > 0 && header.top >= bounds.top && header.bottom <= bounds.bottom;
163 })
164 .toBe(true);
166async function scrollToStart() {
167 await act(async () => {
168 viewport().scrollTop = 0;
169 viewport().dispatchEvent(new Event("scroll"));
170 await new Promise(requestAnimationFrame);
171 });
173async function selectTreeFile(path: string) {
174 const tree = container.querySelector("file-tree-container")!;
175 const row = tree.shadowRoot!.querySelector<HTMLElement>(`[data-item-path="${path}"]`)!;
176 await act(async () =>
177 row.dispatchEvent(
178 new MouseEvent("click", { bubbles: true, composed: true, button: 0, detail: 1 }),
179 ),
180 );
182​
183it("reveals a delayed turn selection, preserves siblings, and repeats after scope changes", async () => {
184 await selectTurn("e.txt");
185 await render();
186 await expect
187 .element(page.getByRole("status", { name: "Loading checkpoint diff..." }))
188 .toBeInTheDocument();
189 await act(async () => registry.set(checkpointAtom, paths.map(filePatch).join("")));
190 await expectRevealed("e.txt");
191 await act(async () => useDiffPanelStore.getState().selectGitScope(threadRef, "branch"));
192 await expect.element(toggle("a.txt", false)).toBeInTheDocument();
193 await selectTurn("e.txt");
194 await expectRevealed("e.txt");
195 await scrollToStart();
196 await toggle("a.txt", false).click();
197 await selectTurn("b.txt");
198 await expect.element(toggle("b.txt", true)).toBeInTheDocument();
199 await toggle("b.txt", true).click();
200 await selectTurn("e.txt");
201 await expectRevealed("e.txt");
202 await scrollToStart();
203 await expect.element(toggle("a.txt", true)).toBeInTheDocument();
204 await expect.element(toggle("b.txt", false)).toBeInTheDocument();
205 await expect.element(toggle("c.txt", false)).toBeInTheDocument();
206 await selectTurn("e.txt");
207 await expectRevealed("e.txt");
208​
209 await selectTurn(undefined, turns[1]!);
210 await expect.element(toggle("a.txt", false)).toBeInTheDocument();
211 await expect.element(toggle("e.txt", false)).toBeInTheDocument();
212});
213​
214it("waits for a lazy Git patch while preserving sibling choices and expanded defaults", async () => {
215 registry.set(collapsedAtom, false);
216 await render();
217 await toggle("b.txt", true).click();
218 await selectTreeFile("b.txt");
219 await expect.element(toggle("b.txt", true)).toBeInTheDocument();
220 await toggle("b.txt", true).click();
221 await scrollToStart();
222 await selectTreeFile("e.txt");
223 expect(viewport().scrollTop).toBe(0);
224 await expect.element(toggle("e.txt", true)).not.toBeInTheDocument();
225 await act(async () =>
226 registry.set(patchAtoms("e.txt"), AsyncResult.success(loadedPatch("e.txt"))),
227 );
228 await expectRevealed("e.txt");
229 await scrollToStart();
230 await expect.element(toggle("a.txt", true)).toBeInTheDocument();
231 await expect.element(toggle("b.txt", false)).toBeInTheDocument();
232 await act(async () => useDiffPanelStore.getState().selectGitScope(threadRef, "unstaged"));
233 await expect.element(toggle("b.txt", true)).toBeInTheDocument();
234});