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

ConnectionsNewRouteScreen.tsx

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