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

openPullRequestLink.browser.test.tsx

303 lines10.6 KB

1import { EnvironmentId, ThreadId } 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}));
14vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.preview }));
15vi.mock("../browser/useOpenLink", () => ({ useOpenLink: () => state.openLink }));
16vi.mock(import("../state/environments"), async (original) => ({
17 ...(await original()),
18 usePrimaryEnvironmentId: () => EnvironmentId.make("local"),
19}));
20vi.mock("../state/entities", async (original) => ({
21 ...(await original<typeof import("../state/entities")>()),
22 readProjects: () => state.projects ?? [project],
23 useProjects: () => [project],
24 readProject: () => project,
25 readThreadShell: () => ({ projectId: "project", worktreePath: null }),
26}));
27vi.mock("../state/server", async (original) => {
28 const { Atom } = await import("effect/reactivity");
29 return {
30 ...(await original<typeof import("../state/server")>()),
31 environmentServerConfigsAtom: Atom.make(new Map([["local", {}]])),
32 };
33});
34​
35import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
36import { __setClientSettingsForTests } from "../hooks/useSettings";
37import { ToastProvider } from "../components/ui/toast";
38import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
39import { ISSUES_PANEL_REF, useRightPanelStore } from "../rightPanelStore";
40import { useDiffPanelStore } from "../diffPanelStore";
41import {
42 startDeferredChangeRequestLinkOpen,
43 useOpenChangeRequestLink,
44} from "./openPullRequestLink";
45​
46const environmentId = EnvironmentId.make("local");
47const threadRef = scopeThreadRef(environmentId, ThreadId.make("thread"));
48const project = {
49 id: "project",
50 environmentId,
51 workspaceRoot: "/repo",
52 repositoryIdentity: {
53 provider: "github",
54 canonicalKey: "github.com/effect-ts/effect",
55 displayName: "Effect-TS/effect",
56 locator: {
57 source: "git-remote",
58 remoteName: "origin",
59 remoteUrl: "https://github.com/Effect-TS/effect.git",
60 },
61 },
62};
63const commitUrl = `https://github.com/Effect-TS/effect/commit/${"a".repeat(40)}?plain=1#diff-original`;
64const pullRequestUrl = "https://github.com/Effect-TS/effect/pull/86";
65const pullRequestCommitUrl = `https://github.com/Effect-TS/effect/pull/1/commits/${"a".repeat(40)}`;
66​
67function CommitLink({ url = commitUrl }: { url?: string }) {
68 const open = useOpenChangeRequestLink(threadRef);
69 return (
70 <a href={url} onClick={(event) => open(event, url)}>
71 Commit
72 </a>
73 );
75​
76function IssuesPagePullRequestLink() {
77 const open = useOpenChangeRequestLink(undefined, ISSUES_PANEL_REF);
78 return (
79 <a
80 href={pullRequestUrl}
81 onClick={(event) => open(event, pullRequestUrl, undefined, environmentId)}
82 >
83 Pull request
84 </a>
85 );
87​
88function ThreadPullRequestLink() {
89 const open = useOpenChangeRequestLink(threadRef);
90 return (
91 <a href={pullRequestUrl} onClick={(event) => open(event, pullRequestUrl)}>
92 Pull request
93 </a>
94 );
96​
97function DeferredThreadLink({
98 label,
99 onStart,
100}: {
101 label: string;
102 onStart: (isCurrent: () => boolean) => void;
103}) {
104 return (
105 <button onClick={() => onStart(startDeferredChangeRequestLinkOpen(threadRef))}>{label}</button>
106 );
108​
109function setup() {
110 state.projects = undefined;
111 state.preview.mockReset().mockResolvedValue(AsyncResult.success({ sources: [] }));
112 state.openLink.mockReset().mockResolvedValue(undefined);
113 __setClientSettingsForTests({
114 ...DEFAULT_CLIENT_SETTINGS,
115 pullRequestLinksOpenInApp: true,
116 browserLinkTarget: "system",
117 });
118 useDiffPanelStore.setState({
119 byThreadKey: {},
120 branchBaseRefByThreadKey: {},
121 });
122 useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });
124​
125it.each([
126 ["shiftKey", commitUrl],
127 ["altKey", commitUrl],
128 ["shiftKey", pullRequestCommitUrl],
129 ["shiftKey", `${pullRequestCommitUrl}#diff-abcR5`],
130 ["altKey", `${pullRequestCommitUrl}#diff-abcR5`],
131 ["shiftKey", pullRequestUrl],
132 ["altKey", pullRequestUrl],
133] as const)("keeps %s clicks on %s native", async (modifier, url) => {
134 setup();
135 await using screen = await render(
136 <AppAtomRegistryProvider>
137 <CommitLink url={url} />
138 </AppAtomRegistryProvider>,
139 );
140 const event = new MouseEvent("click", { bubbles: true, cancelable: true, [modifier]: true });
141 const defaults: boolean[] = [];
142 screen.container.addEventListener(
143 "click",
144 (nativeEvent) => {
145 defaults.push(nativeEvent.defaultPrevented);
146 nativeEvent.preventDefault();
147 },
148 { once: true },
149 );
150 await act(() => screen.getByRole("link", { name: "Commit" }).element().dispatchEvent(event));
151 expect(defaults).toEqual([false]);
152 expect(state.preview).not.toHaveBeenCalled();
153 expect(useRightPanelStore.getState().byThreadKey).toEqual({});
154});
155​
156it.each(["system", "app"] as const)(
157 "offers the original unavailable commit URL when web popups are blocked (%s)",
158 async (browserLinkTarget) => {
159 setup();
160 // Without preview access, the "app" preference opens a popup too.
161 __setClientSettingsForTests({
162 ...DEFAULT_CLIENT_SETTINGS,
163 pullRequestLinksOpenInApp: true,
164 browserLinkTarget,
165 });
166 using _desktop = stubGlobal("desktopBridge", undefined);
167 await using screen = await render(
168 <AppAtomRegistryProvider>
169 <ToastProvider>
170 <CommitLink />
171 </ToastProvider>
172 </AppAtomRegistryProvider>,
173 );
174 using open = vi.spyOn(window, "open").mockReturnValue(null);
175 await screen.getByRole("link", { name: "Commit" }).click();
176 await expect
177 .element(page.getByRole("button", { name: "Open link", exact: true }))
178 .toBeVisible();
179 expect(open).not.toHaveBeenCalled();
180 await page.getByRole("button", { name: "Open link", exact: true }).click();
181 expect(open).toHaveBeenCalledExactlyOnceWith(commitUrl, "_blank", "noopener,noreferrer");
182 expect(state.openLink).not.toHaveBeenCalled();
183 },
184);
185​
186it("opens an available commit in the closed Diff pane without the pane resetting it", async () => {
187 setup();
188 const sha = "a".repeat(40);
189 state.preview.mockResolvedValue(
190 AsyncResult.success({ sources: [{ kind: "commit", headRef: sha }] }),
191 );
192 await using screen = await render(
193 <AppAtomRegistryProvider>
194 <CommitLink />
195 </AppAtomRegistryProvider>,
196 );
197 await screen.getByRole("link", { name: "Commit" }).click();
198 await vi.waitFor(() =>
199 expect(useDiffPanelStore.getState().byThreadKey).toEqual({
200 [scopedThreadKey(threadRef)]: { kind: "commit", sha, baseRef: null },
201 }),
202 );
203});
204​
205it("opens a pull request linked on the Issues page beside its issues", async () => {
206 setup();
207 await using screen = await render(
208 <AppAtomRegistryProvider>
209 <IssuesPagePullRequestLink />
210 </AppAtomRegistryProvider>,
211 { router: "/issues" },
212 );
213 await screen.getByRole("link", { name: "Pull request" }).click();
214 expect(
215 useRightPanelStore.getState().byThreadKey[scopedThreadKey(ISSUES_PANEL_REF)],
216 ).toMatchObject({ isOpen: true, surfaces: [{ kind: "pull-request", number: 86 }] });
217 expect(screen.router?.state.location.pathname).toBe("/issues");
218});
219​
220it("opens a thread's pull request beside it when its project is a folder with no remote", async () => {
221 setup();
222 state.projects = [{ ...project, repositoryIdentity: null }];
223 await using screen = await render(
224 <AppAtomRegistryProvider>
225 <ThreadPullRequestLink />
226 </AppAtomRegistryProvider>,
227 );
228 await screen.getByRole("link", { name: "Pull request" }).click();
229 expect(useRightPanelStore.getState().byThreadKey[scopedThreadKey(threadRef)]).toMatchObject({
230 isOpen: true,
231 surfaces: [{ kind: "pull-request", projectId: "project", number: 86 }],
232 });
233 expect(state.openLink).not.toHaveBeenCalled();
234});
235​
236it.each([
237 ["nothing else happens", async () => {}, true],
238 [
239 "a newer slow link starts",
240 () => page.getByRole("button", { name: "Newer slow reference" }).click(),
241 false,
242 ],
243 ["a newer pull request link opens", () => page.getByRole("link").click(), false],
244 ["the panel closes", () => act(() => useRightPanelStore.getState().close(threadRef)), false],
245] as const)("lets a slow link open only when %s", async (_case, newer, expected) => {
246 setup();
247 let isCurrent = () => true;
248 await using screen = await render(
249 <AppAtomRegistryProvider>
250 <DeferredThreadLink label="Slow reference" onStart={(check) => (isCurrent = check)} />
251 <DeferredThreadLink label="Newer slow reference" onStart={() => {}} />
252 <ThreadPullRequestLink />
253 </AppAtomRegistryProvider>,
254 );
255 await screen.getByRole("button", { name: "Slow reference", exact: true }).click();
256 await newer();
257 expect(isCurrent()).toBe(expected);
258});
259​
260it("lets a slow link clicked after a slow commit link open when the commit resolves first", async () => {
261 setup();
262 const commitLookup = Promise.withResolvers<unknown>();
263 state.preview.mockReturnValue(commitLookup.promise);
264 let isCurrent = () => false;
265 await using screen = await render(
266 <AppAtomRegistryProvider>
267 <CommitLink />
268 <DeferredThreadLink label="Slow reference" onStart={(check) => (isCurrent = check)} />
269 </AppAtomRegistryProvider>,
270 );
271 await screen.getByRole("link", { name: "Commit" }).click();
272 await screen.getByRole("button", { name: "Slow reference" }).click();
273 await act(async () =>
274 commitLookup.resolve(
275 AsyncResult.success({ sources: [{ kind: "commit", headRef: "a".repeat(40) }] }),
276 ),
277 );
278 expect(useDiffPanelStore.getState().byThreadKey).toEqual({});
279 expect(isCurrent()).toBe(true);
280});
281​
282it("drops a slow commit link once the user leaves its thread, even after returning", async () => {
283 setup();
284 const commitLookup = Promise.withResolvers<unknown>();
285 state.preview.mockReturnValue(commitLookup.promise);
286 await using screen = await render(
287 <AppAtomRegistryProvider>
288 <CommitLink />
289 </AppAtomRegistryProvider>,
290 { router: "/local/thread" },
291 );
292 await screen.getByRole("link", { name: "Commit" }).click();
293 expect(state.preview).toHaveBeenCalledOnce();
294 await act(() => screen.router?.history.push("/local/another-thread"));
295 await act(() => screen.router?.history.push("/local/thread"));
296 await act(async () =>
297 commitLookup.resolve(
298 AsyncResult.success({ sources: [{ kind: "commit", headRef: "a".repeat(40) }] }),
299 ),
300 );
301 expect(useDiffPanelStore.getState().byThreadKey).toEqual({});
302 expect(useRightPanelStore.getState().byThreadKey).toEqual({});
303});