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

openPullRequestLink.ts

329 lines13.2 KB

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