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 // Deregistered rows stay in the cached list until the refresh lands, so hide
53 // them by the linkedAt they had. A re-link produces a new linkedAt and shows again.
54 const [removedEnvironments, setRemovedEnvironments] = useState<{
55 readonly accountId: string | null;
56 readonly linkedAtById: ReadonlyMap<EnvironmentId, string>;
57 }>({ accountId: null, linkedAtById: new Map() });
58
59 const handleDeregister = async (environment: RelayClientEnvironmentRecord) => {
60 const accountId = environmentsState.accountId;
61 if (!accountId || mutationPendingRef.current) return;
62
63 mutationPendingRef.current = true;
64 setDeregisteringEnvironmentId(environment.environmentId);
65 const result = await deregisterEnvironment({
66 accountId,
67 environmentId: environment.environmentId,
68 });
69 mutationPendingRef.current = false;
70 setDeregisteringEnvironmentId(null);
71
72 if (result._tag === "Success") {
73 setRemovedEnvironments((current) => {
74 const linkedAtById = new Map(current.accountId === accountId ? current.linkedAtById : []);
75 linkedAtById.set(environment.environmentId, environment.linkedAt);
76 return { accountId, linkedAtById };
77 });
78 environmentsState.refresh();
79 return;
80 }
81 if (isAtomCommandInterrupted(result)) return;
82
83 const cause = squashAtomCommandFailure(result);
84 const message = cause instanceof Error ? cause.message : "Could not deregister the server.";
85 const traceId = findErrorTraceId(cause);
86 console.error("[t3-connect] Could not deregister environment", {
87 environmentId: environment.environmentId,
88 message,
89 traceId,
90 cause,
91 });
92 Dialog.alert(
93 "Could not deregister server",
94 traceId ? `${message}\n\nTrace ID: ${traceId}` : message,
95 traceId
96 ? [
97 {
98 text: "Copy trace ID",
99 onPress: () => copyTextWithHaptic(traceId, { target: "connection-trace-id" }),
100 },
101 { text: "OK", style: "cancel" },
102 ]
103 : undefined,
104 );
105 };
106
107 const removedEnvironmentLinkedAt =
108 removedEnvironments.accountId === environmentsState.accountId
109 ? removedEnvironments.linkedAtById
110 : new Map<EnvironmentId, string>();
111 const environments = (environmentsState.data ?? []).filter(
112 (environment) =>
113 removedEnvironmentLinkedAt.get(environment.environmentId) !== environment.linkedAt,
114 );
115 const isInitialLoad =
116 !environmentsState.accountId || (environmentsState.data === null && !environmentsState.error);
117 const errorTraceId = environmentsState.errorTraceId;
118
119 return (
120 <ScrollView
121 className="flex-1 bg-clerk-page"
122 contentContainerClassName="pb-8"
123 contentInsetAdjustmentBehavior="automatic"
124 refreshControl={
125 <RefreshControl
126 refreshing={environmentsState.isPending && environmentsState.data !== null}
127 onRefresh={environmentsState.refresh}
128 />
129 }
130 >
131 <ClerkSectionHeader>Registered servers</ClerkSectionHeader>
132
133 {environmentsState.error ? (
134 <>
135 <ClerkRow
136 title="Could not load T3 Connect environments"
137 subtitle={environmentsState.error}
138 />
139 {errorTraceId ? (
140 <ClerkButtonRow
141 label="Copy trace ID"
142 onPress={() => {
143 copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
144 }}
145 />
146 ) : null}
147 </>
148 ) : isInitialLoad ? (
149 <View className="flex-row items-center gap-3 px-6 py-4">
150 <AppActivityIndicator colorClassName={"accent-clerk-foreground-muted"} size="small" />
151 <Text className="text-base text-clerk-foreground-muted">Loading environments</Text>
152 </View>
153 ) : environments.length > 0 ? (
154 environments.map((environment) => (
155 <ClerkRow
156 key={environment.environmentId}
157 title={environment.label}
158 subtitle={`${linkedAtLabel(environment.linkedAt)} · ${endpointLabel(environment)}`}
159 accessory={
160 deregisteringEnvironmentId === environment.environmentId ? (
161 <AppActivityIndicator
162 colorClassName={"accent-clerk-foreground-muted"}
163 size="small"
164 />
165 ) : (
166 <Menu
167 actions={ENVIRONMENT_MENU_ACTIONS}
168 isAnchoredToRight
169 onPressAction={() =>
170 confirmDeregister(environment, () => void handleDeregister(environment))
171 }
172 >
173 <Pressable
174 accessibilityLabel={`Actions for ${environment.label}`}
175 accessibilityRole="button"
176 disabled={deregisteringEnvironmentId !== null}
177 className="size-[30px] items-center justify-center active:opacity-60 disabled:opacity-50"
178 >
179 <View className="rotate-90">
180 <SymbolView
181 name="ellipsis"
182 size={18}
183 tintColorClassName={"accent-clerk-foreground-muted"}
184 type="monochrome"
185 />
186 </View>
187 </Pressable>
188 </Menu>
189 )
190 }
191 />
192 ))
193 ) : (
194 <ClerkRow
195 title="No servers registered"
196 subtitle="Link a server from its local Settings to reach it through T3 Connect."
197 />
198 )}
199
200 <Text className="px-6 pt-6 text-xs leading-normal text-clerk-foreground-muted">
201 Connections on this device are managed in Settings.
202 </Text>
203 </ScrollView>
204 );
205}
206
207const ENVIRONMENT_MENU_ACTIONS = [
208 { id: "deregister", title: "Deregister", image: "trash", attributes: { destructive: true } },
209] satisfies MenuAction[];
210
211function ClerkSectionHeader(props: { readonly children: string }) {
212 return (
213 <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">
214 {props.children}
215 </Text>
216 );
217}
218
219function ClerkRow(props: {
220 readonly title: string;
221 readonly subtitle: string;
222 readonly accessory?: ReactNode;
223}) {
224 return (
225 <View
226 collapsable={false}
227 className="flex-row items-center gap-3 border-b border-clerk-border px-6 py-4"
228 >
229 <View className="min-w-0 flex-1 gap-0.5">
230 <Text className="min-h-[22px] text-base text-clerk-foreground" numberOfLines={1}>
231 {props.title}
232 </Text>
233 <Text className="min-h-5 text-sm text-clerk-foreground-muted" numberOfLines={2}>
234 {props.subtitle}
235 </Text>
236 </View>
237 {props.accessory}
238 </View>
239 );
240}
241
242function ClerkButtonRow(props: { readonly label: string; readonly onPress: () => void }) {
243 return (
244 <Pressable
245 accessibilityRole="button"
246 onPress={props.onPress}
247 className="border-b border-clerk-border px-6 py-4 active:opacity-60"
248 >
249 <Text className="text-base font-semibold text-clerk-foreground">{props.label}</Text>
250 </Pressable>
251 );
252}