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