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

openPullRequestLink.ts

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