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

pullRequestLinkContextMenu.ts

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