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