Repository navigation
Expand file tree
/
Copy pathopenPullRequestLink.ts
More file actions
339 lines (327 loc) · 13 KB
/
Copy pathopenPullRequestLink.ts
File metadata and controls
339 lines (327 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import type {
EnvironmentId,
ScopedThreadRef,
ExecutionEnvironmentCapabilities,
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { useNavigate } from "@tanstack/react-router";
import { type MouseEvent } from "react";
import {
resolveChangeRequestLinkTarget,
resolvePullRequestPreviewTarget as resolveSharedPullRequestPreviewTarget,
findProjectOnChangeRequestHost,
} from "@t3tools/client-runtime/change-request-links";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import { canOpenLinksInApp } from "../browser/browserLinkTarget";
import { useOpenLink } from "../browser/useOpenLink";
import { useClientSettings } from "../hooks/useSettings";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
import {
selectThreadBranchBaseRef,
selectThreadDiffPanelSelection,
useDiffPanelStore,
} from "../diffPanelStore";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { readProject, readProjects, readThreadShell, useProjects } from "../state/entities";
import { environmentServerConfigsAtom, serverEnvironment } from "../state/server";
import { usePrimaryEnvironmentId } from "../state/environments";
import { reviewEnvironment } from "../state/review";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
export function resolvePullRequestPreviewTarget({
capabilities,
...input
}: Omit<Parameters<typeof resolveSharedPullRequestPreviewTarget>[0], "pullRequestsEnabled"> & {
capabilities:
| Pick<ExecutionEnvironmentCapabilities, "pullRequests" | "threadPullRequests">
| undefined;
}) {
const own = resolveSharedPullRequestPreviewTarget({
...input,
pullRequestsEnabled: capabilities?.pullRequests === true,
});
if (
own !== null ||
capabilities?.pullRequests !== true ||
capabilities.threadPullRequests !== true ||
input.environmentId === null
)
return own;
const parsed = sourceControlClients.parseChangeRequestUrl(input.url)?.link;
if (parsed === undefined) return null;
const project = findProjectOnChangeRequestHost(
input.projects.filter((project) => project.environmentId === input.environmentId),
parsed,
);
if (project === undefined) return null;
return {
environmentId: input.environmentId,
input: {
projectId: project.id,
host: parsed.authority ?? parsed.host,
repository: parsed.repository,
number: parsed.number,
},
};
}
export function usePullRequestPreviewTarget(environmentId: EnvironmentId | null, url: string) {
const projects = useProjects();
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
return resolvePullRequestPreviewTarget({
environmentId,
projects,
capabilities: serverConfig?.environment.capabilities,
url,
});
}
function shouldOpenPullRequestExternally(
event: Pick<MouseEvent<HTMLElement>, "metaKey" | "ctrlKey"> &
Partial<Pick<MouseEvent<HTMLElement>, "button">>,
): boolean {
return event.metaKey || event.ctrlKey || event.button === 1;
}
export function useOpenChangeRequestLink(
threadRef?: ScopedThreadRef,
panelRef?: ScopedThreadRef,
): (
event: Pick<
MouseEvent<HTMLElement>,
"preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
> &
Partial<Pick<MouseEvent<HTMLElement>, "button" | "shiftKey" | "altKey">>,
targetUrl: string,
targetThreadRef?: ScopedThreadRef,
targetEnvironmentId?: EnvironmentId,
onCommitUnavailable?: () => void,
) => boolean {
const navigate = useNavigate();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const openInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp);
const ignoreWhitespace = useClientSettings((settings) => settings.diffIgnoreWhitespace);
const browserLinkTarget = useClientSettings((settings) => settings.browserLinkTarget);
const readDiffPreview = useAtomQueryRunner(reviewEnvironment.diffPreview, {
reportFailure: false,
refresh: true,
});
const openLink = useOpenLink(threadRef);
return (event, targetUrl, targetThreadRef, targetEnvironmentId, onCommitUnavailable) => {
if (!openInApp || shouldOpenPullRequestExternally(event)) return false;
const resolvedThreadRef = targetThreadRef ?? threadRef;
const resolvedPanelRef = panelRef ?? resolvedThreadRef;
const openPullRequest = () => {
// Read at click time: every provider status push replaces the config map, and
// subscribing would hand every rendered link a new handler. Projects likewise, so a
// link can resolve against a snapshot that arrived after this handler was built.
const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
const target = resolveChangeRequestLinkTarget({
url: targetUrl,
projects: readProjects(),
configLoaded: (environmentId) => serverConfigs.has(environmentId),
environmentId: resolvedThreadRef?.environmentId ?? targetEnvironmentId,
primaryEnvironmentId,
lendHostProject: resolvedPanelRef !== undefined,
});
if (target === null) return false;
const { project, repository, number, host } = target;
const pullRequestsSearch = {
repository,
number,
...(host === undefined ? {} : { selectedHost: host }),
selectedProjectId: project.id,
selectedEnvironmentId: project.environmentId,
};
if (resolvedPanelRef) {
useRightPanelStore.getState().openPullRequest(resolvedPanelRef, {
// The standalone PR panel has a synthetic ref; each tab keeps its real environment.
...(resolvedPanelRef.environmentId === project.environmentId
? {}
: { environmentId: project.environmentId }),
projectId: project.id,
...(host === undefined ? {} : { host }),
repository,
url: targetUrl,
number,
});
if (!resolvedThreadRef) {
void navigate({
to: "/pull-requests",
search: (previous) => ({
...previous,
involvement: previous.involvement ?? "all",
state: previous.state ?? "all",
...pullRequestsSearch,
}),
replace: true,
});
}
return true;
}
void navigate({
to: "/pull-requests",
search: { involvement: "all", state: "all", ...pullRequestsSearch },
});
return true;
};
const commitThread = resolvedThreadRef ? readThreadShell(resolvedThreadRef) : null;
const commitProject =
commitThread && resolvedThreadRef
? readProject({
environmentId: resolvedThreadRef.environmentId,
projectId: commitThread.projectId,
})
: null;
const identity = commitProject?.repositoryIdentity;
const parsedCommit = sourceControlClients.parseCommitUrl(targetUrl, identity?.provider);
// Shift and Alt keep their browser meaning (new window, download) on commit links.
if (parsedCommit !== null && (event.shiftKey || event.altKey)) return false;
if (
parsedCommit !== null &&
commitThread &&
resolvedThreadRef &&
commitProject?.environmentId === resolvedThreadRef.environmentId &&
identity &&
identity.provider === parsedCommit.definition.kind &&
parsedCommit.definition.isChangeRequestInRepository(identity, parsedCommit.link)
) {
const commit = parsedCommit.link;
event.preventDefault();
event.stopPropagation();
const userActionRevision = useRightPanelStore.getState().markUserAction(resolvedThreadRef);
const baseRef = selectThreadBranchBaseRef(useDiffPanelStore.getState(), resolvedThreadRef);
const selection = selectThreadDiffPanelSelection(
useDiffPanelStore.getState().byThreadKey,
resolvedThreadRef,
);
void readDiffPreview({
environmentId: resolvedThreadRef.environmentId,
input: {
cwd: commitThread.worktreePath ?? commitProject.workspaceRoot,
...(baseRef ? { baseRef } : {}),
commitSha: commit.sha,
ignoreWhitespace,
},
})
.then((result) => {
if (
useRightPanelStore.getState().getUserActionRevision(resolvedThreadRef) !==
userActionRevision ||
selectThreadDiffPanelSelection(
useDiffPanelStore.getState().byThreadKey,
resolvedThreadRef,
) !== selection
)
return;
if (
result._tag === "Success" &&
result.value.sources.some(
(source) => source.kind === "commit" && source.headRef === commit.sha,
)
) {
const diffOpen =
selectActiveRightPanel(
useRightPanelStore.getState().byThreadKey,
resolvedThreadRef,
) === "diff";
useDiffPanelStore.getState().selectCommit(resolvedThreadRef, commit.sha, !diffOpen);
useRightPanelStore.getState().open(resolvedThreadRef, "diff");
return;
}
if (openPullRequest()) return;
if (onCommitUnavailable) return onCommitUnavailable();
// A popup opened after the lookup has lost the click's activation, so browsers block it.
if (
window.desktopBridge === undefined &&
(browserLinkTarget !== "app" || !canOpenLinksInApp(resolvedThreadRef))
) {
const toastId = toastManager.add(
stackedThreadToast({
type: "info",
title: "This commit is not in the thread's workspace",
actionProps: {
children: "Open link",
onClick: () => {
toastManager.close(toastId);
window.open(targetUrl, "_blank", "noopener,noreferrer");
},
},
}),
);
return;
}
return openLink(targetUrl, {
event: { metaKey: event.metaKey, ctrlKey: event.ctrlKey, button: event.button },
threadRef: resolvedThreadRef,
});
})
.catch((error: unknown) => console.error(error));
return true;
}
if (!openPullRequest()) return false;
event.preventDefault();
event.stopPropagation();
return true;
};
}
export function useOpenPrLink(threadRef?: ScopedThreadRef, panelRef?: ScopedThreadRef) {
const openChangeRequest = useOpenChangeRequestLink(threadRef, panelRef);
const openLink = useOpenLink(threadRef);
return (event: MouseEvent<HTMLElement>, prUrl: string, targetThreadRef?: ScopedThreadRef) => {
if (event.button > 1) return false;
event.stopPropagation();
const openInBrowser = shouldOpenPullRequestExternally(event);
const isAnchor =
event.currentTarget instanceof HTMLAnchorElement && event.currentTarget.href.length > 0;
// Native links handle modified clicks; buttons still need openExternal.
if (openInBrowser && isAnchor) return false;
event.preventDefault();
if (!openInBrowser && openChangeRequest(event, prUrl, targetThreadRef)) return true;
void openLink(prUrl, { event, threadRef: targetThreadRef }).catch((error: unknown) => {
console.error(error);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open pull request link",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
});
return false;
};
}
/**
* Opens the thread's own pull request (the details panel rows and the composer badge) where
* Settings → General → Open pull requests in says. "Side panel" is useOpenPrLink. "Browser"
* swaps the two: a click goes to the browser "Open links in" picks, and Cmd/Ctrl-click opens
* the side panel, so the other destination stays one modifier away.
*/
export function usePreferredOpenPrLink(threadRef?: ScopedThreadRef) {
const openPrLink = useOpenPrLink(threadRef);
const openChangeRequest = useOpenChangeRequestLink(threadRef);
const openLink = useOpenLink(threadRef);
const target = useClientSettings((settings) => settings.pullRequestOpenTarget);
return (event: MouseEvent<HTMLElement>, prUrl: string, targetThreadRef?: ScopedThreadRef) => {
if (target !== "browser") return openPrLink(event, prUrl, targetThreadRef);
event.stopPropagation();
event.preventDefault();
if (shouldOpenPullRequestExternally(event)) {
const panelEvent = {
preventDefault: () => event.preventDefault(),
stopPropagation: () => event.stopPropagation(),
metaKey: false,
ctrlKey: false,
};
if (openChangeRequest(panelEvent, prUrl, targetThreadRef)) return true;
}
void openLink(prUrl, { threadRef: targetThreadRef }).catch((error: unknown) => {
console.error(error);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open pull request link",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
});
return false;
};
}