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

pullRequestLinkContextMenu.ts

70 lines2.5 KB

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