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

ConnectionsNewRouteScreen.tsx

299 lines10.1 KB

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, 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 Alert.alert(
99 "Camera access needed",
100 "Allow camera access to scan an environment pairing QR code.",
101 );
102 }, [cameraPermission?.granted, requestCameraPermission]);
103​
104 const closeScanner = useCallback(() => {
105 setShowScanner(false);
106 setScannerLocked(false);
107 }, []);
108​
109 const handleQrScan = useCallback(
110 ({ data }: { readonly data: string }) => {
111 if (scannerLocked) {
112 return;
113 }
114​
115 setScannerLocked(true);
116​
117 try {
118 const pairingUrl = extractPairingUrlFromQrPayload(data);
119 const { host, code } = parsePairingUrl(pairingUrl);
120 setHostInput(host);
121 setCodeInput(code);
122 onChangeConnectionPairingUrl(pairingUrl);
123 setShowScanner(false);
124 } catch (error) {
125 Alert.alert(
126 "Invalid QR code",
127 error instanceof Error ? error.message : "Scanned QR code was not recognized.",
128 );
129 } finally {
130 setTimeout(() => {
131 setScannerLocked(false);
132 }, 600);
133 }
134 },
135 [onChangeConnectionPairingUrl, scannerLocked],
136 );
137​
138 const connectAndClose = useCallback(
139 async (pairingUrl: string, replaceWithHome: boolean) => {
140 setIsSubmitting(true);
141 onChangeConnectionPairingUrl(pairingUrl);
142 try {
143 const result = await onConnectPress(pairingUrl);
144 if (AsyncResult.isSuccess(result)) {
145 if (replaceWithHome || !navigation.canGoBack()) {
146 navigation.dispatch(StackActions.replace("Home"));
147 } else {
148 navigation.goBack();
149 }
150 }
151 } finally {
152 setIsSubmitting(false);
153 }
154 },
155 [navigation, onChangeConnectionPairingUrl, onConnectPress],
156 );
157​
158 const handleSubmit = useCallback(async () => {
159 await connectAndClose(buildPairingUrl(hostInput, codeInput), false);
160 }, [codeInput, connectAndClose, hostInput]);
161​
162 useEffect(() => {
163 if (!shouldAutoConnect || attemptedAutoConnectRef.current === routePairingUrl) {
164 return;
165 }
166​
167 attemptedAutoConnectRef.current = routePairingUrl;
168 void connectAndClose(routePairingUrl, true);
169 }, [connectAndClose, routePairingUrl, shouldAutoConnect]);
170​
171 return (
172 <View collapsable={false} className="flex-1 bg-sheet">
173 <NativeStackScreenOptions
174 options={{
175 // Android renders its own in-screen header below instead of the native bar.
176 ...(Platform.OS === "android" ? { headerShown: false } : null),
177 title: showScanner ? "Scan QR Code" : "Add Environment",
178 }}
179 />
180 {Platform.OS === "android" ? (
181 <AndroidScreenHeader
182 title={showScanner ? "Scan QR Code" : "Add Environment"}
183 onBack={() => navigation.goBack()}
184 actions={[
185 {
186 accessibilityLabel: showScanner ? "Close scanner" : "Scan QR code",
187 icon: showScanner ? "xmark" : "camera",
188 onPress: () => {
189 if (showScanner) {
190 closeScanner();
191 } else {
192 void openScanner();
193 }
194 },
195 },
196 ]}
197 />
198 ) : (
199 <NativeHeaderToolbar placement="right">
200 <NativeHeaderToolbar.Button
201 icon={showScanner ? "xmark" : "qrcode.viewfinder"}
202 onPress={() => {
203 if (showScanner) {
204 closeScanner();
205 } else {
206 void openScanner();
207 }
208 }}
209 separateBackground
210 tintColor={headerIconColor}
211 />
212 </NativeHeaderToolbar>
213 )}
214​
215 <ScrollView
216 contentInsetAdjustmentBehavior="automatic"
217 showsVerticalScrollIndicator={false}
218 className="flex-1"
219 contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
220 contentContainerStyle={{
221 paddingHorizontal: 20,
222 paddingTop: 16,
223 }}
224 >
225 <View collapsable={false} className="gap-5">
226 {showScanner ? (
227 cameraPermission?.granted ? (
228 <View className="overflow-hidden rounded-[24px] border-continuous">
229 <CameraView
230 barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
231 onBarcodeScanned={handleQrScan}
232 style={{ aspectRatio: 1, width: "100%" }}
233 />
234 </View>
235 ) : (
236 <View className="items-center gap-3 rounded-[24px] border-continuous bg-card px-5 py-8">
237 <Text className="text-center text-sm leading-normal text-foreground-muted">
238 Camera permission is required to scan a QR code.
239 </Text>
240 <ConnectionSheetButton
241 compact
242 icon="camera"
243 label="Allow camera"
244 tone="secondary"
245 onPress={() => {
246 void openScanner();
247 }}
248 />
249 </View>
250 )
251 ) : (
252 <View collapsable={false} className="gap-4 rounded-[24px] bg-card p-4">
253 <View collapsable={false} className="gap-1.5">
254 <Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
255 Host
256 </Text>
257 <TextInput
258 autoCapitalize="none"
259 autoCorrect={false}
260 keyboardType="url"
261 placeholder="192.168.1.100:8080"
262 value={hostInput}
263 onChangeText={handleHostChange}
264 className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-base text-foreground"
265 />
266 </View>
267​
268 <View collapsable={false} className="gap-1.5">
269 <Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
270 Pairing code
271 </Text>
272 <TextInput
273 autoCapitalize="none"
274 autoCorrect={false}
275 placeholder="abc-123-xyz"
276 value={codeInput}
277 onChangeText={handleCodeChange}
278 className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-base text-foreground"
279 />
280 </View>
281​
282 {pairingConnectionError ? <ErrorBanner message={pairingConnectionError} /> : null}
283​
284 <ConnectionSheetButton
285 icon="plus"
286 label={isSubmitting ? "Pairing..." : "Add environment"}
287 disabled={connectDisabled}
288 tone="primary"
289 onPress={() => {
290 void handleSubmit();
291 }}
292 />
293 </View>
294 )}
295 </View>
296 </ScrollView>
297 </View>
298 );