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