Open History to see the last commit
1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import { T, useGT } from "gt-react-native";
3import { ListRow } from "../../components/ui/ListRow";
4import * as Dialog from "../../components/ui/Dialog";
5import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
6import { useAuth } from "@clerk/expo";
7import { CameraView, useCameraPermissions } from "expo-camera";
8import * as Haptics from "expo-haptics";
9import {
10 StackActions,
11 useIsFocused,
12 useNavigation,
13 type StaticScreenProps,
14} from "@react-navigation/native";
15import type { EnvironmentId } from "@t3tools/contracts";
16import { useAtomValue } from "@effect/atom-react";
17import { useState } from "react";
18import { Linking, Pressable, StyleSheet, View } from "react-native";
19import Svg, { Defs, RadialGradient, Rect, Stop } from "react-native-svg";
20import { useSafeAreaInsets } from "react-native-safe-area-context";
21import { cn } from "../../lib/cn";
22import { useUniwindTheme } from "../../lib/useUniwindTheme";
23import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
24import { SettingsScreen } from "../settings/components/SettingsScreen";
25import { AppText as Text, AppTextInput, type AppTextInputProps } from "../../components/ui/AppText";
26import { FrostedCutout } from "../../components/ui/FrostedCutout";
27import { buildPairingUrl, extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
28import { useRemoteConnections } from "../../state/use-remote-environment-registry";
29import { SymbolView } from "../../components/ui/AppSymbol";
30import { hasCloudPublicConfig } from "../cloud/publicConfig";
31import { CloudEnvironmentRows } from "./CloudEnvironmentRows";
32import { autoConnectReport, devAutoConnectAttemptAtom } from "./devAutoConnect";
33import { splitEnvironmentSections } from "./environmentSections";
34import { leaveSettingsPage } from "../settings/settings-navigation";
35import { workspaceHasColumns } from "../layout/workspace/workspace-selection-store";
36import { m } from "../../i18n/messages";
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 params = route.params ?? {};
49 // Dev-only prefill prevents production links from supplying an attacker-chosen host and token.
50 const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";
51 // A new prefill link replaces whatever the form held.
52 return (
53 <PairingForm
54 key={routePairingUrl}
55 routePairingUrl={routePairingUrl}
56 routeFor={params.routeFor}
57 />
58 );
59}
60
61function PairingForm({
62 routePairingUrl,
63 routeFor,
64}: {
65 readonly routePairingUrl: string;
66 readonly routeFor: EnvironmentId | undefined;
67}) {
68 const gt = useGT();
69 const { connectionPairingUrl, onChangeConnectionPairingUrl, onConnectPress } =
70 useRemoteConnections();
71 const navigation = useNavigation();
72 const insets = useSafeAreaInsets();
73 const [initialPairing] = useState(() => parsePairingUrl(routePairingUrl || connectionPairingUrl));
74 const [hostInput, setHostInput] = useState(initialPairing.host);
75 const [codeInput, setCodeInput] = useState(initialPairing.code);
76 const [isSubmitting, setIsSubmitting] = useState(false);
77 const [submitError, setSubmitError] = useState<string | null>(null);
78 // The user's own edit or submit dismisses the dev auto-connect report.
79 const [ownAttempt, setOwnAttempt] = useState(false);
80 const autoConnect = autoConnectReport(
81 useAtomValue(devAutoConnectAttemptAtom),
82 routePairingUrl,
83 ownAttempt,
84 );
85 const connecting = isSubmitting || autoConnect.connecting;
86 const pairingConnectionError = submitError ?? autoConnect.error;
87 const [cameraPermission, requestCameraPermission] = useCameraPermissions();
88 const screenFocused = useIsFocused();
89 const [scannerLocked, setScannerLocked] = useState(false);
90 // A good scan parks the camera so it can't re-read the code over later edits.
91 const [scanComplete, setScanComplete] = useState(false);
92
93 const headerIconColor = useUniwindTheme()["--color-icon"];
94
95 const connectDisabled = connecting || hostInput.trim().length === 0;
96
97 const clearError = () => {
98 setSubmitError(null);
99 setOwnAttempt(true);
100 };
101
102 const handleHostChange = (value: string) => {
103 const pairing = parsePairingUrl(value);
104 if (pairing.code) {
105 setHostInput(pairing.host);
106 setCodeInput(pairing.code);
107 } else {
108 setHostInput(value);
109 }
110 clearError();
111 };
112
113 const handleCodeChange = (value: string) => {
114 setCodeInput(value);
115 clearError();
116 };
117
118 const handleScanPress = async () => {
119 const permission = await requestCameraPermission();
120 if (permission.granted) {
121 setScanComplete(false);
122 return;
123 }
124 if (permission.canAskAgain) return;
125 Dialog.alert(
126 gt("Camera access needed"),
127 gt("Camera access was denied for this app. Open Settings to enable it."),
128 [
129 { text: gt("Cancel"), style: "cancel" },
130 { text: gt("Open Settings"), onPress: () => void Linking.openSettings() },
131 ],
132 );
133 };
134
135 const handleQrScan = ({ data }: { readonly data: string }) => {
136 if (scannerLocked) {
137 return;
138 }
139
140 setScannerLocked(true);
141
142 try {
143 const pairingUrl = extractPairingUrlFromQrPayload(data);
144 const { host, code } = parsePairingUrl(pairingUrl);
145 setHostInput(host);
146 setCodeInput(code);
147 onChangeConnectionPairingUrl(pairingUrl);
148 setScanComplete(true);
149 setScannerLocked(false);
150 } catch (error) {
151 void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
152 Dialog.alert(
153 gt("Invalid QR code"),
154 error instanceof Error
155 ? (errorDisplayMessage(error, m) ?? error.message)
156 : gt("Scanned QR code was not recognized."),
157 );
158 setTimeout(() => {
159 setScannerLocked(false);
160 }, 600);
161 }
162 };
163
164 const handleSubmit = async () => {
165 const pairingUrl = buildPairingUrl(hostInput, codeInput);
166 setOwnAttempt(true);
167 setSubmitError(null);
168 setIsSubmitting(true);
169 onChangeConnectionPairingUrl(pairingUrl);
170 const outcome = await onConnectPress(pairingUrl, routeFor);
171 setIsSubmitting(false);
172 setSubmitError(outcome.error);
173 void Haptics.notificationAsync(
174 outcome.ok
175 ? Haptics.NotificationFeedbackType.Success
176 : Haptics.NotificationFeedbackType.Error,
177 );
178 if (outcome.ok) {
179 // Replacing with Home would nest it inside any sheet below; return to the opener.
180 if (!navigation.canGoBack()) {
181 navigation.dispatch(StackActions.replace("Home"));
182 } else {
183 // Added from the Settings list, the new environment shows on Environments.
184 leaveSettingsPage(navigation, workspaceHasColumns(), "SettingsEnvironments");
185 }
186 }
187 };
188
189 return (
190 <SettingsScreen
191 title={gt("Add environment")}
192 actions={[
193 {
194 accessibilityLabel: connecting
195 ? gt("Connecting", { $context: "connection status" })
196 : gt("Add environment"),
197 loading: connecting,
198 icon: "checkmark",
199 tintColor: headerIconColor,
200 disabled: connectDisabled,
201 onPress: () => {
202 void handleSubmit();
203 },
204 },
205 ]}
206 >
207 <ScrollView
208 nestedScrollEnabled
209 contentInsetAdjustmentBehavior="automatic"
210 keyboardShouldPersistTaps="handled"
211 showsVerticalScrollIndicator={false}
212 className="flex-1"
213 contentContainerStyle={{
214 paddingHorizontal: 16,
215 paddingTop: 4,
216 paddingBottom: Math.max(insets.bottom, 18) + 18,
217 }}
218 >
219 <View collapsable={false} className="gap-6.5">
220 <PairingScanCard
221 cameraActive={cameraPermission?.granted === true && screenFocused && !scanComplete}
222 onScan={handleQrScan}
223 onScanPress={() => {
224 void handleScanPress();
225 }}
226 />
227
228 <View collapsable={false} className="gap-2">
229 <Text className="px-4 text-sm font-t3-medium text-foreground-muted">
230 <T>Or enter it</T>
231 </Text>
232 <View
233 collapsable={false}
234 className={cn(
235 "overflow-hidden rounded-[26px] border-continuous border bg-grouped-card",
236 pairingConnectionError ? "border-danger-foreground" : "border-transparent",
237 )}
238 >
239 <PairingInputRow
240 label={gt("Address")}
241 keyboardType="url"
242 placeholder="192.168.1.100:3773"
243 value={hostInput}
244 onChangeText={handleHostChange}
245 />
246 <View className="ml-4 border-t border-border-subtle" />
247 <PairingInputRow
248 label={gt("Code", { $context: "pairing code field" })}
249 placeholder={gt("Pairing code")}
250 returnKeyType="go"
251 value={codeInput}
252 onChangeText={handleCodeChange}
253 onSubmitEditing={() => {
254 if (!connectDisabled) void handleSubmit();
255 }}
256 />
257 </View>
258 <Text
259 accessibilityLiveRegion="polite"
260 className={cn(
261 "px-4 text-sm leading-normal",
262 pairingConnectionError ? "text-danger-foreground" : "text-foreground-muted",
263 )}
264 >
265 {pairingConnectionError ??
266 gt(
267 "For machines on your local network or tailnet. The machine keeps its own provider credentials.",
268 )}
269 </Text>
270 </View>
271
272 {hasCloudPublicConfig() ? <T3ConnectSection /> : null}
273 </View>
274 </ScrollView>
275 </SettingsScreen>
276 );
277}
278
279const SCAN_CARD_HEIGHT = 250;
280const SCAN_RETICLE_SIZE = 150;
281const SCAN_RETICLE_TOP = 36;
282const SCAN_RETICLE_RADIUS = 28;
283
284function PairingScanCard(props: {
285 readonly cameraActive: boolean;
286 readonly onScan: (result: { readonly data: string }) => void;
287 readonly onScanPress: () => void;
288}) {
289 const gt = useGT();
290 const light = useAppearancePreferences().themeAppearance === "light";
291 return (
292 <Pressable
293 accessibilityRole={props.cameraActive ? undefined : "button"}
294 accessibilityLabel={props.cameraActive ? undefined : gt("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 <T>Tap to scan</T>
360 </Text>
361 </>
362 )}
363 </View>
364 <Text className={cn("text-center text-sm", light ? "text-black/70" : "text-white/80")}>
365 {gt("Scan the code from {command} or desktop Connections settings", {
366 command: "t3 pair",
367 })}
368 </Text>
369 </View>
370 </Pressable>
371 );
372}
373
374function T3ConnectSection() {
375 const gt = useGT();
376 const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
377 const navigation = useNavigation();
378 const { connectedEnvironments, onSetEnvironmentEnabled, onRemoveEnvironmentPress } =
379 useRemoteConnections();
380 const { connectedCloudEnvironments } = splitEnvironmentSections({
381 connectedEnvironments,
382 cloudEnvironments: null,
383 });
384
385 return (
386 <View collapsable={false} className="gap-2">
387 <Text className="px-4 text-sm font-t3-medium text-foreground-muted">
388 <T>Or use the managed relay</T>
389 </Text>
390 {isSignedIn ? (
391 <CloudEnvironmentRows
392 connectedCloudEnvironments={connectedCloudEnvironments}
393 onSetEnvironmentEnabled={onSetEnvironmentEnabled}
394 onRemoveEnvironment={onRemoveEnvironmentPress}
395 showHeader={false}
396 />
397 ) : (
398 <ListRow
399 label={gt("Sign in to {product}", { product: "T3 Connect" })}
400 description={gt("Reach your machines from anywhere, no network setup.")}
401 disabled={!isLoaded}
402 onPress={() => navigation.navigate("SettingsAuth")}
403 />
404 )}
405 </View>
406 );
407}
408
409function PairingInputRow({
410 label,
411 ...inputProps
412}: Omit<AppTextInputProps, "accessibilityLabel" | "className"> & {
413 readonly label: string;
414}) {
415 return (
416 <View collapsable={false} className="h-13 flex-row items-center gap-3 px-4">
417 <Text
418 accessibilityElementsHidden
419 importantForAccessibility="no-hide-descendants"
420 className="w-20 text-base leading-[23px] text-foreground-muted"
421 >
422 {label}
423 </Text>
424 <AppTextInput
425 {...inputProps}
426 accessibilityLabel={label}
427 autoCapitalize="none"
428 autoCorrect={false}
429 className="min-h-0 flex-1 rounded-none border-0 bg-transparent p-0 text-base leading-[23px]"
430 />
431 </View>
432 );
433}