Skip to content

Commit 0f21fcb

Browse files
feat(mobile): add a T3 Connect page to the Clerk profile (#11765)
Co-authored-by: Claude Fable 5.1 <[email protected]>
1 parent bcc2024 commit 0f21fcb

6 files changed

Lines changed: 374 additions & 12 deletions

File tree

‎apps/mobile/global.css‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,31 @@
233233
}
234234
}
235235

236+
/* ─── Clerk native profile ──────────────────────────────────────────── */
237+
/* Fixed palette for custom pages inside Clerk's native user profile. Mirrors
238+
clerk-theme.json, which themes the SDK's own screens, so ours match them.
239+
Kept out of the runtime palette above on purpose: custom themes must not
240+
restyle Clerk's chrome. Keep in sync with clerk-theme.json. */
241+
@layer theme {
242+
:root {
243+
@variant light {
244+
--color-clerk-page: #f2f2f7;
245+
--color-clerk-foreground: #262626;
246+
--color-clerk-foreground-muted: #737373;
247+
--color-clerk-border: rgba(229, 229, 234, 0.06);
248+
--color-clerk-danger: #dc2626;
249+
}
250+
251+
@variant dark {
252+
--color-clerk-page: #0e0e0e;
253+
--color-clerk-foreground: #f5f5f5;
254+
--color-clerk-foreground-muted: #a3a3a3;
255+
--color-clerk-border: rgba(42, 42, 42, 0.06);
256+
--color-clerk-danger: #fca5a5;
257+
}
258+
}
259+
}
260+
236261
/* ─── Typography ────────────────────────────────────────────────────── */
237262
@theme {
238263
/* Keep these native family names aligned with app.config.ts. */
Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
2+
import {
3+
isAtomCommandInterrupted,
4+
squashAtomCommandFailure,
5+
} from "@t3tools/client-runtime/state/runtime";
6+
import type { MenuAction } from "@react-native-menu/menu";
7+
import type { EnvironmentId } from "@t3tools/contracts";
8+
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
9+
import { type ReactNode, useRef, useState } from "react";
10+
import {
11+
ActivityIndicator,
12+
Alert,
13+
Pressable,
14+
RefreshControl,
15+
ScrollView,
16+
Text,
17+
View,
18+
} from "react-native";
19+
20+
import { SymbolView } from "../../components/AppSymbol";
21+
import { showConfirmDialog } from "../../components/ConfirmDialogHost";
22+
import { ControlPillMenu } from "../../components/ControlPill";
23+
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
24+
import { useAtomCommand } from "../../state/use-atom-command";
25+
import {
26+
deregisterManagedRelayEnvironmentCommand,
27+
useManagedRelayEnvironments,
28+
} from "./managedRelayState";
29+
30+
const linkedAtFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
31+
32+
function linkedAtLabel(value: string): string {
33+
const linkedAt = new Date(value);
34+
return Number.isNaN(linkedAt.getTime())
35+
? "Link date unavailable"
36+
: `Linked ${linkedAtFormatter.format(linkedAt)}`;
37+
}
38+
39+
function endpointLabel(environment: RelayClientEnvironmentRecord): string {
40+
return environment.endpoint.providerKind === "cloudflare_tunnel"
41+
? "Managed tunnel"
42+
: "Activity publishing only";
43+
}
44+
45+
function confirmDeregister(environment: RelayClientEnvironmentRecord, onConfirm: () => void) {
46+
const title = "Deregister server?";
47+
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.`;
48+
if (process.env.EXPO_OS === "ios") {
49+
Alert.alert(title, message, [
50+
{ text: "Cancel", style: "cancel" },
51+
{ text: "Deregister", style: "destructive", onPress: onConfirm },
52+
]);
53+
return;
54+
}
55+
showConfirmDialog({ title, message, confirmText: "Deregister", destructive: true, onConfirm });
56+
}
57+
58+
/**
59+
* The "T3 Connect" custom page inside Clerk's native user profile: every
60+
* environment registered to the signed-in account, with account-level
61+
* deregistration. Mirrors the web UserButton page; connections on this device
62+
* are managed in Settings instead.
63+
*/
64+
export function T3ConnectProfilePage() {
65+
const environmentsState = useManagedRelayEnvironments();
66+
const deregisterEnvironment = useAtomCommand(deregisterManagedRelayEnvironmentCommand, {
67+
reportFailure: false,
68+
});
69+
const [deregisteringEnvironmentId, setDeregisteringEnvironmentId] =
70+
useState<EnvironmentId | null>(null);
71+
const mutationPendingRef = useRef(false);
72+
// Deregistered rows stay in the cached list until the refresh lands, so hide
73+
// them by the linkedAt they had. A re-link produces a new linkedAt and shows again.
74+
const [removedEnvironments, setRemovedEnvironments] = useState<{
75+
readonly accountId: string | null;
76+
readonly linkedAtById: ReadonlyMap<EnvironmentId, string>;
77+
}>({ accountId: null, linkedAtById: new Map() });
78+
79+
const handleDeregister = async (environment: RelayClientEnvironmentRecord) => {
80+
const accountId = environmentsState.accountId;
81+
if (!accountId || mutationPendingRef.current) return;
82+
83+
mutationPendingRef.current = true;
84+
setDeregisteringEnvironmentId(environment.environmentId);
85+
const result = await deregisterEnvironment({
86+
accountId,
87+
environmentId: environment.environmentId,
88+
});
89+
mutationPendingRef.current = false;
90+
setDeregisteringEnvironmentId(null);
91+
92+
if (result._tag === "Success") {
93+
setRemovedEnvironments((current) => {
94+
const linkedAtById = new Map(current.accountId === accountId ? current.linkedAtById : []);
95+
linkedAtById.set(environment.environmentId, environment.linkedAt);
96+
return { accountId, linkedAtById };
97+
});
98+
environmentsState.refresh();
99+
return;
100+
}
101+
if (isAtomCommandInterrupted(result)) return;
102+
103+
const cause = squashAtomCommandFailure(result);
104+
const message = cause instanceof Error ? cause.message : "Could not deregister the server.";
105+
const traceId = findErrorTraceId(cause);
106+
console.error("[t3-connect] Could not deregister environment", {
107+
environmentId: environment.environmentId,
108+
message,
109+
traceId,
110+
cause,
111+
});
112+
Alert.alert(
113+
"Could not deregister server",
114+
traceId ? `${message}\n\nTrace ID: ${traceId}` : message,
115+
traceId
116+
? [
117+
{
118+
text: "Copy trace ID",
119+
onPress: () => copyTextWithHaptic(traceId, { target: "connection-trace-id" }),
120+
},
121+
{ text: "OK", style: "cancel" },
122+
]
123+
: undefined,
124+
);
125+
};
126+
127+
const removedEnvironmentLinkedAt =
128+
removedEnvironments.accountId === environmentsState.accountId
129+
? removedEnvironments.linkedAtById
130+
: new Map<EnvironmentId, string>();
131+
const environments = (environmentsState.data ?? []).filter(
132+
(environment) =>
133+
removedEnvironmentLinkedAt.get(environment.environmentId) !== environment.linkedAt,
134+
);
135+
const isInitialLoad =
136+
!environmentsState.accountId || (environmentsState.data === null && !environmentsState.error);
137+
const errorTraceId = environmentsState.errorTraceId;
138+
139+
return (
140+
<ScrollView
141+
className="flex-1 bg-clerk-page"
142+
contentContainerClassName="pb-8"
143+
contentInsetAdjustmentBehavior="automatic"
144+
refreshControl={
145+
<RefreshControl
146+
refreshing={environmentsState.isPending && environmentsState.data !== null}
147+
onRefresh={environmentsState.refresh}
148+
/>
149+
}
150+
>
151+
<ClerkSectionHeader>Registered servers</ClerkSectionHeader>
152+
153+
{environmentsState.error ? (
154+
<>
155+
<ClerkRow
156+
title="Could not load T3 Connect environments"
157+
subtitle={environmentsState.error}
158+
/>
159+
{errorTraceId ? (
160+
<ClerkButtonRow
161+
label="Copy trace ID"
162+
onPress={() => {
163+
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
164+
}}
165+
/>
166+
) : null}
167+
</>
168+
) : isInitialLoad ? (
169+
<View className="flex-row items-center gap-3 px-6 py-4">
170+
<ActivityIndicator colorClassName={"accent-clerk-foreground-muted"} size="small" />
171+
<Text className="text-base text-clerk-foreground-muted">Loading environments</Text>
172+
</View>
173+
) : environments.length > 0 ? (
174+
environments.map((environment) => (
175+
<ClerkRow
176+
key={environment.environmentId}
177+
title={environment.label}
178+
subtitle={`${linkedAtLabel(environment.linkedAt)} · ${endpointLabel(environment)}`}
179+
accessory={
180+
deregisteringEnvironmentId === environment.environmentId ? (
181+
<ActivityIndicator colorClassName={"accent-clerk-foreground-muted"} size="small" />
182+
) : (
183+
<ControlPillMenu
184+
actions={ENVIRONMENT_MENU_ACTIONS}
185+
isAnchoredToRight
186+
onPressAction={() =>
187+
confirmDeregister(environment, () => void handleDeregister(environment))
188+
}
189+
>
190+
<Pressable
191+
accessibilityLabel={`Actions for ${environment.label}`}
192+
accessibilityRole="button"
193+
disabled={deregisteringEnvironmentId !== null}
194+
className="size-[30px] items-center justify-center active:opacity-60 disabled:opacity-50"
195+
>
196+
<View className="rotate-90">
197+
<SymbolView
198+
name="ellipsis"
199+
size={18}
200+
tintColorClassName={"accent-clerk-foreground-muted"}
201+
type="monochrome"
202+
/>
203+
</View>
204+
</Pressable>
205+
</ControlPillMenu>
206+
)
207+
}
208+
/>
209+
))
210+
) : (
211+
<ClerkRow
212+
title="No servers registered"
213+
subtitle="Link a server from its local Settings to reach it through T3 Connect."
214+
/>
215+
)}
216+
217+
<Text className="px-6 pt-6 text-xs leading-normal text-clerk-foreground-muted">
218+
Connections on this device are managed in Settings.
219+
</Text>
220+
</ScrollView>
221+
);
222+
}
223+
224+
const ENVIRONMENT_MENU_ACTIONS = [
225+
{ id: "deregister", title: "Deregister", image: "trash", attributes: { destructive: true } },
226+
] satisfies MenuAction[];
227+
228+
// Layout primitives that mirror clerk-ios ClerkKitUI's profile rows so a custom
229+
// page reads as one of Clerk's own screens. System font on purpose: Clerk's
230+
// native views do not use the app's DM Sans.
231+
232+
function ClerkSectionHeader(props: { readonly children: string }) {
233+
return (
234+
<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">
235+
{props.children}
236+
</Text>
237+
);
238+
}
239+
240+
function ClerkRow(props: {
241+
readonly title: string;
242+
readonly subtitle: string;
243+
readonly accessory?: ReactNode;
244+
}) {
245+
return (
246+
<View
247+
collapsable={false}
248+
className="flex-row items-center gap-3 border-b border-clerk-border px-6 py-4"
249+
>
250+
<View className="min-w-0 flex-1 gap-0.5">
251+
<Text className="min-h-[22px] text-base text-clerk-foreground" numberOfLines={1}>
252+
{props.title}
253+
</Text>
254+
<Text className="min-h-5 text-sm text-clerk-foreground-muted" numberOfLines={2}>
255+
{props.subtitle}
256+
</Text>
257+
</View>
258+
{props.accessory}
259+
</View>
260+
);
261+
}
262+
263+
function ClerkButtonRow(props: { readonly label: string; readonly onPress: () => void }) {
264+
return (
265+
<Pressable
266+
accessibilityRole="button"
267+
onPress={props.onPress}
268+
className="border-b border-clerk-border px-6 py-4 active:opacity-60"
269+
>
270+
<Text className="text-base font-semibold text-clerk-foreground">{props.label}</Text>
271+
</Pressable>
272+
);
273+
}

‎apps/mobile/src/features/cloud/managedRelayState.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
import { useAtomValue } from "@effect/atom-react";
22
import {
33
createManagedRelayQueryManager,
4+
deregisterManagedRelayEnvironment,
45
managedRelaySessionAtom,
56
readManagedRelaySnapshotState,
67
} from "@t3tools/client-runtime/relay";
8+
import {
9+
createAtomCommandScheduler,
10+
createRuntimeCommand,
11+
} from "@t3tools/client-runtime/state/runtime";
12+
import type { EnvironmentId } from "@t3tools/contracts";
713
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
814
import { AsyncResult, Atom } from "effect/unstable/reactivity";
915
import { useCallback, useEffect } from "react";
@@ -19,6 +25,22 @@ export const managedRelayQueryManager = createManagedRelayQueryManager(managedRe
1925
cloudDebugLog(`query:${event.operation}:${event.stage}:${event.phase}`, { ...event }),
2026
});
2127

28+
const managedRelayMutationScheduler = createAtomCommandScheduler();
29+
30+
export const deregisterManagedRelayEnvironmentCommand = createRuntimeCommand(
31+
managedRelayAtomRuntime,
32+
{
33+
label: "mobile:managed-relay:deregister-environment",
34+
scheduler: managedRelayMutationScheduler,
35+
concurrency: {
36+
mode: "serial",
37+
key: (input: { readonly accountId: string; readonly environmentId: EnvironmentId }) =>
38+
input.accountId,
39+
},
40+
execute: (input, registry) => deregisterManagedRelayEnvironment(registry, input),
41+
},
42+
);
43+
2244
const EMPTY_ENVIRONMENTS_ATOM = Atom.make(
2345
AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
2446
).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environments:null"));

‎apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,21 @@
11
import { useAuth } from "@clerk/expo";
2-
import { AuthView, UserProfileView } from "@clerk/expo/native";
2+
import { AuthView, type UserProfileCustomPage, UserProfileView } from "@clerk/expo/native";
33
import { StackActions, useNavigation } from "@react-navigation/native";
44
import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
55
import { View } from "react-native";
66

77
import { hasCloudPublicConfig } from "../cloud/publicConfig";
8+
import { T3ConnectProfilePage } from "../cloud/T3ConnectProfilePage";
9+
10+
// Custom rows in Clerk's native profile. Mirrors the web UserButton pages.
11+
const USER_PROFILE_CUSTOM_PAGES = [
12+
{
13+
path: "t3-connect",
14+
label: "T3 Connect",
15+
icon: "globe",
16+
content: <T3ConnectProfilePage />,
17+
},
18+
] satisfies UserProfileCustomPage[];
819

920
export function SettingsAuthRouteScreen() {
1021
const navigation = useNavigation();
@@ -40,7 +51,11 @@ function ConfiguredSettingsAuthRouteScreen() {
4051
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
4152
{isLoaded ? (
4253
hasBeenSignedIn.current ? (
43-
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
54+
<UserProfileView
55+
customPages={USER_PROFILE_CUSTOM_PAGES}
56+
isDismissible={false}
57+
onHostBack={handleHostBack}
58+
/>
4459
) : (
4560
<AuthView isDismissible={false} onHostBack={handleHostBack} />
4661
)

0 commit comments

Comments
 (0)