Open History to see the last commit
1import type {
2 EnvironmentId,
3 RepositoryIdentity,
4 ScopedThreadRef,
5 ThreadLinkedPullRequest,
6} from "@t3tools/contracts";
7import { useNavigate } from "@tanstack/react-router";
8import { type MouseEvent, useCallback } from "react";
9
10import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
11
12import { useOpenLink } from "../browser/useOpenLink";
13import { stackedThreadToast, toastManager } from "../components/ui/toast";
14import { useRightPanelStore } from "../rightPanelStore";
15import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
16
17import { useProjects, useServerConfigs } from "../state/entities";
18import { usePrimaryEnvironmentId } from "../state/environments";
19
20/** Builds a GitHub URL that remains available when the pull request API cannot be read. */
21export function gitHubPullRequestBrowserUrl(
22 identity: RepositoryIdentity | null | undefined,
23 repository: string,
24 number: number,
25): string | null {
26 if (identity?.provider !== "github" || !Number.isSafeInteger(number) || number < 1) return null;
27 const repositoryPath = repository.split("/");
28 if (
29 repositoryPath.length !== 2 ||
30 repositoryPath.some((segment) => segment.length === 0 || segment === "." || segment === "..")
31 ) {
32 return null;
33 }
34
35 let origin: string | null = null;
36 try {
37 const remoteUrl = new URL(identity.locator.remoteUrl.trim());
38 if (remoteUrl.protocol === "http:" || remoteUrl.protocol === "https:") {
39 origin = remoteUrl.origin;
40 }
41 } catch {
42 // SCP-style remotes are read from their normalized identity below.
43 }
44 const hostname = identity.canonicalKey.split("/")[0];
45 if (origin === null && !hostname) return null;
46
47 try {
48 const url = new URL(origin ?? `https://${hostname}`);
49 url.pathname = `/${repositoryPath.join("/")}/pull/${number}`;
50 return url.toString();
51 } catch {
52 return null;
53 }
54}
55
56/**
57 * A change request the page can open, named the way the page names one: the host below which the
58 * repository is addressed, the repository path as that host writes it, and the number.
59 *
60 * The two strings are what `pullRequestHostOf` and the project's `repositoryIdentity` produce
61 * from a git remote — lower case, no port, the full path below the host — because the page matches
62 * a link against those. Anything else opens nothing.
63 */
64export interface ChangeRequestLink {
65 readonly host: string;
66 readonly repository: string;
67 readonly number: number;
68}
69
70/** The host itself, one of its subdomains, or an install named after the provider. */
71function isHostOf(hostname: string, apex: string, label?: string): boolean {
72 if (hostname === apex || hostname.endsWith(`.${apex}`)) return true;
73 return label !== undefined && hostname.startsWith(`${label}.`);
74}
75
76/**
77 * The repository and number behind a change request URL on a host the page can read, or null for
78 * anything else — an issue, a commit, a repository root, a host this cannot tell apart from an
79 * ordinary link. Null means the system browser, so a doubtful match is worse than no match: it
80 * takes the reader out of their browser and into a page that cannot find the change request.
81 *
82 * Each host is recognised by the path shape it alone uses, guarded by a hostname it could
83 * plausibly be served from, since self-hosted installs are named whatever their admin chose:
84 * GitLab's `/-/` marker is unique enough to trust on any hostname, while `/pull/` is generic
85 * enough that it is only believed from a GitHub-ish host.
86 */
87export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | null {
88 let url: URL;
89 try {
90 url = new URL(targetUrl);
91 } catch {
92 return null;
93 }
94 // `javascript:`, `mailto:` and friends have no host to speak of and nothing to open.
95 if (url.protocol !== "https:" && url.protocol !== "http:") return null;
96 // Nothing here tries to tell a lookalike hostname from a real one — `github.com.evil.test`,
97 // `github.com-evil.test` and the rest are an open set, and blocking spellings of it costs real
98 // hosts (`gitlab.com.br` is a registrable domain, not a disguise). What a claim is worth is
99 // decided where it is used: only a link matching a repository this workspace has checked out
100 // opens the page, and everything else stays the ordinary link it was.
101 const host = url.hostname.toLowerCase();
102
103 // GitHub, and any Enterprise install: /{owner}/{repo}/pull/{n}
104 if (isHostOf(host, "github.com", "github")) {
105 const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);
106 return claim(host, match);
107 }
108 // GitLab, self-hosted included: /{group}/[{subgroup}/...]{repo}/-/merge_requests/{n}. The `/-/`
109 // separator is GitLab's own, so the hostname is not asked about.
110 const gitlab = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
111 if (gitlab) return claim(host, gitlab);
112 // Bitbucket Cloud: /{workspace}/{repo}/pull-requests/{n}
113 if (isHostOf(host, "bitbucket.org", "bitbucket")) {
114 const match = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
115 return claim(host, match);
116 }
117 // Azure DevOps, both the current host and the per-organisation one it replaced. `_git` is part
118 // of the repository path there, as it is in the remote URL the identity is read from.
119 if (isHostOf(host, "dev.azure.com") || host.endsWith(".visualstudio.com")) {
120 const match = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(url.pathname);
121 return claim(host, match);
122 }
123 return null;
124}
125
126/**
127 * The pull-request URL a GitHub-style `#123` autolink might name. GitHub writes every bare
128 * reference through `/issues/`, including pull requests, so this only builds a candidate: the
129 * caller must successfully read it as a pull request before treating it as one.
130 */
131export function pullRequestCandidateUrlFromReferenceAutolink(targetUrl: string): string | null {
132 let url: URL;
133 try {
134 url = new URL(targetUrl);
135 } catch {
136 return null;
137 }
138 if (
139 (url.protocol !== "https:" && url.protocol !== "http:") ||
140 !isHostOf(url.hostname.toLowerCase(), "github.com", "github")
141 ) {
142 return null;
143 }
144 const match = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u.exec(url.pathname);
145 if (match?.[1] === undefined || match[2] === undefined) return null;
146 url.pathname = `/${match[1]}/pull/${match[2]}`;
147 return url.toString();
148}
149
150/** Match a stored PR without requiring its project to remain available. */
151export function matchesLinkedPullRequestUrl(
152 linkedPullRequest: ThreadLinkedPullRequest,
153 targetUrl: string,
154): boolean {
155 const linked = parseChangeRequestUrl(linkedPullRequest.url);
156 const target = parseChangeRequestUrl(targetUrl);
157 return (
158 linked !== null &&
159 target !== null &&
160 linked.host === target.host &&
161 linked.repository === target.repository &&
162 linked.number === target.number
163 );
164}
165
166/** The repository root behind a recognised change-request URL, without PR-specific state. */
167export function changeRequestRepositoryUrl(targetUrl: string): string | null {
168 const changeRequest = parseChangeRequestUrl(targetUrl);
169 if (changeRequest === null) return null;
170 const url = new URL(targetUrl);
171 const repositoryPath =
172 /^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??
173 /^(.*?)(?:\/pull\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
174 url.pathname,
175 )?.[1];
176 if (!repositoryPath) return null;
177 url.pathname = repositoryPath;
178 url.search = "";
179 url.hash = "";
180 return url.toString();
181}
182
183function claim(host: string, match: RegExpExecArray | null): ChangeRequestLink | null {
184 const repository = match?.[1];
185 const number = Number(match?.[2]);
186 return repository && Number.isSafeInteger(number) && number > 0
187 ? { host, repository: repository.toLowerCase(), number }
188 : null;
189}
190
191/**
192 * Returns a click handler that opens a pull request URL in the system browser.
193 *
194 * Stops event propagation/default so activating the link does not also trigger
195 * an enclosing row or trigger (e.g. opening the branch dropdown), and surfaces a
196 * toast when the local API is unavailable or the open fails.
197 */
198/**
199 * The project a link belongs to, or nothing. Matched the way the server matches: the repository
200 * identity is the full path below the host where one was recorded — which is what nested GitLab
201 * groups and Azure project paths need — and the host is the first segment of the canonical
202 * remote, so github.com and an Enterprise install stay apart.
203 */
204export function findProjectForChangeRequest(
205 projects: ReadonlyArray<EnvironmentProject>,
206 link: ChangeRequestLink,
207): EnvironmentProject | undefined {
208 return projects.find((project) => {
209 const identity = project.repositoryIdentity;
210 if (!identity) return false;
211 const kind = identity.provider as SourceControlProviderKind | undefined;
212 if (kind === undefined) return false;
213 const repository =
214 identity.displayName ??
215 (identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null);
216 return (
217 repository !== null &&
218 repository.toLowerCase() === link.repository.toLowerCase() &&
219 pullRequestHostOf(identity, kind) === link.host.toLowerCase()
220 );
221 });
222}
223
224/**
225 * Opens a change request link on the page, and says whether it did. Anything else — another
226 * organisation's repository, a host nothing here is checked out from, a link that merely looks
227 * like one — is left alone for the caller to handle as the ordinary link it is.
228 *
229 * Resolving the project here rather than on the page is what makes recognising a URL safe: a
230 * lookalike hostname matches no project and stays a link, and the page is handed the project
231 * rather than a host to narrow its whole list by.
232 *
233 * Given a thread, the link opens beside it in the right panel instead of taking the whole app to
234 * the pull requests page: a reader following a link the agent wrote is reading the thread, and
235 * should still be reading it afterwards. Any change request opens there, not only the thread's
236 * own, since the panel is told which one to show.
237 */
238export function shouldOpenPullRequestExternally(
239 event: Pick<MouseEvent<HTMLElement>, "metaKey" | "ctrlKey">,
240): boolean {
241 return event.metaKey || event.ctrlKey;
242}
243
244export function useOpenChangeRequestLink(
245 threadRef?: ScopedThreadRef,
246 panelRef?: ScopedThreadRef,
247): (
248 event: Pick<
249 MouseEvent<HTMLElement>,
250 "preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
251 >,
252 targetUrl: string,
253 targetThreadRef?: ScopedThreadRef,
254 targetEnvironmentId?: EnvironmentId,
255) => boolean {
256 const navigate = useNavigate();
257 const allProjects = useProjects();
258 const serverConfigs = useServerConfigs();
259 const primaryEnvironmentId = usePrimaryEnvironmentId();
260 return useCallback(
261 (event, targetUrl, targetThreadRef, targetEnvironmentId) => {
262 if (shouldOpenPullRequestExternally(event)) return false;
263 const resolvedThreadRef = targetThreadRef ?? threadRef;
264 const resolvedPanelRef = panelRef ?? resolvedThreadRef;
265 const parsed = parseChangeRequestUrl(targetUrl);
266 if (parsed === null) return false;
267 const reads = (environmentId: string) =>
268 serverConfigs.get(environmentId as EnvironmentId)?.environment.capabilities.pullRequests ===
269 true;
270 // Beside a thread the panel reads on that thread's environment, so a project from another
271 // one could not be read there whatever its remote says: two environments can hold the same
272 // repository, and handing the panel the wrong one's id opens a surface that never loads.
273 //
274 // The page has no such tie — it lists every server at once — so the link is resolved
275 // against all of them, the primary first where two hold the same repository.
276 const projects = resolvedThreadRef
277 ? allProjects.filter((project) => project.environmentId === resolvedThreadRef.environmentId)
278 : targetEnvironmentId
279 ? allProjects.filter((project) => project.environmentId === targetEnvironmentId)
280 : allProjects
281 .filter((project) => reads(project.environmentId))
282 .toSorted(
283 (left, right) =>
284 Number(right.environmentId === primaryEnvironmentId) -
285 Number(left.environmentId === primaryEnvironmentId),
286 );
287 const project = findProjectForChangeRequest(projects, parsed);
288 if (project === undefined || !reads(project.environmentId)) return false;
289 event.preventDefault();
290 event.stopPropagation();
291 if (resolvedPanelRef) {
292 useRightPanelStore.getState().openPullRequest(resolvedPanelRef, {
293 // The standalone PR panel has a synthetic ref; each tab keeps its real environment.
294 ...(resolvedPanelRef.environmentId === project.environmentId
295 ? {}
296 : { environmentId: project.environmentId }),
297 projectId: project.id,
298 // The identity's own spelling, not the one read out of the URL: the panel asks the
299 // provider for this repository, while matching a link only ever compares lower case.
300 repository: project.repositoryIdentity?.displayName ?? parsed.repository,
301 number: parsed.number,
302 });
303 if (!resolvedThreadRef) {
304 void navigate({
305 to: "/pull-requests",
306 search: (previous) => ({
307 ...previous,
308 involvement: previous.involvement ?? "all",
309 state: previous.state ?? "all",
310 repository: project.repositoryIdentity?.displayName ?? parsed.repository,
311 number: parsed.number,
312 selectedProjectId: project.id,
313 selectedEnvironmentId: project.environmentId,
314 }),
315 replace: true,
316 });
317 }
318 return true;
319 }
320 void navigate({
321 to: "/pull-requests",
322 search: {
323 involvement: "all",
324 // Every state, so the pull request being opened is also in the list behind it whether
325 // it is open, merged or closed.
326 state: "all",
327 repository: parsed.repository,
328 number: parsed.number,
329 selectedProjectId: project.id,
330 // Named so the page opens the right one of two servers holding this project.
331 selectedEnvironmentId: project.environmentId,
332 },
333 });
334 return true;
335 },
336 [allProjects, navigate, panelRef, primaryEnvironmentId, serverConfigs, threadRef],
337 );
338}
339
340export function useOpenPrLink(threadRef?: ScopedThreadRef) {
341 const openChangeRequest = useOpenChangeRequestLink(threadRef);
342 const openLink = useOpenLink(threadRef);
343 return useCallback(
344 (event: MouseEvent<HTMLElement>, prUrl: string, targetThreadRef?: ScopedThreadRef) => {
345 event.stopPropagation();
346 const openInBrowser = shouldOpenPullRequestExternally(event);
347 const isAnchor =
348 event.currentTarget instanceof HTMLAnchorElement && event.currentTarget.href.length > 0;
349 // A real link already knows how to cmd/ctrl+click. Leave its default
350 // action alone so the browser (or Electron's window-open handler) opens
351 // the host. Buttons have no href, so they still go through openExternal.
352 if (openInBrowser && isAnchor) return false;
353
354 event.preventDefault();
355 if (!openInBrowser && openChangeRequest(event, prUrl, targetThreadRef)) return true;
356
357 // No project to show it in, so it is an ordinary link and follows the
358 // "Open links in" setting; the modifier still forces the system browser.
359 void openLink(prUrl, { event, threadRef: targetThreadRef }).catch((error: unknown) => {
360 console.error(error);
361 toastManager.add(
362 stackedThreadToast({
363 type: "error",
364 title: "Unable to open pull request link",
365 description: error instanceof Error ? error.message : "An error occurred.",
366 }),
367 );
368 });
369 return false;
370 },
371 [openChangeRequest, openLink],
372 );
373}