Open History to see the last commit
1import { AuthPreviewOperateScope, 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 { readEnvironmentScope } from "~/state/session";
12import { useAtomCommand } from "~/state/use-atom-command";
13
14import {
15 canOpenLinksInApp,
16 resolveBrowserLinkTargetPreference,
17 resolveLinkTarget,
18} from "./browserLinkTarget";
19import { BrowserSettingsReadError, openUrlInPreview } from "./openFileInPreview";
20
21const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const;
22
23/**
24 * Failed settings reads reject without opening a browser. The promise also
25 * rejects if the system-browser fallback fails.
26 */
27export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (
28 url: string,
29 options?: {
30 readonly event?: {
31 readonly metaKey: boolean;
32 readonly ctrlKey: boolean;
33 readonly button?: number | undefined;
34 };
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:
47 targetThreadRef != null &&
48 readEnvironmentScope(targetThreadRef.environmentId, AuthPreviewOperateScope) &&
49 canOpenLinksInApp(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}