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

ConnectionsNewRouteScreen.tsx

446 lines15.6 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={linked ? gt`Connect to ${{ environment: linked.label }}` : gt`Add environment`}
204 actions={[
205 {
206 accessibilityLabel: connecting
207 ? gt({ context: "connection status" })`Connecting`
208 : gt`Add environment`,
209 loading: connecting,
210 icon: "checkmark",
211 tintColor: headerIconColor,
212 disabled: connectDisabled,
213 onPress: () => {
214 void handleSubmit();
215 },
216 },
217 ]}
218 >
219 <ScrollView
220 nestedScrollEnabled
221 contentInsetAdjustmentBehavior="automatic"
222 automaticallyAdjustKeyboardInsets
223 keyboardShouldPersistTaps="handled"
224 showsVerticalScrollIndicator={false}
225 className="flex-1"
226 contentContainerStyle={{
227 paddingHorizontal: 16,
228 paddingTop: 4,
229 paddingBottom: Math.max(insets.bottom, 18) + 18,
230 }}
231 >
232 <View collapsable={false} className="gap-6.5">
233 <PairingScanCard
234 cameraActive={cameraPermission?.granted === true && screenFocused && !scanComplete}
235 onScan={handleQrScan}
236 onScanPress={() => {
237 void handleScanPress();
238 }}
239 />
240​
241 <View collapsable={false} className="gap-2">
242 <Text className="px-4 text-sm font-t3-medium text-foreground-muted">
243 <T>Or enter it</T>
244 </Text>
245 <View
246 collapsable={false}
247 className={cn(
248 "overflow-hidden rounded-[26px] border-continuous border bg-grouped-card",
249 pairingConnectionError ? "border-danger-foreground" : "border-transparent",
250 )}
251 >
252 <PairingInputRow
253 label={gt`Address`}
254 keyboardType="url"
255 placeholder="192.168.1.100:3773"
256 value={hostInput}
257 onChangeText={handleHostChange}
258 />
259 <View className="ml-4 border-t border-border-subtle" />
260 <PairingInputRow
261 label={gt({ context: "pairing code field" })`Code`}
262 placeholder={gt`Pairing code`}
263 returnKeyType="go"
264 value={codeInput}
265 onChangeText={handleCodeChange}
266 onSubmitEditing={() => {
267 if (!connectDisabled) void handleSubmit();
268 }}
269 />
270 </View>
271 <Text
272 accessibilityLiveRegion="polite"
273 className={cn(
274 "px-4 text-sm leading-normal",
275 pairingConnectionError ? "text-danger-foreground" : "text-foreground-muted",
276 )}
277 >
278 {pairingConnectionError ??
279 (linked
280 ? gt`Create a pairing code on ${{ environment: linked.label }}, in its Settings → Sharing & access or with \`t3 auth pairing create\`, and enter it here.`
281 : gt`For machines on your local network or tailnet. The machine keeps its own provider credentials.`)}
282 </Text>
283 </View>
284​
285 {hasCloudPublicConfig() ? <T3ConnectSection /> : null}
286 </View>
287 </ScrollView>
288 </SettingsScreen>
289 );
291​
292const SCAN_CARD_HEIGHT = 250;
293const SCAN_RETICLE_SIZE = 150;
294const SCAN_RETICLE_TOP = 36;
295const SCAN_RETICLE_RADIUS = 28;
296​
297function PairingScanCard(props: {
298 readonly cameraActive: boolean;
299 readonly onScan: (result: { readonly data: string }) => void;
300 readonly onScanPress: () => void;
301}) {
302 const gt = useGT();
303 const light = useAppearancePreferences().themeAppearance === "light";
304 return (
305 <Pressable
306 accessibilityRole={props.cameraActive ? undefined : "button"}
307 accessibilityLabel={props.cameraActive ? undefined : gt`Scan QR code`}
308 disabled={props.cameraActive}
309 onPress={props.onScanPress}
310 className={cn(
311 "overflow-hidden rounded-[26px] border-continuous",
312 light ? "bg-white" : "bg-black",
313 )}
314 style={{ height: SCAN_CARD_HEIGHT }}
315 >
316 <Svg accessibilityElementsHidden height="100%" style={StyleSheet.absoluteFill} width="100%">
317 <Defs>
318 <RadialGradient id="pairing-scan-backdrop" cx="50%" cy="50%" r="50%">
319 <Stop offset="0%" stopColor={light ? "#f4f4f5" : "#2e2e2e"} />
320 <Stop offset="100%" stopColor={light ? "#d9d9dc" : "#0e0e0e"} />
321 </RadialGradient>
322 </Defs>
323 <Rect fill="url(#pairing-scan-backdrop)" height="100%" width="100%" />
324 </Svg>
325​
326 {props.cameraActive ? (
327 <>
328 <CameraView
329 active
330 barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
331 onBarcodeScanned={props.onScan}
332 style={StyleSheet.absoluteFill}
333 />
334 <FrostedCutout
335 cutoutTop={SCAN_RETICLE_TOP}
336 cutoutWidth={SCAN_RETICLE_SIZE}
337 cutoutHeight={SCAN_RETICLE_SIZE}
338 cutoutRadius={SCAN_RETICLE_RADIUS}
339 appearance={light ? "light" : "dark"}
340 />
341 </>
342 ) : null}
343​
344 <View
345 pointerEvents="none"
346 className="absolute inset-x-0 items-center gap-3.5"
347 style={{ top: SCAN_RETICLE_TOP }}
348 >
349 <View
350 className={cn(
351 "items-center justify-center gap-2 border-continuous border-[3px]",
352 light ? "border-black/70" : "border-white/80",
353 )}
354 style={{
355 borderRadius: SCAN_RETICLE_RADIUS,
356 height: SCAN_RETICLE_SIZE,
357 width: SCAN_RETICLE_SIZE,
358 }}
359 >
360 {props.cameraActive ? null : (
361 <>
362 <SymbolView
363 name="qrcode.viewfinder"
364 size={44}
365 tintColorClassName={light ? "accent-black/60" : "accent-white/70"}
366 type="monochrome"
367 weight="light"
368 />
369 <Text
370 className={cn("font-t3-medium text-sm", light ? "text-black/70" : "text-white/80")}
371 >
372 <T>Tap to scan</T>
373 </Text>
374 </>
375 )}
376 </View>
377 <Text className={cn("text-center text-sm", light ? "text-black/70" : "text-white/80")}>
378 {gt`Scan the code from ${{ command: "t3 pair" }} or desktop Connections settings`}
379 </Text>
380 </View>
381 </Pressable>
382 );
384​
385function T3ConnectSection() {
386 const gt = useGT();
387 const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
388 const navigation = useNavigation();
389 const { connectedEnvironments, onSetEnvironmentEnabled, onRemoveEnvironmentPress } =
390 useRemoteConnections();
391 const { connectedCloudEnvironments } = splitEnvironmentSections({
392 connectedEnvironments,
393 cloudEnvironments: null,
394 });
395​
396 return (
397 <View collapsable={false} className="gap-2">
398 <Text className="px-4 text-sm font-t3-medium text-foreground-muted">
399 <T>Or use the managed relay</T>
400 </Text>
401 {isSignedIn ? (
402 <CloudEnvironmentRows
403 connectedCloudEnvironments={connectedCloudEnvironments}
404 onSetEnvironmentEnabled={onSetEnvironmentEnabled}
405 onRemoveEnvironment={onRemoveEnvironmentPress}
406 showHeader={false}
407 />
408 ) : (
409 <ListRow
410 label={gt`Sign in to ${{ product: "T3 Connect" }}`}
411 description={gt`Reach your machines from anywhere, no network setup.`}
412 disabled={!isLoaded}
413 onPress={() => navigation.navigate("SettingsAuth")}
414 />
415 )}
416 </View>
417 );
419​
420function PairingInputRow({
421 label,
422 ...inputProps
423}: Omit<AppTextInputProps, "accessibilityLabel" | "className"> & {
424 readonly label: string;
425}) {
426 return (
427 <View collapsable={false} className="min-h-[48px] flex-row items-center gap-3 px-4">
428 <Text
429 accessibilityElementsHidden
430 importantForAccessibility="no-hide-descendants"
431 className="w-20 text-base leading-[23px] text-foreground-muted"
432 >
433 {label}
434 </Text>
435 <AppTextInput
436 {...inputProps}
437 accessibilityLabel={label}
438 autoCapitalize="none"
439 autoCorrect={false}
440 lineBreakModeIOS="middle"
441 textAlignVertical="center"
442 className="min-h-[48px] flex-1 self-stretch rounded-none border-0 bg-transparent p-0 text-base leading-[23px]"
443 />
444 </View>
445 );