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

pullRequestLinkContextMenu.ts

74 lines2.1 KB

1import type { ContextMenuItem, ContextMenuSource } from "@t3tools/contracts";
2import {
3 type SourceControlDefinition,
4 UNKNOWN_SOURCE_CONTROL_CLIENT,
5} from "@t3tools/client-runtime/source-control-clients";
6​
7import { msg } from "gt-react";
8​
9import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
10import { m, type MessageResolver } from "~/i18n/messages";
11import { readLocalApi } from "~/localApi";
12​
13import { toastManager } from "../ui/toast";
14​
15export type PullRequestLinkContextMenuAction = "copy-link" | "open-external";
16​
17export const openOnHostLabel = (
18 host: SourceControlDefinition,
19 resolve: MessageResolver = m,
20): string =>
21 host === UNKNOWN_SOURCE_CONTROL_CLIENT
22 ? resolve(msg("Open on host"))
23 : resolve(msg("Open on {host}", { host: host.label }));
24​
25function pullRequestLinkContextMenuItems(
26 openLabel: string,
27): readonly ContextMenuItem<PullRequestLinkContextMenuAction>[] {
28 return [
29 { id: "copy-link", label: m(msg("Copy link")), icon: "copy" },
30 { id: "open-external", label: openLabel },
31 ];
33​
34export async function showPullRequestLinkContextMenu({
35 url,
36 openLabel,
37 position,
38 source,
39}: {
40 readonly url: string;
41 readonly openLabel: string;
42 readonly position: { readonly x: number; readonly y: number };
43 readonly source: ContextMenuSource;
44}): Promise<void> {
45 const api = readLocalApi();
46 if (!api) return;
47 let action: PullRequestLinkContextMenuAction | null = null;
48 try {
49 action = await api.contextMenu.show(
50 pullRequestLinkContextMenuItems(openLabel),
51 position,
52 source,
53 );
54 } catch {
55 return;
56 }
57 try {
58 if (action === "copy-link")
59 await writeTextToClipboard(url, {
60 target: "link",
61 unavailableMessage: msg("Clipboard API is unavailable while copying link."),
62 failureMessage: msg("Failed to copy link to the clipboard."),
63 });
64 else if (action === "open-external") await api.shell.openExternal(url);
65 } catch {
66 toastManager.add({
67 type: "error",
68 title:
69 action === "copy-link"
70 ? m(msg("Could not copy the link"))
71 : m(msg("Could not open the link")),
72 });
73 }