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

openPullRequestLink.browser.test.tsx

387 lines14.0 KB

1import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
2import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
3import { AsyncResult } from "effect/reactivity";
4import { expect, it, vi } from "vite-plus/test";
5import { page } from "vite-plus/test/browser";
6​
7import { act, render, stubGlobal } from "../../test/render";
8​
9const state = vi.hoisted(() => ({
10 preview: vi.fn(),
11 openLink: vi.fn(),
12 projects: undefined as ReadonlyArray<unknown> | undefined,
13 threadShells: undefined as
14 | Readonly<Record<string, { projectId: string; worktreePath: string | null }>>
15 | undefined,
16}));
17vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.preview }));
18vi.mock("../browser/useOpenLink", () => ({ useOpenLink: () => state.openLink }));
19vi.mock(import("../state/environments"), async (original) => ({
20 ...(await original()),
21 usePrimaryEnvironmentId: () => EnvironmentId.make("local"),
22}));
23vi.mock("../state/entities", async (original) => ({
24 ...(await original<typeof import("../state/entities")>()),
25 readProjects: () => state.projects ?? [project],
26 useProjects: () => [project],
27 readProject: () => project,
28 readThreadShell: (ref: ScopedThreadRef) =>
29 state.threadShells?.[scopedThreadKey(ref)] ?? { projectId: "project", worktreePath: null },
30}));
31vi.mock("../state/server", async (original) => {
32 const { Atom } = await import("effect/reactivity");
33 return {
34 ...(await original<typeof import("../state/server")>()),
35 environmentServerConfigsAtom: Atom.make(new Map([["local", {}]])),
36 };
37});
38​
39import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
40import { __setClientSettingsForTests } from "../hooks/useSettings";
41import { ToastProvider } from "../components/ui/toast";
42import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
43import { hostRightPanel, ISSUES_PANEL_REF, useRightPanelStore } from "../rightPanelStore";
44import { useDiffPanelStore } from "../diffPanelStore";
45import {
46 startDeferredChangeRequestLinkOpen,
47 useOpenChangeRequestLink,
48} from "./openPullRequestLink";
49​
50const environmentId = EnvironmentId.make("local");
51const threadRef = scopeThreadRef(environmentId, ThreadId.make("thread"));
52const project = {
53 id: "project",
54 environmentId,
55 workspaceRoot: "/repo",
56 repositoryIdentity: {
57 provider: "github",
58 canonicalKey: "github.com/effect-ts/effect",
59 displayName: "Effect-TS/effect",
60 locator: {
61 source: "git-remote",
62 remoteName: "origin",
63 remoteUrl: "https://github.com/Effect-TS/effect.git",
64 },
65 },
66};
67const commitUrl = `https://github.com/Effect-TS/effect/commit/${"a".repeat(40)}?plain=1#diff-original`;
68const pullRequestUrl = "https://github.com/Effect-TS/effect/pull/86";
69const pullRequestCommitUrl = `https://github.com/Effect-TS/effect/pull/1/commits/${"a".repeat(40)}`;
70​
71function CommitLink({
72 url = commitUrl,
73 targetRef = threadRef,
74}: {
75 url?: string;
76 targetRef?: ScopedThreadRef;
77}) {
78 const open = useOpenChangeRequestLink(targetRef);
79 return (
80 <a href={url} onClick={(event) => open(event, url)}>
81 Commit
82 </a>
83 );
85​
86function IssuesPagePullRequestLink() {
87 const open = useOpenChangeRequestLink(undefined, ISSUES_PANEL_REF);
88 return (
89 <a
90 href={pullRequestUrl}
91 onClick={(event) => open(event, pullRequestUrl, undefined, environmentId)}
92 >
93 Pull request
94 </a>
95 );
97​
98function ThreadPullRequestLink() {
99 const open = useOpenChangeRequestLink(threadRef);
100 return (
101 <a href={pullRequestUrl} onClick={(event) => open(event, pullRequestUrl)}>
102 Pull request
103 </a>
104 );
106​
107function DeferredThreadLink({
108 label,
109 onStart,
110}: {
111 label: string;
112 onStart: (isCurrent: () => boolean) => void;
113}) {
114 return (
115 <button onClick={() => onStart(startDeferredChangeRequestLinkOpen(threadRef))}>{label}</button>
116 );
118​
119function setup() {
120 state.projects = undefined;
121 state.threadShells = undefined;
122 state.preview.mockReset().mockResolvedValue(AsyncResult.success({ sources: [] }));
123 state.openLink.mockReset().mockResolvedValue(undefined);
124 __setClientSettingsForTests({
125 ...DEFAULT_CLIENT_SETTINGS,
126 pullRequestLinksOpenInApp: true,
127 browserLinkTarget: "system",
128 });
129 useDiffPanelStore.setState({
130 byThreadKey: {},
131 branchBaseRefByThreadKey: {},
132 });
133 useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });
135​
136it.each([
137 ["shiftKey", commitUrl],
138 ["altKey", commitUrl],
139 ["shiftKey", pullRequestCommitUrl],
140 ["shiftKey", `${pullRequestCommitUrl}#diff-abcR5`],
141 ["altKey", `${pullRequestCommitUrl}#diff-abcR5`],
142 ["shiftKey", pullRequestUrl],
143 ["altKey", pullRequestUrl],
144] as const)("keeps %s clicks on %s native", async (modifier, url) => {
145 setup();
146 await using screen = await render(
147 <AppAtomRegistryProvider>
148 <CommitLink url={url} />
149 </AppAtomRegistryProvider>,
150 );
151 const event = new MouseEvent("click", { bubbles: true, cancelable: true, [modifier]: true });
152 const defaults: boolean[] = [];
153 screen.container.addEventListener(
154 "click",
155 (nativeEvent) => {
156 defaults.push(nativeEvent.defaultPrevented);
157 nativeEvent.preventDefault();
158 },
159 { once: true },
160 );
161 await act(() => screen.getByRole("link", { name: "Commit" }).element().dispatchEvent(event));
162 expect(defaults).toEqual([false]);
163 expect(state.preview).not.toHaveBeenCalled();
164 expect(useRightPanelStore.getState().byThreadKey).toEqual({});
165});
166​
167it.each(["system", "app"] as const)(
168 "offers the original unavailable commit URL when web popups are blocked (%s)",
169 async (browserLinkTarget) => {
170 setup();
171 // Without preview access, the "app" preference opens a popup too.
172 __setClientSettingsForTests({
173 ...DEFAULT_CLIENT_SETTINGS,
174 pullRequestLinksOpenInApp: true,
175 browserLinkTarget,
176 });
177 using _desktop = stubGlobal("desktopBridge", undefined);
178 await using screen = await render(
179 <AppAtomRegistryProvider>
180 <ToastProvider>
181 <CommitLink />
182 </ToastProvider>
183 </AppAtomRegistryProvider>,
184 );
185 using open = vi.spyOn(window, "open").mockReturnValue(null);
186 await screen.getByRole("link", { name: "Commit" }).click();
187 await expect
188 .element(page.getByRole("button", { name: "Open link", exact: true }))
189 .toBeVisible();
190 expect(open).not.toHaveBeenCalled();
191 await page.getByRole("button", { name: "Open link", exact: true }).click();
192 expect(open).toHaveBeenCalledExactlyOnceWith(commitUrl, "_blank", "noopener,noreferrer");
193 expect(state.openLink).not.toHaveBeenCalled();
194 },
195);
196​
197it("opens an available commit in the closed Diff pane without the pane resetting it", async () => {
198 setup();
199 const sha = "a".repeat(40);
200 state.preview.mockResolvedValue(
201 AsyncResult.success({ sources: [{ kind: "commit", headRef: sha }] }),
202 );
203 await using screen = await render(
204 <AppAtomRegistryProvider>
205 <CommitLink />
206 </AppAtomRegistryProvider>,
207 );
208 await screen.getByRole("link", { name: "Commit" }).click();
209 await vi.waitFor(() =>
210 expect(useDiffPanelStore.getState().byThreadKey).toEqual({
211 [scopedThreadKey(threadRef)]: { kind: "commit", sha, baseRef: null },
212 }),
213 );
214});
215​
216it("opens a pull request linked on the Issues page beside its issues", async () => {
217 setup();
218 await using screen = await render(
219 <AppAtomRegistryProvider>
220 <IssuesPagePullRequestLink />
221 </AppAtomRegistryProvider>,
222 { router: "/issues" },
223 );
224 await screen.getByRole("link", { name: "Pull request" }).click();
225 expect(
226 useRightPanelStore.getState().byThreadKey[scopedThreadKey(ISSUES_PANEL_REF)],
227 ).toMatchObject({ isOpen: true, surfaces: [{ kind: "pull-request", number: 86 }] });
228 expect(screen.router?.state.location.pathname).toBe("/issues");
229});
230​
231it("opens a thread's pull request beside it when its project is a folder with no remote", async () => {
232 setup();
233 state.projects = [{ ...project, repositoryIdentity: null }];
234 await using screen = await render(
235 <AppAtomRegistryProvider>
236 <ThreadPullRequestLink />
237 </AppAtomRegistryProvider>,
238 );
239 await screen.getByRole("link", { name: "Pull request" }).click();
240 expect(useRightPanelStore.getState().byThreadKey[scopedThreadKey(threadRef)]).toMatchObject({
241 isOpen: true,
242 surfaces: [{ kind: "pull-request", projectId: "project", number: 86 }],
243 });
244 expect(state.openLink).not.toHaveBeenCalled();
245});
246​
247it.each([
248 ["nothing else happens", async () => {}, true],
249 [
250 "a newer slow link starts",
251 () => page.getByRole("button", { name: "Newer slow reference" }).click(),
252 false,
253 ],
254 ["a newer pull request link opens", () => page.getByRole("link").click(), false],
255 ["the panel closes", () => act(() => useRightPanelStore.getState().close(threadRef)), false],
256] as const)("lets a slow link open only when %s", async (_case, newer, expected) => {
257 setup();
258 let isCurrent = () => true;
259 await using screen = await render(
260 <AppAtomRegistryProvider>
261 <DeferredThreadLink label="Slow reference" onStart={(check) => (isCurrent = check)} />
262 <DeferredThreadLink label="Newer slow reference" onStart={() => {}} />
263 <ThreadPullRequestLink />
264 </AppAtomRegistryProvider>,
265 );
266 await screen.getByRole("button", { name: "Slow reference", exact: true }).click();
267 await newer();
268 expect(isCurrent()).toBe(expected);
269});
270​
271it("lets a slow link clicked after a slow commit link open when the commit resolves first", async () => {
272 setup();
273 const commitLookup = Promise.withResolvers<unknown>();
274 state.preview.mockReturnValue(commitLookup.promise);
275 let isCurrent = () => false;
276 await using screen = await render(
277 <AppAtomRegistryProvider>
278 <CommitLink />
279 <DeferredThreadLink label="Slow reference" onStart={(check) => (isCurrent = check)} />
280 </AppAtomRegistryProvider>,
281 );
282 await screen.getByRole("link", { name: "Commit" }).click();
283 await screen.getByRole("button", { name: "Slow reference" }).click();
284 await act(async () =>
285 commitLookup.resolve(
286 AsyncResult.success({ sources: [{ kind: "commit", headRef: "a".repeat(40) }] }),
287 ),
288 );
289 expect(useDiffPanelStore.getState().byThreadKey).toEqual({});
290 expect(isCurrent()).toBe(true);
291});
292​
293it("drops a slow commit link once the user leaves its thread, even after returning", async () => {
294 setup();
295 const commitLookup = Promise.withResolvers<unknown>();
296 state.preview.mockReturnValue(commitLookup.promise);
297 await using screen = await render(
298 <AppAtomRegistryProvider>
299 <CommitLink />
300 </AppAtomRegistryProvider>,
301 { router: "/local/thread" },
302 );
303 await screen.getByRole("link", { name: "Commit" }).click();
304 expect(state.preview).toHaveBeenCalledOnce();
305 await act(() => screen.router?.history.push("/local/another-thread"));
306 await act(() => screen.router?.history.push("/local/thread"));
307 await act(async () =>
308 commitLookup.resolve(
309 AsyncResult.success({ sources: [{ kind: "commit", headRef: "a".repeat(40) }] }),
310 ),
311 );
312 expect(useDiffPanelStore.getState().byThreadKey).toEqual({});
313 expect(useRightPanelStore.getState().byThreadKey).toEqual({});
314});
315​
316it("opens a hosted side chat's commit link in its host workspace and Diff pane", async () => {
317 setup();
318 const sha = "a".repeat(40);
319 const hostRef = scopeThreadRef(environmentId, ThreadId.make("host-thread"));
320 const sideChatRef = scopeThreadRef(environmentId, ThreadId.make("side-chat"));
321 state.threadShells = {
322 [scopedThreadKey(hostRef)]: { projectId: "project", worktreePath: "/host-worktree" },
323 [scopedThreadKey(sideChatRef)]: { projectId: "project", worktreePath: "/side-worktree" },
324 };
325 state.preview.mockResolvedValue(
326 AsyncResult.success({ sources: [{ kind: "commit", headRef: sha }] }),
327 );
328 using _hosted = { [Symbol.dispose]: hostRightPanel(sideChatRef, hostRef) };
329 await using screen = await render(
330 <AppAtomRegistryProvider>
331 <CommitLink targetRef={sideChatRef} />
332 </AppAtomRegistryProvider>,
333 );
334 await screen.getByRole("link", { name: "Commit" }).click();
335 await vi.waitFor(() =>
336 expect(useDiffPanelStore.getState().byThreadKey).toEqual({
337 [scopedThreadKey(hostRef)]: { kind: "commit", sha, baseRef: null },
338 }),
339 );
340 expect(state.preview).toHaveBeenCalledWith({
341 environmentId,
342 input: expect.objectContaining({ cwd: "/host-worktree", commitSha: sha }),
343 });
344 expect(useRightPanelStore.getState().byThreadKey[scopedThreadKey(hostRef)]).toMatchObject({
345 isOpen: true,
346 activeSurfaceId: "diff",
347 });
348 expect(useRightPanelStore.getState().byThreadKey[scopedThreadKey(sideChatRef)]).toBeUndefined();
349});
350​
351it.each([
352 [
353 "the host panel switches tabs",
354 ({ hostRef }: { hostRef: ScopedThreadRef }) =>
355 act(() => useRightPanelStore.getState().open(hostRef, "files")),
356 "files",
357 ],
358 ["the side chat is unhosted", ({ unhost }: { unhost: () => void }) => unhost(), null],
359] as const)(
360 "drops a slow side-chat commit link when %s",
361 async (_case, interrupt, expectedActiveSurfaceId) => {
362 setup();
363 const sha = "a".repeat(40);
364 const hostRef = scopeThreadRef(environmentId, ThreadId.make("host-thread"));
365 const sideChatRef = scopeThreadRef(environmentId, ThreadId.make("side-chat"));
366 const commitLookup = Promise.withResolvers<unknown>();
367 state.preview.mockReturnValue(commitLookup.promise);
368 const unhost = hostRightPanel(sideChatRef, hostRef);
369 using _hosted = { [Symbol.dispose]: unhost };
370 await using screen = await render(
371 <AppAtomRegistryProvider>
372 <CommitLink targetRef={sideChatRef} />
373 </AppAtomRegistryProvider>,
374 );
375 await screen.getByRole("link", { name: "Commit" }).click();
376 expect(state.preview).toHaveBeenCalledOnce();
377 await interrupt({ hostRef, unhost });
378 await act(async () =>
379 commitLookup.resolve(AsyncResult.success({ sources: [{ kind: "commit", headRef: sha }] })),
380 );
381 expect(useDiffPanelStore.getState().byThreadKey).toEqual({});
382 expect(
383 useRightPanelStore.getState().byThreadKey[scopedThreadKey(hostRef)]?.activeSurfaceId ?? null,
384 ).toBe(expectedActiveSurfaceId);
385 expect(useRightPanelStore.getState().byThreadKey[scopedThreadKey(sideChatRef)]).toBeUndefined();
386 },
387);