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

T3ConnectProfilePage.tsx

256 lines9.5 KB

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