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

ConnectionsNewRouteScreen.tsx

455 lines15.8 KB

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