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

pullRequestLinkContextMenu.ts

52 lines1.6 KB

1import type { ContextMenuItem } from "@t3tools/contracts";
2import {
3 type SourceControlDefinition,
4 UNKNOWN_SOURCE_CONTROL_CLIENT,
5} from "@t3tools/client-runtime/source-control-clients";
6​
7import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
8import { readLocalApi } from "~/localApi";
9​
10import { toastManager } from "../ui/toast";
11​
12export type PullRequestLinkContextMenuAction = "copy-link" | "open-external";
13​
14export const openOnHostLabel = (host: SourceControlDefinition): string =>
15 host === UNKNOWN_SOURCE_CONTROL_CLIENT ? "Open on host" : `Open on ${host.label}`;
16​
17function pullRequestLinkContextMenuItems(
18 openLabel: string,
19): readonly ContextMenuItem<PullRequestLinkContextMenuAction>[] {
20 return [
21 { id: "copy-link", label: "Copy link", icon: "copy" },
22 { id: "open-external", label: openLabel },
23 ];
25​
26export async function showPullRequestLinkContextMenu({
27 url,
28 openLabel,
29 position,
30}: {
31 readonly url: string;
32 readonly openLabel: string;
33 readonly position: { readonly x: number; readonly y: number };
34}): Promise<void> {
35 const api = readLocalApi();
36 if (!api) return;
37 let action: PullRequestLinkContextMenuAction | null = null;
38 try {
39 action = await api.contextMenu.show(pullRequestLinkContextMenuItems(openLabel), position);
40 } catch {
41 return;
42 }
43 try {
44 if (action === "copy-link") await writeTextToClipboard(url, "link");
45 else if (action === "open-external") await api.shell.openExternal(url);
46 } catch {
47 toastManager.add({
48 type: "error",
49 title: action === "copy-link" ? "Could not copy the link" : "Could not open the link",
50 });
51 }