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 { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
7import { parseChangeRequestUrl, type ChangeRequestLink } from "@t3tools/shared/changeRequestUrl";
8import {
9 canonicalRepositoryKey,
10 sourceControlRepositorySelector,
11} from "@t3tools/shared/sourceControl";
12
13import { useOpenLink } from "../browser/useOpenLink";
14import { stackedThreadToast, toastManager } from "../components/ui/toast";
15import { useRightPanelStore } from "../rightPanelStore";
16import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
17
18import { useProjects, useServerConfigs } from "../state/entities";
19import { serverEnvironment } from "../state/server";
20import { usePrimaryEnvironmentId } from "../state/environments";
21
22export {
23 parseChangeRequestUrl,
24 type ChangeRequestLink,
25 gitHubPullRequestBrowserUrl,
26 pullRequestCandidateUrlFromReferenceAutolink,
27 matchesLinkedPullRequestUrl,
28 changeRequestRepositoryUrl,
29} from "@t3tools/shared/changeRequestUrl";
30
31function resolvedForgejoRepository(project: EnvironmentProject): URL | null {
32 const identity = project.repositoryIdentity;
33 if (identity?.provider !== "forgejo" || !identity.webUrl) return null;
34 try {
35 const url = new URL(identity.webUrl);
36 return url.protocol === "http:" || url.protocol === "https:" ? url : null;
37 } catch {
38 return null;
39 }
40}
41
42/** Keep Forgejo servers on different HTTP ports separate when selecting a project. */
43function matchesChangeRequestAuthority(
44 project: EnvironmentProject,
45 link: ChangeRequestLink,
46): boolean {
47 if (link.authority === undefined) return true;
48 try {
49 const remote = new URL(project.repositoryIdentity?.locator.remoteUrl ?? "");
50 if (remote.protocol === "http:" || remote.protocol === "https:") {
51 return remote.host.toLowerCase() === link.authority;
52 }
53 } catch {
54 // SSH remotes do not specify the server's HTTP port; tea resolves the configured login.
55 }
56 return true;
57}
58
59/**
60 * The project a link belongs to, or nothing. Matched the way the server matches: the repository
61 * identity is the full path below the host where one was recorded — which is what nested GitLab
62 * groups and Azure project paths need — and the host is the first segment of the canonical
63 * remote, so github.com and an Enterprise install stay apart.
64 */
65export function findProjectForChangeRequest(
66 projects: ReadonlyArray<EnvironmentProject>,
67 link: ChangeRequestLink,
68): EnvironmentProject | undefined {
69 return projects.find((project) => {
70 const identity = project.repositoryIdentity;
71 if (!identity || !matchesChangeRequestAuthority(project, link)) return false;
72 const kind = identity.provider as SourceControlProviderKind | undefined;
73 if (kind === undefined) return false;
74 const web = resolvedForgejoRepository(project);
75 if (web)
76 return (
77 web.host.toLowerCase() === (link.authority ?? link.host).toLowerCase() &&
78 web.pathname.replace(/^\/+|\/+$/g, "").toLowerCase() === link.repository.toLowerCase()
79 );
80 if (kind === "azure-devops") {
81 return (
82 canonicalRepositoryKey(identity.canonicalKey.toLowerCase()) ===
83 canonicalRepositoryKey(`${link.host}/${link.repository}`.toLowerCase())
84 );
85 }
86 const repository =
87 identity.displayName ??
88 (identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null);
89 return (
90 repository !== null &&
91 repository.toLowerCase() === link.repository.toLowerCase() &&
92 (pullRequestHostOf(identity, kind) === link.host.toLowerCase() ||
93 pullRequestHostOf(identity, kind) === link.authority)
94 );
95 });
96}
97
98export function resolvePullRequestPreviewTarget({
99 environmentId,
100 projects,
101 pullRequestsEnabled,
102 url,
103}: {
104 environmentId: EnvironmentId | null;
105 projects: ReadonlyArray<EnvironmentProject>;
106 pullRequestsEnabled: boolean;
107 url: string;
108}): { environmentId: EnvironmentId; input: PullRequestRef } | null {
109 if (!pullRequestsEnabled || environmentId === null) return null;
110 const parsed = parseChangeRequestUrl(url);
111 if (parsed === null) return null;
112 const project = findProjectForChangeRequest(
113 projects.filter((candidate) => candidate.environmentId === environmentId),
114 parsed,
115 );
116 if (project === undefined) return null;
117 return {
118 environmentId,
119 input: {
120 projectId: project.id,
121 host: parsed.authority ?? parsed.host,
122 repository: sourceControlRepositorySelector(project.repositoryIdentity) ?? parsed.repository,
123 number: parsed.number,
124 },
125 };
126}
127
128export function usePullRequestPreviewTarget(environmentId: EnvironmentId | null, url: string) {
129 const projects = useProjects();
130 const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
131 return useMemo(
132 () =>
133 resolvePullRequestPreviewTarget({
134 environmentId,
135 projects,
136 pullRequestsEnabled: serverConfig?.environment.capabilities.pullRequests === true,
137 url,
138 }),
139 [environmentId, projects, serverConfig, url],
140 );
141}
142
143/**
144 * Any project checked out from the link's host. Thread links are host-level, so a pull request
145 * from a repository nobody has checked out is still linkable as long as one project on that
146 * host can lend the server its credentials. The link's own project, when it exists, comes first.
147 */
148export function findProjectOnChangeRequestHost(
149 projects: ReadonlyArray<EnvironmentProject>,
150 link: ChangeRequestLink,
151): EnvironmentProject | undefined {
152 const own = findProjectForChangeRequest(projects, link);
153 if (own !== undefined) return own;
154 // Azure CLI reads use the checkout's organization and project, not host-wide credentials.
155 if (
156 canonicalRepositoryKey(`${link.host}/${link.repository}`.toLowerCase()).startsWith(
157 "dev.azure.com/",
158 )
159 )
160 return undefined;
161 return projects.find((project) => {
162 const identity = project.repositoryIdentity;
163 const kind = identity?.provider as SourceControlProviderKind | undefined;
164 const web = resolvedForgejoRepository(project);
165 if (web) {
166 const mount = web.pathname
167 .replace(/^\/+|\/+$/g, "")
168 .split("/")
169 .slice(0, -2)
170 .join("/");
171 return (
172 web.host.toLowerCase() === (link.authority ?? link.host).toLowerCase() &&
173 (!mount || link.repository.toLowerCase().startsWith(`${mount.toLowerCase()}/`))
174 );
175 }
176 return (
177 identity != null &&
178 kind !== undefined &&
179 kind !== "azure-devops" &&
180 matchesChangeRequestAuthority(project, link) &&
181 (pullRequestHostOf(identity, kind) === link.host.toLowerCase() ||
182 pullRequestHostOf(identity, kind) === link.authority)
183 );
184 });
185}
186
187/**
188 * Opens a change request link on the page, and says whether it did. Anything else — another
189 * organisation's repository, a host nothing here is checked out from, a link that merely looks
190 * like one — is left alone for the caller to handle as the ordinary link it is.
191 *
192 * Resolving the project here rather than on the page is what makes recognising a URL safe: a
193 * lookalike hostname matches no project and stays a link, and the page is handed the project
194 * rather than a host to narrow its whole list by.
195 *
196 * Given a thread, the link opens beside it in the right panel instead of taking the whole app to
197 * the pull requests page: a reader following a link the agent wrote is reading the thread, and
198 * should still be reading it afterwards. Any change request opens there, not only the thread's
199 * own, since the panel is told which one to show.
200 */
201export function shouldOpenPullRequestExternally(
202 event: Pick<MouseEvent<HTMLElement>, "metaKey" | "ctrlKey">,
203): boolean {
204 return event.metaKey || event.ctrlKey;
205}
206
207export function useOpenChangeRequestLink(
208 threadRef?: ScopedThreadRef,
209 panelRef?: ScopedThreadRef,
210): (
211 event: Pick<
212 MouseEvent<HTMLElement>,
213 "preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
214 >,
215 targetUrl: string,
216 targetThreadRef?: ScopedThreadRef,
217 targetEnvironmentId?: EnvironmentId,
218) => boolean {
219 const navigate = useNavigate();
220 const allProjects = useProjects();
221 const serverConfigs = useServerConfigs();
222 const primaryEnvironmentId = usePrimaryEnvironmentId();
223 return useCallback(
224 (event, targetUrl, targetThreadRef, targetEnvironmentId) => {
225 if (shouldOpenPullRequestExternally(event)) return false;
226 const resolvedThreadRef = targetThreadRef ?? threadRef;
227 const resolvedPanelRef = panelRef ?? resolvedThreadRef;
228 const parsed = parseChangeRequestUrl(targetUrl);
229 if (parsed === null) return false;
230 const reads = (environmentId: string) =>
231 serverConfigs.get(environmentId as EnvironmentId)?.environment.capabilities.pullRequests ===
232 true;
233 // Beside a thread the panel reads on that thread's environment, so a project from another
234 // one could not be read there whatever its remote says: two environments can hold the same
235 // repository, and handing the panel the wrong one's id opens a surface that never loads.
236 //
237 // The page has no such tie — it lists every server at once — so the link is resolved
238 // against all of them, the primary first where two hold the same repository.
239 const projects = resolvedThreadRef
240 ? allProjects.filter((project) => project.environmentId === resolvedThreadRef.environmentId)
241 : targetEnvironmentId
242 ? allProjects.filter((project) => project.environmentId === targetEnvironmentId)
243 : allProjects
244 .filter((project) => reads(project.environmentId))
245 .toSorted(
246 (left, right) =>
247 Number(right.environmentId === primaryEnvironmentId) -
248 Number(left.environmentId === primaryEnvironmentId),
249 );
250 const exactProject = findProjectForChangeRequest(projects, parsed);
251 const project =
252 exactProject ??
253 (resolvedPanelRef
254 ? findProjectOnChangeRequestHost(
255 projects.filter(
256 (candidate) =>
257 serverConfigs.get(candidate.environmentId)?.environment.capabilities
258 .threadPullRequests === true,
259 ),
260 parsed,
261 )
262 : undefined);
263 if (project === undefined || !reads(project.environmentId)) return false;
264 const repository =
265 serverConfigs.get(project.environmentId)?.environment.capabilities.threadPullRequests ===
266 true
267 ? parsed.repository
268 : (sourceControlRepositorySelector(project.repositoryIdentity) ?? parsed.repository);
269 event.preventDefault();
270 event.stopPropagation();
271 if (resolvedPanelRef) {
272 useRightPanelStore.getState().openPullRequest(resolvedPanelRef, {
273 // The standalone PR panel has a synthetic ref; each tab keeps its real environment.
274 ...(resolvedPanelRef.environmentId === project.environmentId
275 ? {}
276 : { environmentId: project.environmentId }),
277 projectId: project.id,
278 ...(serverConfigs.get(project.environmentId)?.environment.capabilities
279 .threadPullRequests === true
280 ? { host: parsed.authority ?? parsed.host }
281 : {}),
282 repository,
283 url: targetUrl,
284 number: parsed.number,
285 });
286 if (!resolvedThreadRef) {
287 void navigate({
288 to: "/pull-requests",
289 search: (previous) => ({
290 ...previous,
291 involvement: previous.involvement ?? "all",
292 state: previous.state ?? "all",
293 repository,
294 number: parsed.number,
295 selectedHost: parsed.authority ?? parsed.host,
296 selectedProjectId: project.id,
297 selectedEnvironmentId: project.environmentId,
298 }),
299 replace: true,
300 });
301 }
302 return true;
303 }
304 void navigate({
305 to: "/pull-requests",
306 search: {
307 involvement: "all",
308 // Every state, so the pull request being opened is also in the list behind it whether
309 // it is open, merged or closed.
310 state: "all",
311 repository,
312 number: parsed.number,
313 selectedHost: parsed.authority ?? parsed.host,
314 selectedProjectId: project.id,
315 // Named so the page opens the right one of two servers holding this project.
316 selectedEnvironmentId: project.environmentId,
317 },
318 });
319 return true;
320 },
321 [allProjects, navigate, panelRef, primaryEnvironmentId, serverConfigs, threadRef],
322 );
323}
324
325export function useOpenPrLink(threadRef?: ScopedThreadRef) {
326 const openChangeRequest = useOpenChangeRequestLink(threadRef);
327 const openLink = useOpenLink(threadRef);
328 return useCallback(
329 (event: MouseEvent<HTMLElement>, prUrl: string, targetThreadRef?: ScopedThreadRef) => {
330 event.stopPropagation();
331 const openInBrowser = shouldOpenPullRequestExternally(event);
332 const isAnchor =
333 event.currentTarget instanceof HTMLAnchorElement && event.currentTarget.href.length > 0;
334 // A real link already knows how to cmd/ctrl+click. Leave its default
335 // action alone so the browser (or Electron's window-open handler) opens
336 // the host. Buttons have no href, so they still go through openExternal.
337 if (openInBrowser && isAnchor) return false;
338
339 event.preventDefault();
340 if (!openInBrowser && openChangeRequest(event, prUrl, targetThreadRef)) return true;
341
342 // No project to show it in, so it is an ordinary link and follows the
343 // "Open links in" setting; the modifier still forces the system browser.
344 void openLink(prUrl, { event, threadRef: targetThreadRef }).catch((error: unknown) => {
345 console.error(error);
346 toastManager.add(
347 stackedThreadToast({
348 type: "error",
349 title: "Unable to open pull request link",
350 description: error instanceof Error ? error.message : "An error occurred.",
351 }),
352 );
353 });
354 return false;
355 },
356 [openChangeRequest, openLink],
357 );
358}