Open History to see the last commit
1import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
2import { CameraView, useCameraPermissions } from "expo-camera";
3import {
4 StackActions,
5 useNavigation,
6 useRoute,
7 type StaticScreenProps,
8} from "@react-navigation/native";
9import type { EnvironmentId } from "@t3tools/contracts";
10import { AsyncResult } from "effect/reactivity";
11import { useCallback, useEffect, useRef, useState } from "react";
12import { Alert, Linking, Platform, View } from "react-native";
13import { useSafeAreaInsets } from "react-native-safe-area-context";
14import { useUniwindTheme } from "../../lib/useUniwindTheme";
15import { SettingsScreen } from "../settings/components/SettingsScreen";
16import { AppText as Text } from "../../components/AppText";
17import { ErrorBanner } from "../../components/ErrorBanner";
18import { ConnectionFormField } from "./ConnectionFormField";
19import { ConnectionSheetButton } from "./ConnectionSheetButton";
20import { buildPairingUrl, extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
21import { useRemoteConnections } from "../../state/use-remote-environment-registry";
22
23type ConnectionsNewRouteParams = {
24 readonly mode?: string;
25 readonly pairingUrl?: string;
26 readonly autoConnect?: string;
27 /** Adds a route to this saved machine instead of a new environment. */
28 readonly routeFor?: EnvironmentId;
29};
30
31export function ConnectionsNewRouteScreen({
32 route,
33}: StaticScreenProps<ConnectionsNewRouteParams | undefined>) {
34 const {
35 connectionPairingUrl,
36 onChangeConnectionPairingUrl,
37 onConnectPress,
38 pairingConnectionError,
39 } = useRemoteConnections();
40 const navigation = useNavigation();
41 const routeName = useRoute().name;
42 const params = route.params ?? {};
43 // Deep-link prefill exists for development automation only. A production
44 // link must not arrive with attacker-chosen host and token already filled.
45 const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";
46 const shouldAutoConnect =
47 __DEV__ &&
48 routePairingUrl.length > 0 &&
49 (params.autoConnect === "1" || params.autoConnect === "true");
50 const insets = useSafeAreaInsets();
51 const [hostInput, setHostInput] = useState("");
52 const [codeInput, setCodeInput] = useState("");
53 const [isSubmitting, setIsSubmitting] = useState(false);
54 const [showScanner, setShowScanner] = useState(params.mode === "scan_qr");
55 const [cameraPermission, requestCameraPermission] = useCameraPermissions();
56 const [scannerLocked, setScannerLocked] = useState(false);
57 const attemptedAutoConnectRef = useRef<string | null>(null);
58
59 const headerIconColor = useUniwindTheme()["--color-icon"];
60
61 const connectDisabled = isSubmitting || hostInput.trim().length === 0;
62
63 useEffect(() => {
64 const { host, code } = parsePairingUrl(connectionPairingUrl);
65 setHostInput(host);
66 setCodeInput(code);
67 }, [connectionPairingUrl]);
68
69 useEffect(() => {
70 if (routePairingUrl.length === 0) {
71 return;
72 }
73
74 const { host, code } = parsePairingUrl(routePairingUrl);
75 setHostInput(host);
76 setCodeInput(code);
77 }, [routePairingUrl]);
78
79 useEffect(() => {
80 if (pairingConnectionError) {
81 setIsSubmitting(false);
82 }
83 }, [pairingConnectionError]);
84
85 const handleHostChange = useCallback((value: string) => {
86 setHostInput(value);
87 }, []);
88
89 const handleCodeChange = useCallback((value: string) => {
90 setCodeInput(value);
91 }, []);
92
93 const openScanner = useCallback(async () => {
94 if (cameraPermission?.granted) {
95 setScannerLocked(false);
96 setShowScanner(true);
97 return;
98 }
99
100 const permission = await requestCameraPermission();
101 if (permission.granted) {
102 setScannerLocked(false);
103 setShowScanner(true);
104 return;
105 }
106
107 if (permission.canAskAgain) {
108 Alert.alert(
109 "Camera access needed",
110 "Allow camera access to scan an environment pairing QR code.",
111 );
112 return;
113 }
114
115 Alert.alert(
116 "Camera access needed",
117 "Camera access was denied for this app. Open Settings to enable it.",
118 [
119 { text: "Cancel", style: "cancel" },
120 { text: "Open Settings", onPress: () => void Linking.openSettings() },
121 ],
122 );
123 }, [cameraPermission?.granted, requestCameraPermission]);
124
125 const closeScanner = useCallback(() => {
126 setShowScanner(false);
127 setScannerLocked(false);
128 }, []);
129
130 const handleQrScan = useCallback(
131 ({ data }: { readonly data: string }) => {
132 if (scannerLocked) {
133 return;
134 }
135
136 setScannerLocked(true);
137
138 try {
139 const pairingUrl = extractPairingUrlFromQrPayload(data);
140 const { host, code } = parsePairingUrl(pairingUrl);
141 setHostInput(host);
142 setCodeInput(code);
143 onChangeConnectionPairingUrl(pairingUrl);
144 setShowScanner(false);
145 } catch (error) {
146 Alert.alert(
147 "Invalid QR code",
148 error instanceof Error ? error.message : "Scanned QR code was not recognized.",
149 );
150 } finally {
151 setTimeout(() => {
152 setScannerLocked(false);
153 }, 600);
154 }
155 },
156 [onChangeConnectionPairingUrl, scannerLocked],
157 );
158
159 const connectAndClose = useCallback(
160 async (pairingUrl: string, replaceWithHome: boolean) => {
161 setIsSubmitting(true);
162 onChangeConnectionPairingUrl(pairingUrl);
163 try {
164 const result = await onConnectPress(pairingUrl, params.routeFor);
165 if (AsyncResult.isSuccess(result)) {
166 if (replaceWithHome || !navigation.canGoBack()) {
167 navigation.dispatch(StackActions.replace("Home"));
168 } else {
169 navigation.goBack();
170 }
171 }
172 } finally {
173 setIsSubmitting(false);
174 }
175 },
176 [navigation, onChangeConnectionPairingUrl, onConnectPress, params.routeFor],
177 );
178
179 const handleSubmit = useCallback(async () => {
180 await connectAndClose(buildPairingUrl(hostInput, codeInput), false);
181 }, [codeInput, connectAndClose, hostInput]);
182
183 useEffect(() => {
184 if (!shouldAutoConnect || attemptedAutoConnectRef.current === routePairingUrl) {
185 return;
186 }
187
188 attemptedAutoConnectRef.current = routePairingUrl;
189 void connectAndClose(routePairingUrl, true);
190 }, [connectAndClose, routePairingUrl, shouldAutoConnect]);
191
192 return (
193 <SettingsScreen
194 formSheet={routeName === "ConnectionsNew"}
195 title={showScanner ? "Scan QR Code" : "Add Environment"}
196 actions={[
197 {
198 accessibilityLabel: showScanner ? "Close scanner" : "Scan QR code",
199 icon: showScanner ? "xmark" : Platform.OS === "ios" ? "qrcode.viewfinder" : "camera",
200 tintColor: headerIconColor,
201 onPress: () => {
202 if (showScanner) {
203 closeScanner();
204 } else {
205 void openScanner();
206 }
207 },
208 },
209 ]}
210 >
211 <ScrollView
212 contentInsetAdjustmentBehavior="automatic"
213 showsVerticalScrollIndicator={false}
214 className="flex-1"
215 contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
216 contentContainerStyle={{
217 paddingHorizontal: 20,
218 paddingTop: 16,
219 }}
220 >
221 <View collapsable={false} className="gap-5">
222 {showScanner ? (
223 cameraPermission?.granted ? (
224 <View className="overflow-hidden rounded-[24px] border-continuous">
225 <CameraView
226 barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
227 onBarcodeScanned={handleQrScan}
228 style={{ aspectRatio: 1, width: "100%" }}
229 />
230 </View>
231 ) : (
232 <View className="items-center gap-3 rounded-[24px] border-continuous bg-grouped-card px-5 py-8">
233 <Text className="text-center text-sm leading-normal text-foreground-muted">
234 Camera permission is required to scan a QR code.
235 </Text>
236 <ConnectionSheetButton
237 compact
238 icon="camera"
239 label="Allow camera"
240 tone="secondary"
241 onPress={() => {
242 void openScanner();
243 }}
244 />
245 </View>
246 )
247 ) : (
248 <View collapsable={false} className="gap-4 rounded-[24px] bg-grouped-card p-4">
249 <ConnectionFormField
250 label="Host"
251 autoCapitalize="none"
252 autoCorrect={false}
253 keyboardType="url"
254 placeholder="192.168.1.100:8080"
255 value={hostInput}
256 onChangeText={handleHostChange}
257 />
258
259 <ConnectionFormField
260 label="Pairing code"
261 autoCapitalize="none"
262 autoCorrect={false}
263 placeholder="abc-123-xyz"
264 value={codeInput}
265 onChangeText={handleCodeChange}
266 />
267
268 {pairingConnectionError ? <ErrorBanner message={pairingConnectionError} /> : null}
269
270 <View className="android:flex-row android:justify-end">
271 <ConnectionSheetButton
272 icon="plus"
273 label={isSubmitting ? "Pairing..." : "Add environment"}
274 disabled={connectDisabled}
275 tone="primary"
276 onPress={() => {
277 void handleSubmit();
278 }}
279 />
280 </View>
281 </View>
282 )}
283 </View>
284 </ScrollView>
285 </SettingsScreen>
286 );
287}