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