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