Open History to see the last commit
1import type { EnvironmentId, PullRequestRef, ScopedThreadRef } from "@t3tools/contracts";
2import { useAtomValue } from "@effect/atom-react";
3import { useNavigate } from "@tanstack/react-router";
4import { type MouseEvent, useCallback, useMemo } from "react";
5
6import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
7import { parseChangeRequestUrl, type ChangeRequestLink } from "@t3tools/shared/changeRequestUrl";
8import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
9
10import { useOpenLink } from "../browser/useOpenLink";
11import { useClientSettings } from "../hooks/useSettings";
12import { stackedThreadToast, toastManager } from "../components/ui/toast";
13import { useRightPanelStore } from "../rightPanelStore";
14import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
15
16import { useProjects, useServerConfigs } from "../state/entities";
17import { serverEnvironment } from "../state/server";
18import { usePrimaryEnvironmentId } from "../state/environments";
19
20export {
21 parseChangeRequestUrl,
22 type ChangeRequestLink,
23 gitHubPullRequestBrowserUrl,
24 pullRequestCandidateUrlFromReferenceAutolink,
25 matchesLinkedPullRequestUrl,
26 changeRequestRepositoryUrl,
27} from "@t3tools/shared/changeRequestUrl";
28
29/**
30 * The project a link belongs to, or nothing. Matched the way the server matches: the repository
31 * identity is the full path below the host where one was recorded — which is what nested GitLab
32 * groups and Azure project paths need — and the host is the first segment of the canonical
33 * remote, so github.com and an Enterprise install stay apart.
34 */
35export function findProjectForChangeRequest(
36 projects: ReadonlyArray<EnvironmentProject>,
37 link: ChangeRequestLink,
38): EnvironmentProject | undefined {
39 return projects.find((project) => {
40 const identity = project.repositoryIdentity;
41 return (
42 identity?.provider !== undefined &&
43 sourceControlClients.get(identity.provider).isChangeRequestInRepository(identity, link)
44 );
45 });
46}
47
48export function resolvePullRequestPreviewTarget({
49 environmentId,
50 projects,
51 pullRequestsEnabled,
52 url,
53}: {
54 environmentId: EnvironmentId | null;
55 projects: ReadonlyArray<EnvironmentProject>;
56 pullRequestsEnabled: boolean;
57 url: string;
58}): { environmentId: EnvironmentId; input: PullRequestRef } | null {
59 if (!pullRequestsEnabled || environmentId === null) return null;
60 const parsed = parseChangeRequestUrl(url);
61 if (parsed === null) return null;
62 const project = findProjectForChangeRequest(
63 projects.filter((candidate) => candidate.environmentId === environmentId),
64 parsed,
65 );
66 if (project === undefined) return null;
67 return {
68 environmentId,
69 input: {
70 projectId: project.id,
71 host: parsed.authority ?? parsed.host,
72 repository: sourceControlRepositorySelector(project.repositoryIdentity) ?? parsed.repository,
73 number: parsed.number,
74 },
75 };
76}
77
78export function usePullRequestPreviewTarget(environmentId: EnvironmentId | null, url: string) {
79 const projects = useProjects();
80 const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
81 return useMemo(
82 () =>
83 resolvePullRequestPreviewTarget({
84 environmentId,
85 projects,
86 pullRequestsEnabled: serverConfig?.environment.capabilities.pullRequests === true,
87 url,
88 }),
89 [environmentId, projects, serverConfig, url],
90 );
91}
92
93/**
94 * Any project checked out from the link's host. Thread links are host-level, so a pull request
95 * from a repository nobody has checked out is still linkable as long as one project on that
96 * host can lend the server its credentials. The link's own project, when it exists, comes first.
97 */
98export function findProjectOnChangeRequestHost(
99 projects: ReadonlyArray<EnvironmentProject>,
100 link: ChangeRequestLink,
101): EnvironmentProject | undefined {
102 const own = findProjectForChangeRequest(projects, link);
103 if (own !== undefined) return own;
104 return projects.find((project) => {
105 const identity = project.repositoryIdentity;
106 return (
107 identity?.provider !== undefined &&
108 sourceControlClients.get(identity.provider).canReadChangeRequestOnHost(identity, link)
109 );
110 });
111}
112
113/**
114 * Opens a change request link on the page, and says whether it did. Anything else — another
115 * organisation's repository, a host nothing here is checked out from, a link that merely looks
116 * like one — is left alone for the caller to handle as the ordinary link it is.
117 *
118 * Resolving the project here rather than on the page is what makes recognising a URL safe: a
119 * lookalike hostname matches no project and stays a link, and the page is handed the project
120 * rather than a host to narrow its whole list by.
121 *
122 * Given a thread, the link opens beside it in the right panel instead of taking the whole app to
123 * the pull requests page: a reader following a link the agent wrote is reading the thread, and
124 * should still be reading it afterwards. Any change request opens there, not only the thread's
125 * own, since the panel is told which one to show.
126 *
127 * With "Open pull requests in T3 Code" turned off, every link is left alone.
128 */
129/** Cmd/Ctrl-click and middle-click send a pull request to the browser instead of the panel. */
130export function shouldOpenPullRequestExternally(
131 event: Pick<MouseEvent<HTMLElement>, "metaKey" | "ctrlKey"> &
132 Partial<Pick<MouseEvent<HTMLElement>, "button">>,
133): boolean {
134 return event.metaKey || event.ctrlKey || event.button === 1;
135}
136
137export function useOpenChangeRequestLink(
138 threadRef?: ScopedThreadRef,
139 panelRef?: ScopedThreadRef,
140): (
141 event: Pick<
142 MouseEvent<HTMLElement>,
143 "preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
144 >,
145 targetUrl: string,
146 targetThreadRef?: ScopedThreadRef,
147 targetEnvironmentId?: EnvironmentId,
148) => boolean {
149 const navigate = useNavigate();
150 const allProjects = useProjects();
151 const serverConfigs = useServerConfigs();
152 const primaryEnvironmentId = usePrimaryEnvironmentId();
153 const openInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp);
154 return useCallback(
155 (event, targetUrl, targetThreadRef, targetEnvironmentId) => {
156 if (!openInApp || shouldOpenPullRequestExternally(event)) return false;
157 const resolvedThreadRef = targetThreadRef ?? threadRef;
158 const resolvedPanelRef = panelRef ?? resolvedThreadRef;
159 const parsed = parseChangeRequestUrl(targetUrl);
160 if (parsed === null) return false;
161 const reads = (environmentId: string) =>
162 serverConfigs.get(environmentId as EnvironmentId)?.environment.capabilities.pullRequests ===
163 true;
164 // Beside a thread the panel reads on that thread's environment, so a project from another
165 // one could not be read there whatever its remote says: two environments can hold the same
166 // repository, and handing the panel the wrong one's id opens a surface that never loads.
167 //
168 // The page has no such tie — it lists every server at once — so the link is resolved
169 // against all of them, the primary first where two hold the same repository.
170 const projects = resolvedThreadRef
171 ? allProjects.filter((project) => project.environmentId === resolvedThreadRef.environmentId)
172 : targetEnvironmentId
173 ? allProjects.filter((project) => project.environmentId === targetEnvironmentId)
174 : allProjects
175 .filter((project) => reads(project.environmentId))
176 .toSorted(
177 (left, right) =>
178 Number(right.environmentId === primaryEnvironmentId) -
179 Number(left.environmentId === primaryEnvironmentId),
180 );
181 const exactProject = findProjectForChangeRequest(projects, parsed);
182 const project =
183 exactProject ??
184 (resolvedPanelRef
185 ? findProjectOnChangeRequestHost(
186 projects.filter(
187 (candidate) =>
188 serverConfigs.get(candidate.environmentId)?.environment.capabilities
189 .threadPullRequests === true,
190 ),
191 parsed,
192 )
193 : undefined);
194 if (project === undefined || !reads(project.environmentId)) return false;
195 const repository =
196 serverConfigs.get(project.environmentId)?.environment.capabilities.threadPullRequests ===
197 true
198 ? parsed.repository
199 : (sourceControlRepositorySelector(project.repositoryIdentity) ?? parsed.repository);
200 event.preventDefault();
201 event.stopPropagation();
202 if (resolvedPanelRef) {
203 useRightPanelStore.getState().openPullRequest(resolvedPanelRef, {
204 // The standalone PR panel has a synthetic ref; each tab keeps its real environment.
205 ...(resolvedPanelRef.environmentId === project.environmentId
206 ? {}
207 : { environmentId: project.environmentId }),
208 projectId: project.id,
209 ...(serverConfigs.get(project.environmentId)?.environment.capabilities
210 .threadPullRequests === true
211 ? { host: parsed.authority ?? parsed.host }
212 : {}),
213 repository,
214 url: targetUrl,
215 number: parsed.number,
216 });
217 if (!resolvedThreadRef) {
218 void navigate({
219 to: "/pull-requests",
220 search: (previous) => ({
221 ...previous,
222 involvement: previous.involvement ?? "all",
223 state: previous.state ?? "all",
224 repository,
225 number: parsed.number,
226 selectedHost: parsed.authority ?? parsed.host,
227 selectedProjectId: project.id,
228 selectedEnvironmentId: project.environmentId,
229 }),
230 replace: true,
231 });
232 }
233 return true;
234 }
235 void navigate({
236 to: "/pull-requests",
237 search: {
238 involvement: "all",
239 // Every state, so the pull request being opened is also in the list behind it whether
240 // it is open, merged or closed.
241 state: "all",
242 repository,
243 number: parsed.number,
244 selectedHost: parsed.authority ?? parsed.host,
245 selectedProjectId: project.id,
246 // Named so the page opens the right one of two servers holding this project.
247 selectedEnvironmentId: project.environmentId,
248 },
249 });
250 return true;
251 },
252 [allProjects, navigate, openInApp, panelRef, primaryEnvironmentId, serverConfigs, threadRef],
253 );
254}
255
256export function useOpenPrLink(threadRef?: ScopedThreadRef) {
257 const openChangeRequest = useOpenChangeRequestLink(threadRef);
258 const openLink = useOpenLink(threadRef);
259 return useCallback(
260 (event: MouseEvent<HTMLElement>, prUrl: string, targetThreadRef?: ScopedThreadRef) => {
261 // Buttons also pass this to onAuxClick for middle-click; a right-click is not an open.
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 // A real link already knows how to cmd/ctrl/middle-click. Leave its default
268 // action alone so the browser (or Electron's window-open handler) opens
269 // the host. Buttons have no href, so they still go through openExternal.
270 if (openInBrowser && isAnchor) return false;
271
272 event.preventDefault();
273 if (!openInBrowser && openChangeRequest(event, prUrl, targetThreadRef)) return true;
274
275 // No project to show it in, so it is an ordinary link and follows the
276 // "Open links in" setting; the modifier still forces the system browser.
277 void openLink(prUrl, { event, threadRef: targetThreadRef }).catch((error: unknown) => {
278 console.error(error);
279 toastManager.add(
280 stackedThreadToast({
281 type: "error",
282 title: "Unable to open pull request link",
283 description: error instanceof Error ? error.message : "An error occurred.",
284 }),
285 );
286 });
287 return false;
288 },
289 [openChangeRequest, openLink],
290 );
291}