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