Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
3import { useAuth } from "@clerk/expo";
4import { CameraView, useCameraPermissions } from "expo-camera";
5import * as Haptics from "expo-haptics";
6import {
7 StackActions,
8 useIsFocused,
9 useNavigation,
10 useRoute,
11 type StaticScreenProps,
12} from "@react-navigation/native";
13import type { EnvironmentId } from "@t3tools/contracts";
14import { AsyncResult } from "effect/reactivity";
15import { useEffect, useRef, useState } from "react";
16import { Linking, Pressable, StyleSheet, View } from "react-native";
17import Svg, { Defs, RadialGradient, Rect, Stop } from "react-native-svg";
18import { useSafeAreaInsets } from "react-native-safe-area-context";
19import { cn } from "../../lib/cn";
20import { useUniwindTheme } from "../../lib/useUniwindTheme";
21import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
22import { SettingsScreen } from "../settings/components/SettingsScreen";
23import { AppText as Text, AppTextInput, type AppTextInputProps } from "../../components/ui/AppText";
24import { FrostedCutout } from "../../components/ui/FrostedCutout";
25import { buildPairingUrl, extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
26import {
27 setPendingConnectionError,
28 useRemoteConnections,
29} from "../../state/use-remote-environment-registry";
30import { SymbolView } from "../../components/ui/AppSymbol";
31import { hasCloudPublicConfig } from "../cloud/publicConfig";
32import { CloudEnvironmentRows } from "./CloudEnvironmentRows";
33import { splitEnvironmentSections } from "./environmentSections";
34
35type ConnectionsNewRouteParams = {
36 readonly mode?: string;
37 readonly pairingUrl?: string;
38 readonly autoConnect?: string;
39 readonly routeFor?: EnvironmentId;
40};
41
42export function ConnectionsNewRouteScreen({
43 route,
44}: StaticScreenProps<ConnectionsNewRouteParams | undefined>) {
45 const {
46 connectionPairingUrl,
47 onChangeConnectionPairingUrl,
48 onConnectPress,
49 pairingConnectionError,
50 } = useRemoteConnections();
51 const navigation = useNavigation();
52 const routeName = useRoute().name;
53 const params = route.params ?? {};
54 // Deep-link prefill exists for development automation only. A production
55 // link must not arrive with attacker-chosen host and token already filled.
56 const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";
57 const shouldAutoConnect =
58 __DEV__ &&
59 routePairingUrl.length > 0 &&
60 (params.autoConnect === "1" || params.autoConnect === "true");
61 const insets = useSafeAreaInsets();
62 const [hostInput, setHostInput] = useState("");
63 const [codeInput, setCodeInput] = useState("");
64 const [isSubmitting, setIsSubmitting] = useState(false);
65 const [cameraPermission, requestCameraPermission] = useCameraPermissions();
66 const screenFocused = useIsFocused();
67 const [scannerLocked, setScannerLocked] = useState(false);
68 // A good scan parks the camera so it can't re-read the code over later edits.
69 const [scanComplete, setScanComplete] = useState(false);
70 const attemptedAutoConnectRef = useRef<string | null>(null);
71
72 const headerIconColor = useUniwindTheme()["--color-icon"];
73
74 const connectDisabled = isSubmitting || hostInput.trim().length === 0;
75
76 useEffect(() => {
77 const { host, code } = parsePairingUrl(connectionPairingUrl);
78 setHostInput(host);
79 setCodeInput(code);
80 }, [connectionPairingUrl]);
81
82 useEffect(() => {
83 if (routePairingUrl.length === 0) {
84 return;
85 }
86
87 const { host, code } = parsePairingUrl(routePairingUrl);
88 setHostInput(host);
89 setCodeInput(code);
90 }, [routePairingUrl]);
91
92 useEffect(() => {
93 if (pairingConnectionError) {
94 setIsSubmitting(false);
95 }
96 }, [pairingConnectionError]);
97
98 const handleHostChange = (value: string) => {
99 setHostInput(value);
100 setPendingConnectionError(null);
101 };
102
103 const handleCodeChange = (value: string) => {
104 setCodeInput(value);
105 setPendingConnectionError(null);
106 };
107
108 useEffect(() => () => setPendingConnectionError(null), []);
109
110 const handleScanPress = async () => {
111 const permission = await requestCameraPermission();
112 if (permission.granted) {
113 setScanComplete(false);
114 return;
115 }
116 if (permission.canAskAgain) return;
117 Dialog.alert(
118 "Camera access needed",
119 "Camera access was denied for this app. Open Settings to enable it.",
120 [
121 { text: "Cancel", style: "cancel" },
122 { text: "Open Settings", onPress: () => void Linking.openSettings() },
123 ],
124 );
125 };
126
127 const handleQrScan = ({ data }: { readonly data: string }) => {
128 if (scannerLocked) {
129 return;
130 }
131
132 setScannerLocked(true);
133
134 try {
135 const pairingUrl = extractPairingUrlFromQrPayload(data);
136 const { host, code } = parsePairingUrl(pairingUrl);
137 setHostInput(host);
138 setCodeInput(code);
139 onChangeConnectionPairingUrl(pairingUrl);
140 setScanComplete(true);
141 setScannerLocked(false);
142 } catch (error) {
143 void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
144 Dialog.alert(
145 "Invalid QR code",
146 error instanceof Error ? error.message : "Scanned QR code was not recognized.",
147 );
148 setTimeout(() => {
149 setScannerLocked(false);
150 }, 600);
151 }
152 };
153
154 const connectAndClose = async (pairingUrl: string) => {
155 setIsSubmitting(true);
156 onChangeConnectionPairingUrl(pairingUrl);
157 const result = await onConnectPress(pairingUrl, params.routeFor);
158 setIsSubmitting(false);
159 void Haptics.notificationAsync(
160 AsyncResult.isSuccess(result)
161 ? Haptics.NotificationFeedbackType.Success
162 : Haptics.NotificationFeedbackType.Error,
163 );
164 if (AsyncResult.isSuccess(result)) {
165 // Return to whatever opened the sheet. Replacing it with Home would
166 // nest Home inside any sheet still below it.
167 if (!navigation.canGoBack()) {
168 navigation.dispatch(StackActions.replace("Home"));
169 } else {
170 navigation.goBack();
171 }
172 }
173 };
174
175 const handleSubmit = async () => {
176 await connectAndClose(buildPairingUrl(hostInput, codeInput));
177 };
178
179 useEffect(() => {
180 if (!shouldAutoConnect || attemptedAutoConnectRef.current === routePairingUrl) {
181 return;
182 }
183
184 attemptedAutoConnectRef.current = routePairingUrl;
185 void connectAndClose(routePairingUrl);
186 }, [connectAndClose, routePairingUrl, shouldAutoConnect]);
187
188 return (
189 <SettingsScreen
190 formSheet={routeName === "ConnectionsNew"}
191 title="Add environment"
192 actions={[
193 {
194 accessibilityLabel: isSubmitting ? "Connecting" : "Add environment",
195 loading: isSubmitting,
196 icon: "checkmark",
197 tintColor: headerIconColor,
198 disabled: connectDisabled,
199 onPress: () => {
200 void handleSubmit();
201 },
202 },
203 ]}
204 >
205 <ScrollView
206 nestedScrollEnabled
207 contentInsetAdjustmentBehavior="automatic"
208 keyboardShouldPersistTaps="handled"
209 showsVerticalScrollIndicator={false}
210 className="flex-1"
211 contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
212 contentContainerStyle={{
213 paddingHorizontal: 16,
214 paddingTop: 4,
215 }}
216 >
217 <View collapsable={false} className="gap-6.5">
218 <PairingScanCard
219 cameraActive={cameraPermission?.granted === true && screenFocused && !scanComplete}
220 onScan={handleQrScan}
221 onScanPress={() => {
222 void handleScanPress();
223 }}
224 />
225
226 <View collapsable={false} className="gap-2">
227 <Text className="px-4 text-sm font-t3-medium text-foreground-muted">Or enter it</Text>
228 <View
229 collapsable={false}
230 className={cn(
231 "overflow-hidden rounded-[26px] border-continuous border bg-grouped-card",
232 pairingConnectionError ? "border-danger-foreground" : "border-transparent",
233 )}
234 >
235 <PairingInputRow
236 label="Address"
237 keyboardType="url"
238 placeholder="192.168.1.100:3773"
239 value={hostInput}
240 onChangeText={handleHostChange}
241 />
242 <View className="ml-4 border-t border-border-subtle" />
243 <PairingInputRow
244 label="Code"
245 placeholder="Pairing code"
246 returnKeyType="go"
247 value={codeInput}
248 onChangeText={handleCodeChange}
249 onSubmitEditing={() => {
250 if (!connectDisabled) void handleSubmit();
251 }}
252 />
253 </View>
254 <Text
255 accessibilityLiveRegion="polite"
256 className={cn(
257 "px-4 text-sm leading-normal",
258 pairingConnectionError ? "text-danger-foreground" : "text-foreground-muted",
259 )}
260 >
261 {pairingConnectionError ??
262 "For machines on your local network or tailnet. The machine keeps its own provider credentials."}
263 </Text>
264 </View>
265
266 {hasCloudPublicConfig() ? <T3ConnectSection /> : null}
267 </View>
268 </ScrollView>
269 </SettingsScreen>
270 );
271}
272
273const SCAN_CARD_HEIGHT = 250;
274const SCAN_RETICLE_SIZE = 150;
275const SCAN_RETICLE_TOP = 36;
276const SCAN_RETICLE_RADIUS = 28;
277
278function PairingScanCard(props: {
279 readonly cameraActive: boolean;
280 readonly onScan: (result: { readonly data: string }) => void;
281 readonly onScanPress: () => void;
282}) {
283 const light = useAppearancePreferences().themeAppearance === "light";
284 return (
285 <Pressable
286 accessibilityRole={props.cameraActive ? undefined : "button"}
287 accessibilityLabel={props.cameraActive ? undefined : "Scan QR code"}
288 disabled={props.cameraActive}
289 onPress={props.onScanPress}
290 className={cn(
291 "overflow-hidden rounded-[26px] border-continuous",
292 light ? "bg-white" : "bg-black",
293 )}
294 style={{ height: SCAN_CARD_HEIGHT }}
295 >
296 <Svg accessibilityElementsHidden height="100%" style={StyleSheet.absoluteFill} width="100%">
297 <Defs>
298 <RadialGradient id="pairing-scan-backdrop" cx="50%" cy="50%" r="50%">
299 <Stop offset="0%" stopColor={light ? "#f4f4f5" : "#2e2e2e"} />
300 <Stop offset="100%" stopColor={light ? "#d9d9dc" : "#0e0e0e"} />
301 </RadialGradient>
302 </Defs>
303 <Rect fill="url(#pairing-scan-backdrop)" height="100%" width="100%" />
304 </Svg>
305
306 {props.cameraActive ? (
307 <>
308 <CameraView
309 active
310 barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
311 onBarcodeScanned={props.onScan}
312 style={StyleSheet.absoluteFill}
313 />
314 <FrostedCutout
315 cutoutTop={SCAN_RETICLE_TOP}
316 cutoutWidth={SCAN_RETICLE_SIZE}
317 cutoutHeight={SCAN_RETICLE_SIZE}
318 cutoutRadius={SCAN_RETICLE_RADIUS}
319 appearance={light ? "light" : "dark"}
320 />
321 </>
322 ) : null}
323
324 <View
325 pointerEvents="none"
326 className="absolute inset-x-0 items-center gap-3.5"
327 style={{ top: SCAN_RETICLE_TOP }}
328 >
329 <View
330 className={cn(
331 "items-center justify-center gap-2 border-continuous border-[3px]",
332 light ? "border-black/70" : "border-white/80",
333 )}
334 style={{
335 borderRadius: SCAN_RETICLE_RADIUS,
336 height: SCAN_RETICLE_SIZE,
337 width: SCAN_RETICLE_SIZE,
338 }}
339 >
340 {props.cameraActive ? null : (
341 <>
342 <SymbolView
343 name="qrcode.viewfinder"
344 size={44}
345 tintColorClassName={light ? "accent-black/60" : "accent-white/70"}
346 type="monochrome"
347 weight="light"
348 />
349 <Text
350 className={cn("font-t3-medium text-sm", light ? "text-black/70" : "text-white/80")}
351 >
352 Tap to scan
353 </Text>
354 </>
355 )}
356 </View>
357 <Text className={cn("text-center text-sm", light ? "text-black/70" : "text-white/80")}>
358 Scan the code from t3 pair or desktop Connections settings
359 </Text>
360 </View>
361 </Pressable>
362 );
363}
364
365function T3ConnectSection() {
366 const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
367 const navigation = useNavigation();
368 const { connectedEnvironments, onSetEnvironmentEnabled, onRemoveEnvironmentPress } =
369 useRemoteConnections();
370 const { connectedCloudEnvironments } = splitEnvironmentSections({
371 connectedEnvironments,
372 cloudEnvironments: null,
373 });
374
375 return (
376 <View collapsable={false} className="gap-2">
377 <Text className="px-4 text-sm font-t3-medium text-foreground-muted">
378 Or use the managed relay
379 </Text>
380 {isSignedIn ? (
381 <CloudEnvironmentRows
382 connectedCloudEnvironments={connectedCloudEnvironments}
383 onSetEnvironmentEnabled={onSetEnvironmentEnabled}
384 onRemoveEnvironment={onRemoveEnvironmentPress}
385 showHeader={false}
386 />
387 ) : (
388 <Pressable
389 accessibilityRole="button"
390 disabled={!isLoaded}
391 onPress={() => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" })}
392 className="min-h-13 flex-row items-center gap-3 rounded-[26px] border-continuous bg-grouped-card px-4 active:opacity-70"
393 >
394 <View className="min-w-0 flex-1 py-3">
395 <Text className="text-base text-foreground">Sign in to T3 Connect</Text>
396 <Text className="text-sm text-foreground-muted">
397 Reach your machines from anywhere, no network setup.
398 </Text>
399 </View>
400 <SymbolView
401 name="chevron.right"
402 size={14}
403 tintColorClassName="accent-chevron"
404 type="monochrome"
405 weight="semibold"
406 />
407 </Pressable>
408 )}
409 </View>
410 );
411}
412
413function PairingInputRow({
414 label,
415 ...inputProps
416}: Omit<AppTextInputProps, "accessibilityLabel" | "className"> & {
417 readonly label: string;
418}) {
419 return (
420 <View collapsable={false} className="h-13 flex-row items-center gap-3 px-4">
421 <Text
422 accessibilityElementsHidden
423 importantForAccessibility="no-hide-descendants"
424 className="w-20 text-base leading-[23px] text-foreground-muted"
425 >
426 {label}
427 </Text>
428 <AppTextInput
429 {...inputProps}
430 accessibilityLabel={label}
431 autoCapitalize="none"
432 autoCorrect={false}
433 className="min-h-0 flex-1 rounded-none border-0 bg-transparent p-0 text-base leading-[23px]"
434 />
435 </View>
436 );
437}