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

useOpenLink.ts

63 lines2.5 KB

1import type { ScopedThreadRef } from "@t3tools/contracts";
2import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
3import { useCallback } from "react";
4​
5import { recordVisitForThread } from "~/browserHistoryStore";
6import { readLocalApi } from "~/localApi";
7import { previewEnvironment } from "~/state/preview";
8import { useAtomCommand } from "~/state/use-atom-command";
9​
10import {
11 canOpenLinksInApp,
12 resolveBrowserLinkTargetPreference,
13 resolveLinkTarget,
14} from "./browserLinkTarget";
15import { openUrlInPreview } from "./openFileInPreview";
16​
17const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const;
18​
19/**
20 * Opens a URL where the "Open links in" setting says, for buttons that sit
21 * beside a thread but are not markdown anchors: CI check details, a pull
22 * request that has no project to open in the panel. Without a thread there is
23 * nowhere to put an in-app tab, so the link goes to the system browser.
24 *
25 * An in-app open that fails falls back to the system browser rather than
26 * dropping the click: the user asked for the link, and the setting only says
27 * where it should go first. The returned promise rejects only when that
28 * fallback fails too, the same way `shell.openExternal` does.
29 */
30export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (
31 url: string,
32 options?: {
33 readonly event?: { readonly metaKey: boolean; readonly ctrlKey: boolean };
34 /** Thread to open beside when it is not the hook's own, e.g. a sidebar row's. */
35 readonly threadRef?: ScopedThreadRef | undefined;
36 },
37) => Promise<void> {
38 const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
39 return useCallback(
40 async (url, options = {}) => {
41 const targetThreadRef = options.threadRef ?? threadRef;
42 const target = resolveLinkTarget({
43 url,
44 event: options.event ?? NO_MODIFIER,
45 preference: await resolveBrowserLinkTargetPreference(),
46 canOpenInApp: canOpenLinksInApp(Boolean(targetThreadRef)),
47 });
48 if (target === "app" && targetThreadRef) {
49 const result = await openUrlInPreview({ threadRef: targetThreadRef, url, openPreview });
50 if (isAtomCommandInterrupted(result)) return;
51 if (result._tag === "Success") {
52 recordVisitForThread(targetThreadRef, url);
53 return;
54 }
55 console.error(result.cause);
56 }
57 const api = readLocalApi();
58 if (!api) throw new Error("Link opening is unavailable.");
59 await api.shell.openExternal(url);
60 },
61 [openPreview, threadRef],
62 );