Open History to see the last commit
1import type { ContextMenuItem } from "@t3tools/contracts";
2
3import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
4import { readLocalApi } from "~/localApi";
5
6import { toastManager } from "../ui/toast";
7
8export type PullRequestLinkContextMenuAction = "copy-link" | "open-external";
9
10/** Named for the host rather than "externally": the point is where you will land. */
11const OPEN_ON_HOST_LABELS: Partial<Record<string, string>> = {
12 github: "Open on GitHub",
13 gitlab: "Open on GitLab",
14 bitbucket: "Open on Bitbucket",
15 "azure-devops": "Open on Azure DevOps",
16};
17
18export const openOnHostLabel = (provider: string): string =>
19 OPEN_ON_HOST_LABELS[provider] ?? "Open on host";
20
21/** Copy first: it is the reason to right-click a number rather than click it. */
22function pullRequestLinkContextMenuItems(
23 openLabel: string,
24): readonly ContextMenuItem<PullRequestLinkContextMenuAction>[] {
25 return [
26 { id: "copy-link", label: "Copy link", icon: "copy" },
27 { id: "open-external", label: openLabel },
28 ];
29}
30
31/**
32 * The right-click on a change request's number. Everywhere else that number is written it is a
33 * link, and the gesture that copies a link is the one hand reaches for — so without this the
34 * platform's own edit menu opens over a control that has nothing to cut, paste or select.
35 *
36 * The host is named by the caller rather than guessed here: the same number belongs to GitHub,
37 * GitLab, Bitbucket or Azure DevOps depending on where it was read, and the `url` the contract
38 * carries is already whichever of them it came from.
39 */
40export async function showPullRequestLinkContextMenu({
41 url,
42 openLabel,
43 position,
44}: {
45 readonly url: string;
46 readonly openLabel: string;
47 readonly position: { readonly x: number; readonly y: number };
48}): Promise<void> {
49 const api = readLocalApi();
50 if (!api) return;
51 let action: PullRequestLinkContextMenuAction | null = null;
52 try {
53 action = await api.contextMenu.show(pullRequestLinkContextMenuItems(openLabel), position);
54 } catch {
55 // A menu that could not be shown has already cost the reader their right-click; there is
56 // nothing to say about it that a second popup would not make worse.
57 return;
58 }
59 try {
60 if (action === "copy-link") await writeTextToClipboard(url, "link");
61 else if (action === "open-external") await api.shell.openExternal(url);
62 } catch {
63 toastManager.add({
64 type: "error",
65 title: action === "copy-link" ? "Could not copy the link" : "Could not open the link",
66 });
67 }
68}