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