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

T3ConnectProfilePage.tsx

289 lines10.4 KB

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