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