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

openPullRequestLink.ts

283 lines11.4 KB

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