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

ConnectionsNewRouteScreen.tsx

444 lines15.0 KB

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 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 = useCallback((value: string) => {
99 setHostInput(value);
100 setPendingConnectionError(null);
101 }, []);
102​
103 const handleCodeChange = useCallback((value: string) => {
104 setCodeInput(value);
105 setPendingConnectionError(null);
106 }, []);
107​
108 useEffect(() => () => setPendingConnectionError(null), []);
109​
110 const handleScanPress = useCallback(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 }, [requestCameraPermission]);
126​
127 const handleQrScan = useCallback(
128 ({ data }: { readonly data: string }) => {
129 if (scannerLocked) {
130 return;
131 }
132​
133 setScannerLocked(true);
134​
135 try {
136 const pairingUrl = extractPairingUrlFromQrPayload(data);
137 const { host, code } = parsePairingUrl(pairingUrl);
138 setHostInput(host);
139 setCodeInput(code);
140 onChangeConnectionPairingUrl(pairingUrl);
141 setScanComplete(true);
142 setScannerLocked(false);
143 } catch (error) {
144 void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
145 Dialog.alert(
146 "Invalid QR code",
147 error instanceof Error ? error.message : "Scanned QR code was not recognized.",
148 );
149 setTimeout(() => {
150 setScannerLocked(false);
151 }, 600);
152 }
153 },
154 [onChangeConnectionPairingUrl, scannerLocked],
155 );
156​
157 const connectAndClose = useCallback(
158 async (pairingUrl: string, replaceWithHome: boolean) => {
159 setIsSubmitting(true);
160 onChangeConnectionPairingUrl(pairingUrl);
161 try {
162 const result = await onConnectPress(pairingUrl, params.routeFor);
163 void Haptics.notificationAsync(
164 AsyncResult.isSuccess(result)
165 ? Haptics.NotificationFeedbackType.Success
166 : Haptics.NotificationFeedbackType.Error,
167 );
168 if (AsyncResult.isSuccess(result)) {
169 if (replaceWithHome || !navigation.canGoBack()) {
170 navigation.dispatch(StackActions.replace("Home"));
171 } else {
172 navigation.goBack();
173 }
174 }
175 } finally {
176 setIsSubmitting(false);
177 }
178 },
179 [navigation, onChangeConnectionPairingUrl, onConnectPress, params.routeFor],
180 );
181​
182 const handleSubmit = useCallback(async () => {
183 await connectAndClose(buildPairingUrl(hostInput, codeInput), false);
184 }, [codeInput, connectAndClose, hostInput]);
185​
186 useEffect(() => {
187 if (!shouldAutoConnect || attemptedAutoConnectRef.current === routePairingUrl) {
188 return;
189 }
190​
191 attemptedAutoConnectRef.current = routePairingUrl;
192 void connectAndClose(routePairingUrl, true);
193 }, [connectAndClose, routePairingUrl, shouldAutoConnect]);
194​
195 return (
196 <SettingsScreen
197 formSheet={routeName === "ConnectionsNew"}
198 title="Add environment"
199 actions={[
200 {
201 accessibilityLabel: isSubmitting ? "Connecting" : "Add environment",
202 loading: isSubmitting,
203 icon: "checkmark",
204 tintColor: headerIconColor,
205 disabled: connectDisabled,
206 onPress: () => {
207 void handleSubmit();
208 },
209 },
210 ]}
211 >
212 <ScrollView
213 nestedScrollEnabled
214 contentInsetAdjustmentBehavior="automatic"
215 keyboardShouldPersistTaps="handled"
216 showsVerticalScrollIndicator={false}
217 className="flex-1"
218 contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
219 contentContainerStyle={{
220 paddingHorizontal: 16,
221 paddingTop: 4,
222 }}
223 >
224 <View collapsable={false} className="gap-6.5">
225 <PairingScanCard
226 cameraActive={cameraPermission?.granted === true && screenFocused && !scanComplete}
227 onScan={handleQrScan}
228 onScanPress={() => {
229 void handleScanPress();
230 }}
231 />
232​
233 <View collapsable={false} className="gap-2">
234 <Text className="px-4 text-sm font-t3-medium text-foreground-muted">Or enter it</Text>
235 <View
236 collapsable={false}
237 className={cn(
238 "overflow-hidden rounded-[26px] border-continuous border bg-grouped-card",
239 pairingConnectionError ? "border-danger-foreground" : "border-transparent",
240 )}
241 >
242 <PairingInputRow
243 label="Address"
244 keyboardType="url"
245 placeholder="192.168.1.100:3773"
246 value={hostInput}
247 onChangeText={handleHostChange}
248 />
249 <View className="ml-4 border-t border-border-subtle" />
250 <PairingInputRow
251 label="Code"
252 placeholder="Pairing code"
253 returnKeyType="go"
254 value={codeInput}
255 onChangeText={handleCodeChange}
256 onSubmitEditing={() => {
257 if (!connectDisabled) void handleSubmit();
258 }}
259 />
260 </View>
261 <Text
262 accessibilityLiveRegion="polite"
263 className={cn(
264 "px-4 text-sm leading-normal",
265 pairingConnectionError ? "text-danger-foreground" : "text-foreground-muted",
266 )}
267 >
268 {pairingConnectionError ??
269 "For machines on your local network or tailnet. The machine keeps its own provider credentials."}
270 </Text>
271 </View>
272​
273 {hasCloudPublicConfig() ? <T3ConnectSection /> : null}
274 </View>
275 </ScrollView>
276 </SettingsScreen>
277 );
279​
280const SCAN_CARD_HEIGHT = 250;
281const SCAN_RETICLE_SIZE = 150;
282const SCAN_RETICLE_TOP = 36;
283const SCAN_RETICLE_RADIUS = 28;
284​
285function PairingScanCard(props: {
286 readonly cameraActive: boolean;
287 readonly onScan: (result: { readonly data: string }) => void;
288 readonly onScanPress: () => void;
289}) {
290 const light = useAppearancePreferences().themeAppearance === "light";
291 return (
292 <Pressable
293 accessibilityRole={props.cameraActive ? undefined : "button"}
294 accessibilityLabel={props.cameraActive ? undefined : "Scan QR code"}
295 disabled={props.cameraActive}
296 onPress={props.onScanPress}
297 className={cn(
298 "overflow-hidden rounded-[26px] border-continuous",
299 light ? "bg-white" : "bg-black",
300 )}
301 style={{ height: SCAN_CARD_HEIGHT }}
302 >
303 <Svg accessibilityElementsHidden height="100%" style={StyleSheet.absoluteFill} width="100%">
304 <Defs>
305 <RadialGradient id="pairing-scan-backdrop" cx="50%" cy="50%" r="50%">
306 <Stop offset="0%" stopColor={light ? "#f4f4f5" : "#2e2e2e"} />
307 <Stop offset="100%" stopColor={light ? "#d9d9dc" : "#0e0e0e"} />
308 </RadialGradient>
309 </Defs>
310 <Rect fill="url(#pairing-scan-backdrop)" height="100%" width="100%" />
311 </Svg>
312​
313 {props.cameraActive ? (
314 <>
315 <CameraView
316 active
317 barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
318 onBarcodeScanned={props.onScan}
319 style={StyleSheet.absoluteFill}
320 />
321 <FrostedCutout
322 cutoutTop={SCAN_RETICLE_TOP}
323 cutoutWidth={SCAN_RETICLE_SIZE}
324 cutoutHeight={SCAN_RETICLE_SIZE}
325 cutoutRadius={SCAN_RETICLE_RADIUS}
326 appearance={light ? "light" : "dark"}
327 />
328 </>
329 ) : null}
330​
331 <View
332 pointerEvents="none"
333 className="absolute inset-x-0 items-center gap-3.5"
334 style={{ top: SCAN_RETICLE_TOP }}
335 >
336 <View
337 className={cn(
338 "items-center justify-center gap-2 border-continuous border-[3px]",
339 light ? "border-black/70" : "border-white/80",
340 )}
341 style={{
342 borderRadius: SCAN_RETICLE_RADIUS,
343 height: SCAN_RETICLE_SIZE,
344 width: SCAN_RETICLE_SIZE,
345 }}
346 >
347 {props.cameraActive ? null : (
348 <>
349 <SymbolView
350 name="qrcode.viewfinder"
351 size={44}
352 tintColorClassName={light ? "accent-black/60" : "accent-white/70"}
353 type="monochrome"
354 weight="light"
355 />
356 <Text
357 className={cn("font-t3-medium text-sm", light ? "text-black/70" : "text-white/80")}
358 >
359 Tap to scan
360 </Text>
361 </>
362 )}
363 </View>
364 <Text className={cn("text-center text-sm", light ? "text-black/70" : "text-white/80")}>
365 Scan the code from t3 pair or desktop Connections settings
366 </Text>
367 </View>
368 </Pressable>
369 );
371​
372function T3ConnectSection() {
373 const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
374 const navigation = useNavigation();
375 const { connectedEnvironments, onSetEnvironmentEnabled, onRemoveEnvironmentPress } =
376 useRemoteConnections();
377 const { connectedCloudEnvironments } = splitEnvironmentSections({
378 connectedEnvironments,
379 cloudEnvironments: null,
380 });
381​
382 return (
383 <View collapsable={false} className="gap-2">
384 <Text className="px-4 text-sm font-t3-medium text-foreground-muted">
385 Or use the managed relay
386 </Text>
387 {isSignedIn ? (
388 <CloudEnvironmentRows
389 connectedCloudEnvironments={connectedCloudEnvironments}
390 onSetEnvironmentEnabled={onSetEnvironmentEnabled}
391 onRemoveEnvironment={onRemoveEnvironmentPress}
392 showHeader={false}
393 />
394 ) : (
395 <Pressable
396 accessibilityRole="button"
397 disabled={!isLoaded}
398 onPress={() => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" })}
399 className="min-h-13 flex-row items-center gap-3 rounded-[26px] border-continuous bg-grouped-card px-4 active:opacity-70"
400 >
401 <View className="min-w-0 flex-1 py-3">
402 <Text className="text-base text-foreground">Sign in to T3 Connect</Text>
403 <Text className="text-sm text-foreground-muted">
404 Reach your machines from anywhere, no network setup.
405 </Text>
406 </View>
407 <SymbolView
408 name="chevron.right"
409 size={14}
410 tintColorClassName="accent-chevron"
411 type="monochrome"
412 weight="semibold"
413 />
414 </Pressable>
415 )}
416 </View>
417 );
419​
420function PairingInputRow({
421 label,
422 ...inputProps
423}: Omit<AppTextInputProps, "accessibilityLabel" | "className"> & {
424 readonly label: string;
425}) {
426 return (
427 <View collapsable={false} className="h-13 flex-row items-center gap-3 px-4">
428 <Text
429 accessibilityElementsHidden
430 importantForAccessibility="no-hide-descendants"
431 className="w-20 text-base leading-[23px] text-foreground-muted"
432 >
433 {label}
434 </Text>
435 <AppTextInput
436 {...inputProps}
437 accessibilityLabel={label}
438 autoCapitalize="none"
439 autoCorrect={false}
440 className="min-h-0 flex-1 rounded-none border-0 bg-transparent p-0 text-base leading-[23px]"
441 />
442 </View>
443 );