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

externalLinkContextMenu.ts

78 lines2.5 KB

1import type { ContextMenuItem } from "@t3tools/contracts";
2​
3export type ExternalLinkContextMenuAction = "open-in-preview" | "open-external" | "copy-link";
4​
5export type ExternalLinkContextMenuFailureOperation =
6 | "show-link-context-menu"
7 | "open-link-in-preview"
8 | "open-link-external"
9 | "copy-link";
10​
11const FAILURE_OPERATION_BY_ACTION = {
12 "open-in-preview": "open-link-in-preview",
13 "open-external": "open-link-external",
14 "copy-link": "copy-link",
15} as const satisfies Record<ExternalLinkContextMenuAction, ExternalLinkContextMenuFailureOperation>;
16​
17const EXTERNAL_LINK_CONTEXT_MENU_ITEMS = [
18 { id: "open-in-preview", label: "Open in integrated browser" },
19 { id: "open-external", label: "Open in system browser" },
20 { id: "copy-link", label: "Copy Link" },
21] as const satisfies readonly ContextMenuItem<ExternalLinkContextMenuAction>[];
22​
23interface ShowExternalLinkContextMenuOptions {
24 readonly href: string;
25 readonly position: { readonly x: number; readonly y: number };
26 readonly showContextMenu: (
27 items: readonly ContextMenuItem<ExternalLinkContextMenuAction>[],
28 position: { readonly x: number; readonly y: number },
29 ) => Promise<ExternalLinkContextMenuAction | null>;
30 readonly openInPreview: (href: string) => Promise<void>;
31 readonly openExternal: (href: string) => Promise<void>;
32 readonly copyLink: (href: string) => Promise<unknown>;
33 readonly reportFailure: (
34 operation: ExternalLinkContextMenuFailureOperation,
35 cause: unknown,
36 ) => void;
38​
39export function resolveExternalWebLinkHost(href: string | undefined): string | null {
40 if (!href) return null;
41 try {
42 const url = new URL(href);
43 if (url.protocol !== "http:" && url.protocol !== "https:") return null;
44 return url.hostname || null;
45 } catch {
46 return null;
47 }
49​
50export async function showExternalLinkContextMenu({
51 href,
52 position,
53 showContextMenu,
54 openInPreview,
55 openExternal,
56 copyLink,
57 reportFailure,
58}: ShowExternalLinkContextMenuOptions): Promise<void> {
59 let action: ExternalLinkContextMenuAction | null;
60 try {
61 action = await showContextMenu(EXTERNAL_LINK_CONTEXT_MENU_ITEMS, position);
62 } catch (cause) {
63 reportFailure("show-link-context-menu", cause);
64 return;
65 }
66​
67 try {
68 if (action === "open-in-preview") {
69 await openInPreview(href);
70 } else if (action === "open-external") {
71 await openExternal(href);
72 } else if (action === "copy-link") {
73 await copyLink(href);
74 }
75 } catch (cause) {
76 if (action) reportFailure(FAILURE_OPERATION_BY_ACTION[action], cause);
77 }