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

ConnectionsNewRouteScreen.tsx

313 lines10.4 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, AppTextInput as TextInput } from "../../components/AppText";
17import { ErrorBanner } from "../../components/ErrorBanner";
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" : "camera",
197 onPress: () => {
198 if (showScanner) {
199 closeScanner();
200 } else {
201 void openScanner();
202 }
203 },
204 },
205 ]}
206 >
207 <NativeStackScreenOptions
208 options={{ title: showScanner ? "Scan QR Code" : "Add Environment" }}
209 />
210 {Platform.OS !== "android" ? (
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 ) : null}
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 <View className={Platform.OS === "android" ? "flex-row justify-end" : undefined}>
297 <ConnectionSheetButton
298 icon="plus"
299 label={isSubmitting ? "Pairing..." : "Add environment"}
300 disabled={connectDisabled}
301 tone="primary"
302 onPress={() => {
303 void handleSubmit();
304 }}
305 />
306 </View>
307 </View>
308 )}
309 </View>
310 </ScrollView>
311 </SettingsScreen>
312 );