Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

openPullRequestLink.ts

311 lines12.6 KB

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