@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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