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