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

useOpenLink.ts

60 lines2.3 KB

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/** Rejects on settings read failure without opening a browser, or if the system-browser fallback fails. */
22export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (
23 url: string,
24 options?: {
25 readonly event?: {
26 readonly metaKey: boolean;
27 readonly ctrlKey: boolean;
28 readonly button?: number | undefined;
29 };
30 readonly threadRef?: ScopedThreadRef | undefined;
31 },
32) => Promise<void> {
33 const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
34 return async (url, options = {}) => {
35 const targetThreadRef = options.threadRef ?? threadRef;
36 const target = resolveLinkTarget({
37 url,
38 event: options.event ?? NO_MODIFIER,
39 preference: await resolveBrowserLinkTargetPreference(),
40 canOpenInApp:
41 targetThreadRef != null &&
42 readEnvironmentScope(targetThreadRef.environmentId, AuthPreviewOperateScope) &&
43 canOpenLinksInApp(targetThreadRef),
44 });
45 if (target === "app" && targetThreadRef) {
46 const result = await openUrlInPreview({ threadRef: targetThreadRef, url, openPreview });
47 if (isAtomCommandInterrupted(result)) return;
48 if (result._tag === "Success") {
49 recordVisitForThread(targetThreadRef, url);
50 return;
51 }
52 const failure = squashAtomCommandFailure(result);
53 if (failure instanceof BrowserSettingsReadError) throw failure;
54 console.error(result.cause);
55 }
56 const api = readLocalApi();
57 if (!api) throw new Error("Link opening is unavailable.");
58 await api.shell.openExternal(url);
59 };