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