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

ConnectionsNewRouteScreen.tsx

457 lines15.6 KB

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