The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { ScopedThreadRef } from "@t3tools/contracts"; |
| 2 | import { |
| 3 | isAtomCommandInterrupted, |
| 4 | squashAtomCommandFailure, |
| 5 | } from "@t3tools/client-runtime/state/runtime"; |
| 6 | import { recordVisitForThread } from "~/browserHistoryStore"; |
| 7 | import { readLocalApi } from "~/localApi"; |
| 8 | import { previewEnvironment } from "~/state/preview"; |
| 9 | import { useAtomCommand } from "~/state/use-atom-command"; |
| 10 | |
| 11 | import { |
| 12 | canOpenLinksInApp, |
| 13 | resolveBrowserLinkTargetPreference, |
| 14 | resolveLinkTarget, |
| 15 | } from "./browserLinkTarget"; |
| 16 | import { isBrowserSettingsReadError, openUrlInPreview } from "./openFileInPreview"; |
| 17 | import { msg } from "gt-react"; |
| 18 | import { m } from "~/i18n/messages"; |
| 19 | |
| 20 | const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const; |
| 21 | |
| 22 | /** Rejects on settings read failure without opening a browser, or if the system-browser fallback fails. */ |
| 23 | export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): ( |
| 24 | url: string, |
| 25 | options?: { |
| 26 | readonly event?: { |
| 27 | readonly metaKey: boolean; |
| 28 | readonly ctrlKey: boolean; |
| 29 | readonly button?: number | undefined; |
| 30 | }; |
| 31 | readonly threadRef?: ScopedThreadRef | undefined; |
| 32 | }, |
| 33 | ) => Promise<void> { |
| 34 | const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false }); |
| 35 | return async (url, options = {}) => { |
| 36 | const targetThreadRef = options.threadRef ?? threadRef; |
| 37 | const target = resolveLinkTarget({ |
| 38 | url, |
| 39 | event: options.event ?? NO_MODIFIER, |
| 40 | preference: await resolveBrowserLinkTargetPreference(), |
| 41 | canOpenInApp: canOpenLinksInApp(targetThreadRef), |
| 42 | }); |
| 43 | if (target === "app" && targetThreadRef) { |
| 44 | const result = await openUrlInPreview({ threadRef: targetThreadRef, url, openPreview }); |
| 45 | if (isAtomCommandInterrupted(result)) return; |
| 46 | if (result._tag === "Success") { |
| 47 | recordVisitForThread(targetThreadRef, url); |
| 48 | return; |
| 49 | } |
| 50 | const failure = squashAtomCommandFailure(result); |
| 51 | if (isBrowserSettingsReadError(failure)) throw failure; |
| 52 | console.error(result.cause); |
| 53 | } |
| 54 | const api = readLocalApi(); |
| 55 | if (!api) throw new Error(m(msg("Link opening is unavailable."))); |
| 56 | await api.shell.openExternal(url); |
| 57 | }; |
| 58 | } |