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 { recordVisitForThread } from "~/browserHistoryStore";
7import { readLocalApi } from "~/localApi";
8import { previewEnvironment } from "~/state/preview";
9import { readEnvironmentScope } from "~/state/session";
10import { useAtomCommand } from "~/state/use-atom-command";
11
12import {
13 canOpenLinksInApp,
14 resolveBrowserLinkTargetPreference,
15 resolveLinkTarget,
16} from "./browserLinkTarget";
17import { BrowserSettingsReadError, openUrlInPreview } from "./openFileInPreview";
18
19const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const;
20
21/**
22 * Failed settings reads reject without opening a browser. The promise also
23 * rejects if the system-browser fallback fails.
24 */
25export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (
26 url: string,
27 options?: {
28 readonly event?: {
29 readonly metaKey: boolean;
30 readonly ctrlKey: boolean;
31 readonly button?: number | undefined;
32 };
33 readonly threadRef?: ScopedThreadRef | undefined;
34 },
35) => Promise<void> {
36 const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
37 return async (url, options = {}) => {
38 const targetThreadRef = options.threadRef ?? threadRef;
39 const target = resolveLinkTarget({
40 url,
41 event: options.event ?? NO_MODIFIER,
42 preference: await resolveBrowserLinkTargetPreference(),
43 canOpenInApp:
44 targetThreadRef != null &&
45 readEnvironmentScope(targetThreadRef.environmentId, AuthPreviewOperateScope) &&
46 canOpenLinksInApp(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 const failure = squashAtomCommandFailure(result);
56 if (failure instanceof BrowserSettingsReadError) throw failure;
57 console.error(result.cause);
58 }
59 const api = readLocalApi();
60 if (!api) throw new Error("Link opening is unavailable.");
61 await api.shell.openExternal(url);
62 };
63}