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

ConnectionsNewRouteScreen.tsx

424 lines14.1 KB

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