Open History to see the last commit
1import type { NavigationState, PartialState } from "@react-navigation/native";
2import { CommonActions, StackActions } from "@react-navigation/native";
3import type { EnvironmentId } from "@t3tools/contracts";
4import { Atom } from "effect/reactivity";
5
6import { findLinkedRoute } from "../../lib/appLinking";
7import { rootNavigationRef, whenRootNavigationReady } from "../../lib/rootNavigation";
8import { appAtomRegistry } from "../../state/atom-registry";
9import { leaveSettingsPage } from "../settings/settings-navigation";
10import { workspaceHasColumns } from "../workspace/workspace-selection-store";
11import { pairEnvironment } from "../../state/use-remote-environment-registry";
12
13export type DevAutoConnectAttempt =
14 | { readonly pairingUrl: string; readonly status: "connecting" }
15 | { readonly pairingUrl: string; readonly status: "failed"; readonly error: string | null };
16
17/** The pairing the dev deep link started, so the form it opens can show its progress. */
18export const devAutoConnectAttemptAtom = Atom.make<DevAutoConnectAttempt | null>(null).pipe(
19 Atom.keepAlive,
20 Atom.withLabel("mobile:dev-auto-connect-attempt"),
21);
22
23/**
24 * What the form opened by `routePairingUrl` shows of the dev auto-connect. Editing or submitting
25 * (`dismissed`) hides a failure, but a pairing still running keeps Connect busy, so the user
26 * cannot start a second pairing beside it.
27 */
28export function autoConnectReport(
29 attempt: DevAutoConnectAttempt | null,
30 routePairingUrl: string,
31 dismissed: boolean,
32): { readonly connecting: boolean; readonly error: string | null } {
33 if (attempt === null || routePairingUrl.length === 0 || attempt.pairingUrl !== routePairingUrl) {
34 return { connecting: false, error: null };
35 }
36 if (attempt.status === "connecting") return { connecting: true, error: null };
37 return { connecting: false, error: dismissed ? null : attempt.error };
38}
39
40// The pairing form is mounted both as a root sheet and inside the settings sheet.
41const PAIRING_FORM_ROUTES = ["ConnectionsNew", "SettingsEnvironmentNew"];
42
43function isAutoConnectFlag(value: unknown): boolean {
44 return value === "1" || value === "true";
45}
46
47async function connect(pairingUrl: string, expectedEnvironmentId: EnvironmentId | undefined) {
48 const attempt: DevAutoConnectAttempt = { pairingUrl, status: "connecting" };
49 appAtomRegistry.set(devAutoConnectAttemptAtom, attempt);
50 const outcome = await pairEnvironment(pairingUrl, expectedEnvironmentId);
51 // A later link replaced or cleared this attempt; its result belongs to no open form.
52 if (appAtomRegistry.get(devAutoConnectAttemptAtom) !== attempt) return;
53 if (!outcome.ok) {
54 appAtomRegistry.set(devAutoConnectAttemptAtom, {
55 pairingUrl,
56 status: "failed",
57 error: outcome.error,
58 });
59 return;
60 }
61 whenRootNavigationReady(() => {
62 // A newer link (with or without the flag) owns the form now.
63 if (appAtomRegistry.get(devAutoConnectAttemptAtom) !== attempt) return;
64 appAtomRegistry.set(devAutoConnectAttemptAtom, null);
65 const current = rootNavigationRef.getCurrentRoute()?.name;
66 if (current === undefined || !PAIRING_FORM_ROUTES.includes(current)) return;
67 // Same exit as the form's own Connect: return to the opener, and on columns show the
68 // new environment on Environments instead of an empty detail.
69 if (!rootNavigationRef.canGoBack()) rootNavigationRef.dispatch(StackActions.replace("Home"));
70 else leaveSettingsPage(rootNavigationRef, workspaceHasColumns(), "SettingsEnvironments");
71 });
72}
73
74/**
75 * `connections/new?pairingUrl=…&autoConnect=1` (or `settings/environment-new?…`) pairs from the
76 * link itself, so a remount of the form never pairs twice. Production builds ignore the flag so
77 * a link can never pair with an attacker-chosen host.
78 */
79export function startDevAutoConnect(
80 state: PartialState<NavigationState> | undefined,
81): PartialState<NavigationState> | undefined {
82 if (!__DEV__) return state;
83 const route = findLinkedRoute(state, PAIRING_FORM_ROUTES);
84 if (route === undefined) return state;
85 const params = (route.params ?? {}) as {
86 readonly autoConnect?: unknown;
87 readonly pairingUrl?: unknown;
88 readonly routeFor?: EnvironmentId;
89 };
90 const pairingUrl = typeof params.pairingUrl === "string" ? params.pairingUrl.trim() : "";
91 if (isAutoConnectFlag(params.autoConnect) && pairingUrl.length > 0) {
92 void connect(pairingUrl, params.routeFor);
93 } else {
94 // Only links put a pairing URL on the form, so a form opened by any other link starts
95 // clean instead of showing an earlier auto-connect's failure for the same URL.
96 appAtomRegistry.set(devAutoConnectAttemptAtom, null);
97 }
98 return state;
99}
100
101/**
102 * A pairing link that lands on an open pairing form fills that form. React Navigation would push
103 * `ConnectionsNew` over the Settings page's `SettingsEnvironmentNew`, stacking two copies of the
104 * same form. The form keys on the link's pairing URL, so new params remount it with the prefill.
105 */
106export function pairingFormLinkAction(
107 link: PartialState<NavigationState>,
108 current: NavigationState | undefined,
109) {
110 const linked = findLinkedRoute(link, PAIRING_FORM_ROUTES);
111 const open = current?.routes[current.index];
112 if (!linked || !current || !open || !PAIRING_FORM_ROUTES.includes(open.name)) return undefined;
113 return {
114 ...CommonActions.replaceParams(linked.params ?? {}),
115 source: open.key,
116 target: current.key,
117 };
118}