Open History to see the last commit
1import { findErrorTraceId } from "@t3tools/client-runtime/errors";
2import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import type { MenuAction } from "@react-native-menu/menu";
7import type { EnvironmentId } from "@t3tools/contracts";
8import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
9import { type ReactNode, useRef, useState } from "react";
10import { Pressable, RefreshControl, ScrollView, Text, View } from "react-native";
11
12import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
13import { SymbolView } from "../../components/ui/AppSymbol";
14import * as Dialog from "../../components/ui/Dialog";
15import { Menu } from "../../components/ui/Menu";
16import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
17import { useAtomCommand } from "../../state/use-atom-command";
18import {
19 deregisterManagedRelayEnvironmentCommand,
20 useManagedRelayEnvironments,
21} from "./managedRelayState";
22
23const linkedAtFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
24
25function linkedAtLabel(value: string): string {
26 const linkedAt = new Date(value);
27 return Number.isNaN(linkedAt.getTime())
28 ? "Link date unavailable"
29 : `Linked ${linkedAtFormatter.format(linkedAt)}`;
30}
31
32function endpointLabel(environment: RelayClientEnvironmentRecord): string {
33 return environment.endpoint.providerKind === "cloudflare_tunnel"
34 ? "Managed tunnel"
35 : "Activity publishing only";
36}
37
38function confirmDeregister(environment: RelayClientEnvironmentRecord, onConfirm: () => void) {
39 const title = "Deregister server?";
40 const message = `“${environment.label}” will be removed from this account. T3 Connect access will be revoked, any managed tunnel will be removed, and a host space will become available. Local connections on your devices are not changed.`;
41 Dialog.confirm({ title, message, confirmText: "Deregister", destructive: true, onConfirm });
42}
43
44export function T3ConnectProfilePage() {
45 const environmentsState = useManagedRelayEnvironments();
46 const deregisterEnvironment = useAtomCommand(deregisterManagedRelayEnvironmentCommand, {
47 reportFailure: false,
48 });
49 const [deregisteringEnvironmentId, setDeregisteringEnvironmentId] =
50 useState<EnvironmentId | null>(null);
51 const mutationPendingRef = useRef(false);
52 // Hide cached rows by linkedAt until refresh; re-linking changes linkedAt and restores visibility.
53 const [removedEnvironments, setRemovedEnvironments] = useState<{
54 readonly accountId: string | null;
55 readonly linkedAtById: ReadonlyMap<EnvironmentId, string>;
56 }>({ accountId: null, linkedAtById: new Map() });
57
58 const handleDeregister = async (environment: RelayClientEnvironmentRecord) => {
59 const accountId = environmentsState.accountId;
60 if (!accountId || mutationPendingRef.current) return;
61
62 mutationPendingRef.current = true;
63 setDeregisteringEnvironmentId(environment.environmentId);
64 const result = await deregisterEnvironment({
65 accountId,
66 environmentId: environment.environmentId,
67 });
68 mutationPendingRef.current = false;
69 setDeregisteringEnvironmentId(null);
70
71 if (result._tag === "Success") {
72 setRemovedEnvironments((current) => {
73 const linkedAtById = new Map(current.accountId === accountId ? current.linkedAtById : []);
74 linkedAtById.set(environment.environmentId, environment.linkedAt);
75 return { accountId, linkedAtById };
76 });
77 environmentsState.refresh();
78 return;
79 }
80 if (isAtomCommandInterrupted(result)) return;
81
82 const cause = squashAtomCommandFailure(result);
83 const message = cause instanceof Error ? cause.message : "Could not deregister the server.";
84 const traceId = findErrorTraceId(cause);
85 console.error("[t3-connect] Could not deregister environment", {
86 environmentId: environment.environmentId,
87 message,
88 traceId,
89 cause,
90 });
91 Dialog.alert(
92 "Could not deregister server",
93 traceId ? `${message}\n\nTrace ID: ${traceId}` : message,
94 traceId
95 ? [
96 {
97 text: "Copy trace ID",
98 onPress: () => copyTextWithHaptic(traceId, { target: "connection-trace-id" }),
99 },
100 { text: "OK", style: "cancel" },
101 ]
102 : undefined,
103 );
104 };
105
106 const removedEnvironmentLinkedAt =
107 removedEnvironments.accountId === environmentsState.accountId
108 ? removedEnvironments.linkedAtById
109 : new Map<EnvironmentId, string>();
110 const environments = (environmentsState.data ?? []).filter(
111 (environment) =>
112 removedEnvironmentLinkedAt.get(environment.environmentId) !== environment.linkedAt,
113 );
114 const isInitialLoad =
115 !environmentsState.accountId || (environmentsState.data === null && !environmentsState.error);
116 const errorTraceId = environmentsState.errorTraceId;
117
118 return (
119 <ScrollView
120 className="flex-1 bg-clerk-page"
121 contentContainerClassName="pb-8"
122 contentInsetAdjustmentBehavior="automatic"
123 refreshControl={
124 <RefreshControl
125 refreshing={environmentsState.isPending && environmentsState.data !== null}
126 onRefresh={environmentsState.refresh}
127 />
128 }
129 >
130 <ClerkSectionHeader>Registered servers</ClerkSectionHeader>
131
132 {environmentsState.error ? (
133 <>
134 <ClerkRow
135 title="Could not load T3 Connect environments"
136 subtitle={environmentsState.error}
137 />
138 {errorTraceId ? (
139 <ClerkButtonRow
140 label="Copy trace ID"
141 onPress={() => {
142 copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
143 }}
144 />
145 ) : null}
146 </>
147 ) : isInitialLoad ? (
148 <View className="flex-row items-center gap-3 px-6 py-4">
149 <AppActivityIndicator colorClassName={"accent-clerk-foreground-muted"} size="small" />
150 <Text className="text-base text-clerk-foreground-muted">Loading environments</Text>
151 </View>
152 ) : environments.length > 0 ? (
153 environments.map((environment) => (
154 <ClerkRow
155 key={environment.environmentId}
156 title={environment.label}
157 subtitle={`${linkedAtLabel(environment.linkedAt)} · ${endpointLabel(environment)}`}
158 accessory={
159 deregisteringEnvironmentId === environment.environmentId ? (
160 <AppActivityIndicator
161 colorClassName={"accent-clerk-foreground-muted"}
162 size="small"
163 />
164 ) : (
165 <Menu
166 actions={ENVIRONMENT_MENU_ACTIONS}
167 isAnchoredToRight
168 onPressAction={() =>
169 confirmDeregister(environment, () => void handleDeregister(environment))
170 }
171 >
172 <Pressable
173 accessibilityLabel={`Actions for ${environment.label}`}
174 accessibilityRole="button"
175 disabled={deregisteringEnvironmentId !== null}
176 className="size-[30px] items-center justify-center active:opacity-60 disabled:opacity-50"
177 >
178 <View className="rotate-90">
179 <SymbolView
180 name="ellipsis"
181 size={18}
182 tintColorClassName={"accent-clerk-foreground-muted"}
183 type="monochrome"
184 />
185 </View>
186 </Pressable>
187 </Menu>
188 )
189 }
190 />
191 ))
192 ) : (
193 <ClerkRow
194 title="No servers registered"
195 subtitle="Link a server from its local Settings to reach it through T3 Connect."
196 />
197 )}
198
199 <Text className="px-6 pt-6 text-xs leading-normal text-clerk-foreground-muted">
200 Connections on this device are managed in Settings.
201 </Text>
202 </ScrollView>
203 );
204}
205
206const ENVIRONMENT_MENU_ACTIONS = [
207 { id: "deregister", title: "Deregister", image: "trash", attributes: { destructive: true } },
208] satisfies MenuAction[];
209
210function ClerkSectionHeader(props: { readonly children: string }) {
211 return (
212 <Text className="min-h-4 border-b border-clerk-border px-6 pt-8 pb-4 text-xs font-medium tracking-[0.3px] text-clerk-foreground-muted uppercase">
213 {props.children}
214 </Text>
215 );
216}
217
218function ClerkRow(props: {
219 readonly title: string;
220 readonly subtitle: string;
221 readonly accessory?: ReactNode;
222}) {
223 return (
224 <View
225 collapsable={false}
226 className="flex-row items-center gap-3 border-b border-clerk-border px-6 py-4"
227 >
228 <View className="min-w-0 flex-1 gap-0.5">
229 <Text className="min-h-[22px] text-base text-clerk-foreground" numberOfLines={1}>
230 {props.title}
231 </Text>
232 <Text className="min-h-5 text-sm text-clerk-foreground-muted" numberOfLines={2}>
233 {props.subtitle}
234 </Text>
235 </View>
236 {props.accessory}
237 </View>
238 );
239}
240
241function ClerkButtonRow(props: { readonly label: string; readonly onPress: () => void }) {
242 return (
243 <Pressable
244 accessibilityRole="button"
245 onPress={props.onPress}
246 className="border-b border-clerk-border px-6 py-4 active:opacity-60"
247 >
248 <Text className="text-base font-semibold text-clerk-foreground">{props.label}</Text>
249 </Pressable>
250 );
251}