Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ConnectionsNewRouteScreen.tsx

304 lines9.8 KB

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