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

openPullRequestLink.browser.test.tsx

160 lines5.9 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(() => ({ preview: vi.fn(), openLink: vi.fn() }));
10vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.preview }));
11vi.mock("../browser/useOpenLink", () => ({ useOpenLink: () => state.openLink }));
12vi.mock(import("../state/environments"), async (original) => ({
13 ...(await original()),
14 usePrimaryEnvironmentId: () => EnvironmentId.make("local"),
15}));
16vi.mock("../state/entities", async (original) => ({
17 ...(await original<typeof import("../state/entities")>()),
18 readProjects: () => [project],
19 useProjects: () => [project],
20 readProject: () => project,
21 readThreadShell: () => ({ projectId: "project", worktreePath: null }),
22}));
23vi.mock("../state/server", async (original) => {
24 const { Atom } = await import("effect/reactivity");
25 return {
26 ...(await original<typeof import("../state/server")>()),
27 environmentServerConfigsAtom: Atom.make(new Map([["local", {}]])),
28 };
29});
30​
31import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
32import { __setClientSettingsForTests } from "../hooks/useSettings";
33import { ToastProvider } from "../components/ui/toast";
34import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
35import { useRightPanelStore } from "../rightPanelStore";
36import { useDiffPanelStore } from "../diffPanelStore";
37import { useOpenChangeRequestLink } from "./openPullRequestLink";
38​
39const environmentId = EnvironmentId.make("local");
40const threadRef = scopeThreadRef(environmentId, ThreadId.make("thread"));
41const project = {
42 id: "project",
43 environmentId,
44 workspaceRoot: "/repo",
45 repositoryIdentity: {
46 provider: "github",
47 canonicalKey: "github.com/effect-ts/effect",
48 displayName: "Effect-TS/effect",
49 locator: {
50 source: "git-remote",
51 remoteName: "origin",
52 remoteUrl: "https://github.com/Effect-TS/effect.git",
53 },
54 },
55};
56const commitUrl = `https://github.com/Effect-TS/effect/commit/${"a".repeat(40)}?plain=1#diff-original`;
57const pullRequestCommitUrl = `https://github.com/Effect-TS/effect/pull/1/commits/${"a".repeat(40)}`;
58​
59function CommitLink({ url = commitUrl }: { url?: string }) {
60 const open = useOpenChangeRequestLink(threadRef);
61 return (
62 <a href={url} onClick={(event) => open(event, url)}>
63 Commit
64 </a>
65 );
67​
68function setup() {
69 state.preview.mockReset().mockResolvedValue(AsyncResult.success({ sources: [] }));
70 state.openLink.mockReset().mockResolvedValue(undefined);
71 __setClientSettingsForTests({
72 ...DEFAULT_CLIENT_SETTINGS,
73 pullRequestLinksOpenInApp: true,
74 browserLinkTarget: "system",
75 });
76 useDiffPanelStore.setState({
77 byThreadKey: {},
78 branchBaseRefByThreadKey: {},
79 keepSelectionOnOpenThreadKey: null,
80 });
81 useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });
83​
84it.each([
85 ["shiftKey", commitUrl],
86 ["altKey", commitUrl],
87 ["shiftKey", pullRequestCommitUrl],
88] as const)("keeps %s clicks on %s native", async (modifier, url) => {
89 setup();
90 await using screen = await render(
91 <AppAtomRegistryProvider>
92 <CommitLink url={url} />
93 </AppAtomRegistryProvider>,
94 );
95 const event = new MouseEvent("click", { bubbles: true, cancelable: true, [modifier]: true });
96 const defaults: boolean[] = [];
97 screen.container.addEventListener(
98 "click",
99 (nativeEvent) => {
100 defaults.push(nativeEvent.defaultPrevented);
101 nativeEvent.preventDefault();
102 },
103 { once: true },
104 );
105 await act(() => screen.getByRole("link", { name: "Commit" }).element().dispatchEvent(event));
106 expect(defaults).toEqual([false]);
107 expect(state.preview).not.toHaveBeenCalled();
108 expect(useRightPanelStore.getState().byThreadKey).toEqual({});
109});
110​
111it.each(["system", "app"] as const)(
112 "offers the original unavailable commit URL when web popups are blocked (%s)",
113 async (browserLinkTarget) => {
114 setup();
115 // Without preview access, the "app" preference opens a popup too.
116 __setClientSettingsForTests({
117 ...DEFAULT_CLIENT_SETTINGS,
118 pullRequestLinksOpenInApp: true,
119 browserLinkTarget,
120 });
121 using _desktop = stubGlobal("desktopBridge", undefined);
122 await using screen = await render(
123 <AppAtomRegistryProvider>
124 <ToastProvider>
125 <CommitLink />
126 </ToastProvider>
127 </AppAtomRegistryProvider>,
128 );
129 using open = vi.spyOn(window, "open").mockReturnValue(null);
130 await screen.getByRole("link", { name: "Commit" }).click();
131 await expect
132 .element(page.getByRole("button", { name: "Open link", exact: true }))
133 .toBeVisible();
134 expect(open).not.toHaveBeenCalled();
135 await page.getByRole("button", { name: "Open link", exact: true }).click();
136 expect(open).toHaveBeenCalledExactlyOnceWith(commitUrl, "_blank", "noopener,noreferrer");
137 expect(state.openLink).not.toHaveBeenCalled();
138 },
139);
140​
141it("opens an available commit in the closed Diff pane without the pane resetting it", async () => {
142 setup();
143 const sha = "a".repeat(40);
144 state.preview.mockResolvedValue(
145 AsyncResult.success({ sources: [{ kind: "commit", headRef: sha }] }),
146 );
147 await using screen = await render(
148 <AppAtomRegistryProvider>
149 <CommitLink />
150 </AppAtomRegistryProvider>,
151 );
152 await screen.getByRole("link", { name: "Commit" }).click();
153 await vi.waitFor(() =>
154 expect(useDiffPanelStore.getState().byThreadKey).toEqual({
155 [scopedThreadKey(threadRef)]: { kind: "commit", sha, baseRef: null },
156 }),
157 );
158 // ChatView resets a pane opened without an explicit request to Changes unless this is set.
159 expect(useDiffPanelStore.getState().consumeKeepSelectionOnOpen(threadRef)).toBe(true);
160});