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

openPullRequestLink.ts

285 lines11.1 KB

1import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor";
2import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
3import { useAtomValue } from "@effect/atom-react";
4import { useNavigate } from "@tanstack/react-router";
5import { type MouseEvent } from "react";
6​
7import {
8 resolveChangeRequestLinkTarget,
9 resolvePullRequestPreviewTarget,
10} from "@t3tools/client-runtime/change-request-links";
11​
12import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
13​
14import { canOpenLinksInApp } from "../browser/browserLinkTarget";
15import { useOpenLink } from "../browser/useOpenLink";
16import { useClientSettings } from "../hooks/useSettings";
17import { stackedThreadToast, toastManager } from "../components/ui/toast";
18import { useRightPanelStore } from "../rightPanelStore";
19import {
20 selectThreadBranchBaseRef,
21 selectThreadDiffPanelSelection,
22 useDiffPanelStore,
23} from "../diffPanelStore";
24​
25import { appAtomRegistry } from "../rpc/atomRegistry";
26import { readProject, readProjects, readThreadShell, useProjects } from "../state/entities";
27import { environmentServerConfigsAtom, serverEnvironment } from "../state/server";
28import { usePrimaryEnvironmentId } from "../state/environments";
29import { reviewEnvironment } from "../state/review";
30import { useAtomQueryRunner } from "../state/use-atom-query-runner";
31​
32export function usePullRequestPreviewTarget(environmentId: EnvironmentId | null, url: string) {
33 const projects = useProjects();
34 const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
35 return resolvePullRequestPreviewTarget({
36 environmentId,
37 projects,
38 pullRequestsEnabled: serverConfig !== null,
39 url,
40 });
42​
43/** Where a click on this link opens the in-app panel, read at call time as the click reads it. */
44export function pullRequestLinkPanelTarget(input: {
45 readonly url: string;
46 readonly environmentId: EnvironmentId | undefined;
47 readonly primaryEnvironmentId: EnvironmentId | null;
48 readonly lendHostProject: boolean;
49}) {
50 // Read at click time: every provider status push replaces the config map, and
51 // subscribing would hand every rendered link a new handler. Projects likewise, so a
52 // link can resolve against a snapshot that arrived after this handler was built.
53 const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
54 return resolveChangeRequestLinkTarget({
55 url: input.url,
56 projects: readProjects(),
57 configLoaded: (environmentId) => serverConfigs.has(environmentId),
58 environmentId: input.environmentId,
59 primaryEnvironmentId: input.primaryEnvironmentId,
60 lendHostProject: input.lendHostProject,
61 });
63​
64function shouldOpenPullRequestExternally(
65 event: Pick<MouseEvent<HTMLElement>, "metaKey" | "ctrlKey"> &
66 Partial<Pick<MouseEvent<HTMLElement>, "button">>,
67): boolean {
68 return event.metaKey || event.ctrlKey || event.button === 1;
70​
71export function useOpenChangeRequestLink(
72 threadRef?: ScopedThreadRef,
73 panelRef?: ScopedThreadRef,
74): (
75 event: Pick<
76 MouseEvent<HTMLElement>,
77 "preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
78 > &
79 Partial<Pick<MouseEvent<HTMLElement>, "button" | "shiftKey" | "altKey">>,
80 targetUrl: string,
81 targetThreadRef?: ScopedThreadRef,
82 targetEnvironmentId?: EnvironmentId,
83 onCommitUnavailable?: () => void,
84) => boolean {
85 const navigate = useNavigate();
86 const primaryEnvironmentId = usePrimaryEnvironmentId();
87 const openInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp);
88 const ignoreWhitespace = useClientSettings((settings) => settings.diffIgnoreWhitespace);
89 const browserLinkTarget = useClientSettings((settings) => settings.browserLinkTarget);
90 const readDiffPreview = useAtomQueryRunner(reviewEnvironment.diffPreview, {
91 reportFailure: false,
92 refresh: true,
93 });
94 const openLink = useOpenLink(threadRef);
95 return (event, targetUrl, targetThreadRef, targetEnvironmentId, onCommitUnavailable) => {
96 if (!openInApp || shouldOpenPullRequestExternally(event)) return false;
97 const resolvedThreadRef = targetThreadRef ?? threadRef;
98 const resolvedPanelRef = panelRef ?? resolvedThreadRef;
99 const openPullRequest = () => {
100 const target = pullRequestLinkPanelTarget({
101 url: targetUrl,
102 environmentId: resolvedThreadRef?.environmentId ?? targetEnvironmentId,
103 primaryEnvironmentId,
104 lendHostProject: resolvedPanelRef !== undefined,
105 });
106 if (target === null) return false;
107 const { project, repository, number, host } = target;
108 const revealUrl = parsePullRequestAnchor(targetUrl) === null ? undefined : targetUrl;
109 const pullRequestsSearch = {
110 repository,
111 number,
112 ...(host === undefined ? {} : { selectedHost: host }),
113 selectedProjectId: project.id,
114 selectedEnvironmentId: project.environmentId,
115 };
116 if (resolvedPanelRef) {
117 useRightPanelStore.getState().openPullRequest(resolvedPanelRef, {
118 // The standalone PR panel has a synthetic ref; each tab keeps its real environment.
119 ...(resolvedPanelRef.environmentId === project.environmentId
120 ? {}
121 : { environmentId: project.environmentId }),
122 projectId: project.id,
123 ...(host === undefined ? {} : { host }),
124 repository,
125 url: targetUrl,
126 ...(revealUrl === undefined ? {} : { revealUrl }),
127 number,
128 });
129 if (!resolvedThreadRef) {
130 void navigate({
131 to: "/pull-requests",
132 search: (previous) => ({
133 ...previous,
134 involvement: previous.involvement ?? "all",
135 state: previous.state ?? "all",
136 ...pullRequestsSearch,
137 }),
138 replace: true,
139 });
140 }
141 return true;
142 }
143 void navigate({
144 to: "/pull-requests",
145 search: {
146 involvement: "all",
147 state: "all",
148 ...pullRequestsSearch,
149 ...(revealUrl === undefined ? {} : { selectedUrl: revealUrl }),
150 },
151 });
152 return true;
153 };
154 const commitThread = resolvedThreadRef ? readThreadShell(resolvedThreadRef) : null;
155 const commitProject =
156 commitThread && resolvedThreadRef
157 ? readProject({
158 environmentId: resolvedThreadRef.environmentId,
159 projectId: commitThread.projectId,
160 })
161 : null;
162 const identity = commitProject?.repositoryIdentity;
163 const parsedCommit = sourceControlClients.parseCommitUrl(targetUrl, identity?.provider);
164 // Shift and Alt keep their browser meaning (new window, download) on commit links.
165 if (parsedCommit !== null && (event.shiftKey || event.altKey)) return false;
166 // A plain commit link stays a workspace commit; one naming a file or line opens the PR's diff.
167 const anchor = parsePullRequestAnchor(targetUrl);
168 if (anchor !== null && anchor.kind !== "code" && openPullRequest()) {
169 event.preventDefault();
170 event.stopPropagation();
171 return true;
172 }
173​
174 if (
175 parsedCommit !== null &&
176 commitThread &&
177 resolvedThreadRef &&
178 commitProject?.environmentId === resolvedThreadRef.environmentId &&
179 identity &&
180 identity.provider === parsedCommit.definition.kind &&
181 parsedCommit.definition.isChangeRequestInRepository(identity, parsedCommit.link)
182 ) {
183 const commit = parsedCommit.link;
184 event.preventDefault();
185 event.stopPropagation();
186 const userActionRevision = useRightPanelStore.getState().markUserAction(resolvedThreadRef);
187 const baseRef = selectThreadBranchBaseRef(useDiffPanelStore.getState(), resolvedThreadRef);
188 const selection = selectThreadDiffPanelSelection(
189 useDiffPanelStore.getState().byThreadKey,
190 resolvedThreadRef,
191 );
192 void readDiffPreview({
193 environmentId: resolvedThreadRef.environmentId,
194 input: {
195 cwd: commitThread.worktreePath ?? commitProject.workspaceRoot,
196 ...(baseRef ? { baseRef } : {}),
197 commitSha: commit.sha,
198 ignoreWhitespace,
199 },
200 })
201 .then((result) => {
202 if (
203 useRightPanelStore.getState().getUserActionRevision(resolvedThreadRef) !==
204 userActionRevision ||
205 selectThreadDiffPanelSelection(
206 useDiffPanelStore.getState().byThreadKey,
207 resolvedThreadRef,
208 ) !== selection
209 )
210 return;
211 if (
212 result._tag === "Success" &&
213 result.value.sources.some(
214 (source) => source.kind === "commit" && source.headRef === commit.sha,
215 )
216 ) {
217 useDiffPanelStore.getState().selectCommit(resolvedThreadRef, commit.sha);
218 useRightPanelStore.getState().open(resolvedThreadRef, "diff");
219 return;
220 }
221 if (openPullRequest()) return;
222 if (onCommitUnavailable) return onCommitUnavailable();
223 // A popup opened after the lookup has lost the click's activation, so browsers block it.
224 if (
225 window.desktopBridge === undefined &&
226 (browserLinkTarget !== "app" || !canOpenLinksInApp(resolvedThreadRef))
227 ) {
228 const toastId = toastManager.add(
229 stackedThreadToast({
230 type: "info",
231 title: "This commit is not in the thread's workspace",
232 actionProps: {
233 children: "Open link",
234 onClick: () => {
235 toastManager.close(toastId);
236 window.open(targetUrl, "_blank", "noopener,noreferrer");
237 },
238 },
239 }),
240 );
241 return;
242 }
243 return openLink(targetUrl, {
244 event: { metaKey: event.metaKey, ctrlKey: event.ctrlKey, button: event.button },
245 threadRef: resolvedThreadRef,
246 });
247 })
248 .catch((error: unknown) => console.error(error));
249 return true;
250 }
251 if (!openPullRequest()) return false;
252 event.preventDefault();
253 event.stopPropagation();
254 return true;
255 };
257​
258export function useOpenPrLink(threadRef?: ScopedThreadRef) {
259 const openChangeRequest = useOpenChangeRequestLink(threadRef);
260 const openLink = useOpenLink(threadRef);
261 return (event: MouseEvent<HTMLElement>, prUrl: string, targetThreadRef?: ScopedThreadRef) => {
262 if (event.button > 1) return false;
263 event.stopPropagation();
264 const openInBrowser = shouldOpenPullRequestExternally(event);
265 const isAnchor =
266 event.currentTarget instanceof HTMLAnchorElement && event.currentTarget.href.length > 0;
267 // Native links handle modified clicks; buttons still need openExternal.
268 if (openInBrowser && isAnchor) return false;
269​
270 event.preventDefault();
271 if (!openInBrowser && openChangeRequest(event, prUrl, targetThreadRef)) return true;
272​
273 void openLink(prUrl, { event, threadRef: targetThreadRef }).catch((error: unknown) => {
274 console.error(error);
275 toastManager.add(
276 stackedThreadToast({
277 type: "error",
278 title: "Unable to open pull request link",
279 description: error instanceof Error ? error.message : "An error occurred.",
280 }),
281 );
282 });
283 return false;
284 };