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

browserLinkTarget.ts

51 lines1.6 KB

1import {
2 AuthPreviewOperateScope,
3 type BrowserLinkTarget,
4 type ScopedThreadRef,
5} from "@t3tools/contracts";
6​
7import { ensureClientSettingsHydrated, getClientSettings } from "~/hooks/useSettings";
8import { readEnvironmentScope } from "~/state/session";
9import { isPreviewAvailableFor } from "./previewRuntime";
10​
11export interface ResolveLinkTargetInput {
12 readonly url: string;
13 readonly event: {
14 readonly metaKey: boolean;
15 readonly ctrlKey: boolean;
16 readonly button?: number | undefined;
17 };
18 readonly preference: BrowserLinkTarget;
19 readonly canOpenInApp: boolean;
21​
22export function resolveLinkTarget(input: ResolveLinkTargetInput): BrowserLinkTarget {
23 if (input.event.metaKey || input.event.ctrlKey || input.event.button === 1) return "system";
24 if (input.preference !== "app") return "system";
25 if (!input.canOpenInApp) return "system";
26 if (!isWebUrl(input.url)) return "system";
27 return "app";
29​
30export function isWebUrl(url: string): boolean {
31 try {
32 const { protocol } = new URL(url);
33 return protocol === "http:" || protocol === "https:";
34 } catch {
35 return false;
36 }
38​
39/** Before hydration, the default "system" would ignore a saved "app" link target. */
40export async function resolveBrowserLinkTargetPreference(): Promise<BrowserLinkTarget> {
41 await ensureClientSettingsHydrated();
42 return getClientSettings().browserLinkTarget;
44​
45export function canOpenLinksInApp(threadRef: ScopedThreadRef | null | undefined): boolean {
46 return (
47 threadRef != null &&
48 readEnvironmentScope(threadRef.environmentId, AuthPreviewOperateScope) &&
49 isPreviewAvailableFor(threadRef.environmentId)
50 );