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

index.tsx

515 lines16.4 KB

1import { useAuth, useUser } from "@clerk/expo";
2import * as Notifications from "expo-notifications";
3import { Link, Stack, useRouter } from "expo-router";
4import { SymbolView } from "expo-symbols";
5import * as Effect from "effect/Effect";
6import { useCallback, useEffect, useMemo, useState } from "react";
7import type { ComponentProps, ReactNode } from "react";
8import { Alert, Linking, Pressable, ScrollView, Switch, View } from "react-native";
9import { useSafeAreaInsets } from "react-native-safe-area-context";
10​
11import {
12 isAtomCommandInterrupted,
13 reportAtomCommandResult,
14 settleAsyncResult,
15 settlePromise,
16 squashAtomCommandFailure,
17} from "@t3tools/client-runtime/state/runtime";
18import { AppText as Text } from "../../components/AppText";
19import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/liveActivityPreferences";
20import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions";
21import { refreshAgentAwarenessRegistration } from "../../features/agent-awareness/remoteRegistration";
22import { refreshManagedRelayEnvironments } from "../../features/cloud/managedRelayState";
23import { useClerkSettingsSheetDetent } from "../../features/cloud/ClerkSettingsSheetDetent";
24import {
25 hasCloudPublicConfig,
26 resolveRelayClerkTokenOptions,
27} from "../../features/cloud/publicConfig";
28import { runtime } from "../../lib/runtime";
29import { loadPreferences } from "../../lib/storage";
30import { useThemeColor } from "../../lib/useThemeColor";
31import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
32​
33type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
34type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
35​
36export default function SettingsRouteScreen() {
37 return hasCloudPublicConfig() ? <ConfiguredSettingsRouteScreen /> : <LocalSettingsRouteScreen />;
39​
40function LocalSettingsRouteScreen() {
41 const insets = useSafeAreaInsets();
42 const { savedConnectionsById } = useSavedRemoteConnections();
43 const environmentCount = Object.keys(savedConnectionsById).length;
44​
45 return (
46 <View collapsable={false} className="flex-1 bg-sheet">
47 <Stack.Screen options={{ title: "Settings" }} />
48 <ScrollView
49 contentInsetAdjustmentBehavior="automatic"
50 showsVerticalScrollIndicator={false}
51 style={{ flex: 1 }}
52 contentContainerStyle={{
53 gap: 24,
54 paddingBottom: Math.max(insets.bottom, 18) + 18,
55 paddingHorizontal: 20,
56 paddingTop: 16,
57 }}
58 >
59 <SettingsSection title="Configuration">
60 <SettingsRow
61 icon="desktopcomputer"
62 label="Environments"
63 value={`${environmentCount}`}
64 href="/settings/environments"
65 />
66 </SettingsSection>
67​
68 <ArchivedThreadsSettingsSection />
69​
70 <AppSettingsSection />
71 </ScrollView>
72 </View>
73 );
75​
76function ConfiguredSettingsRouteScreen() {
77 const insets = useSafeAreaInsets();
78 const { push } = useRouter();
79 const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
80 const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
81 const { user } = useUser();
82 const { savedConnectionsById } = useSavedRemoteConnections();
83 const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
84 const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
85​
86 const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
87 const environmentCount = connections.length;
88 const accountLabel = useMemo(() => {
89 if (!isLoaded) return "Checking";
90 if (!isSignedIn) return "Request access";
91 return user?.primaryEmailAddress?.emailAddress ?? "Signed in";
92 }, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]);
93​
94 const refreshNotifications = useCallback(async () => {
95 if (process.env.EXPO_OS !== "ios") {
96 setNotificationStatus("unsupported");
97 return;
98 }
99 const result = await settlePromise(() => Notifications.getPermissionsAsync());
100 if (result._tag === "Failure") {
101 reportAtomCommandResult(result, { label: "notification permission refresh" });
102 setNotificationStatus("disabled");
103 return;
104 }
105 setNotificationStatus(result.value.granted ? "enabled" : "disabled");
106 }, []);
107​
108 useEffect(() => {
109 void refreshNotifications();
110 }, [refreshNotifications]);
111​
112 useEffect(() => {
113 if (!isLoaded) {
114 setLiveActivityStatus("checking");
115 return;
116 }
117 if (!isSignedIn) {
118 setLiveActivityStatus("signed-out");
119 return;
120 }
121 void (async () => {
122 const result = await settlePromise(() => loadPreferences());
123 if (result._tag === "Failure") {
124 reportAtomCommandResult(result, { label: "live activity preference load" });
125 setLiveActivityStatus("enabled");
126 return;
127 }
128 setLiveActivityStatus(result.value.liveActivitiesEnabled === false ? "disabled" : "enabled");
129 })();
130 }, [isLoaded, isSignedIn]);
131​
132 const requestNotifications = useCallback(async () => {
133 const result = await settleAsyncResult(() =>
134 runtime.runPromiseExit(
135 requestAgentNotificationPermission.pipe(
136 Effect.tap((permission) =>
137 permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
138 ),
139 ),
140 ),
141 );
142 if (result._tag === "Failure") {
143 if (!isAtomCommandInterrupted(result)) {
144 const error = squashAtomCommandFailure(result);
145 Alert.alert(
146 "Notifications unavailable",
147 error instanceof Error ? error.message : "Could not request notification permission.",
148 );
149 }
150 return;
151 }
152 if (result.value.type === "granted") {
153 setNotificationStatus("enabled");
154 Alert.alert(
155 "Notifications enabled",
156 "Live Activity notifications are enabled for this device.",
157 );
158 return;
159 }
160 if (result.value.type === "unsupported") {
161 setNotificationStatus("unsupported");
162 Alert.alert(
163 "Notifications unavailable",
164 "Live Activity notifications are only available on iOS.",
165 );
166 return;
167 }
168 setNotificationStatus("disabled");
169 if (result.value.canAskAgain) {
170 Alert.alert("Notifications disabled", "Notifications were not enabled.");
171 return;
172 }
173 Alert.alert(
174 "Notifications disabled",
175 "Notifications were denied for this app. Open Settings to enable them.",
176 [
177 { text: "Cancel", style: "cancel" },
178 { text: "Open Settings", onPress: () => void Linking.openSettings() },
179 ],
180 );
181 }, []);
182​
183 const promptSignIn = useCallback(() => {
184 Alert.alert(
185 "Request T3 Cloud access",
186 "Live Activity updates require approved T3 Cloud access so relay can deliver updates to this device.",
187 [
188 { text: "Cancel", style: "cancel" },
189 { text: "Continue", onPress: () => push("/settings/waitlist") },
190 ],
191 );
192 }, [push]);
193​
194 const linkEnvironments = useCallback(async () => {
195 if (!isSignedIn) {
196 promptSignIn();
197 return;
198 }
199​
200 setLiveActivityStatus("linking");
201 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
202 if (tokenResult._tag === "Failure") {
203 setLiveActivityStatus("disabled");
204 const error = squashAtomCommandFailure(tokenResult);
205 Alert.alert(
206 "Live Activities unavailable",
207 error instanceof Error ? error.message : "Could not enable Live Activity updates.",
208 );
209 return;
210 }
211 if (!tokenResult.value) {
212 promptSignIn();
213 setLiveActivityStatus("signed-out");
214 return;
215 }
216​
217 const updateResult = await settleAsyncResult(() =>
218 runtime.runPromiseExit(
219 setLiveActivityUpdatesEnabled({
220 enabled: true,
221 clerkToken: tokenResult.value,
222 connections,
223 }),
224 ),
225 );
226 if (updateResult._tag === "Failure") {
227 setLiveActivityStatus("disabled");
228 if (!isAtomCommandInterrupted(updateResult)) {
229 const error = squashAtomCommandFailure(updateResult);
230 Alert.alert(
231 "Live Activities unavailable",
232 error instanceof Error ? error.message : "Could not enable Live Activity updates.",
233 );
234 }
235 return;
236 }
237​
238 refreshManagedRelayEnvironments();
239 setLiveActivityStatus("enabled");
240 Alert.alert(
241 "Live Activities enabled",
242 environmentCount > 0
243 ? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
244 : "Live Activity updates are enabled. Add an environment to start receiving updates.",
245 );
246 }, [connections, environmentCount, getToken, isSignedIn, promptSignIn]);
247​
248 const handleDeviceNotificationsChange = useCallback(
249 (enabled: boolean) => {
250 if (enabled) {
251 void requestNotifications();
252 return;
253 }
254​
255 Alert.alert(
256 "Disable notifications",
257 "Notification permission is controlled by iOS. Open Settings to disable notifications for T3 Code.",
258 [
259 { text: "Cancel", style: "cancel" },
260 { text: "Open Settings", onPress: () => void Linking.openSettings() },
261 ],
262 );
263 },
264 [requestNotifications],
265 );
266​
267 const handleLiveActivitiesChange = useCallback(
268 (enabled: boolean) => {
269 if (!enabled) {
270 setLiveActivityStatus("disabled");
271 void (async () => {
272 let token: string | null = null;
273 if (isSignedIn) {
274 const tokenResult = await settlePromise(() =>
275 getToken(resolveRelayClerkTokenOptions()),
276 );
277 if (tokenResult._tag === "Failure") {
278 reportAtomCommandResult(tokenResult, {
279 label: "live activity disable token lookup",
280 });
281 return;
282 }
283 token = tokenResult.value;
284 }
285​
286 const updateResult = await settleAsyncResult(() =>
287 runtime.runPromiseExit(
288 setLiveActivityUpdatesEnabled({
289 enabled: false,
290 clerkToken: token,
291 connections,
292 }),
293 ),
294 );
295 if (updateResult._tag === "Failure") {
296 reportAtomCommandResult(updateResult, {
297 label: "live activity disable",
298 });
299 return;
300 }
301 refreshManagedRelayEnvironments();
302 })();
303 return;
304 }
305​
306 if (!isSignedIn) {
307 promptSignIn();
308 return;
309 }
310​
311 void linkEnvironments();
312 },
313 [connections, getToken, isSignedIn, linkEnvironments, promptSignIn],
314 );
315​
316 const openAccount = useCallback(() => {
317 if (!isLoaded) return;
318 if (!isSignedIn) {
319 push("/settings/waitlist");
320 return;
321 }
322 expandClerkSheet();
323 push("/settings/auth");
324 }, [expandClerkSheet, isLoaded, isSignedIn, push]);
325​
326 return (
327 <View collapsable={false} className="flex-1 bg-sheet">
328 <Stack.Screen options={{ title: "Settings" }} />
329 <ScrollView
330 contentInsetAdjustmentBehavior="automatic"
331 showsVerticalScrollIndicator={false}
332 style={{ flex: 1 }}
333 contentContainerStyle={{
334 gap: 24,
335 paddingBottom: Math.max(insets.bottom, 18) + 18,
336 paddingHorizontal: 20,
337 paddingTop: 16,
338 }}
339 >
340 <View className="gap-3">
341 <SettingsSection title="Account">
342 <SettingsRow
343 icon="person.crop.circle"
344 label="T3 Account"
345 value={accountLabel}
346 onPress={openAccount}
347 />
348 </SettingsSection>
349 <Text className="px-2 text-sm leading-[18px] text-foreground-muted">
350 T3 Code works locally without signing in. Cloud features are optional.
351 </Text>
352 </View>
353​
354 <SettingsSection title="Configuration">
355 <SettingsRow
356 icon="desktopcomputer"
357 label="Environments"
358 value={`${environmentCount}`}
359 href="/settings/environments"
360 />
361 <SettingsSwitchRow
362 icon="bell.badge"
363 label="Device Notifications"
364 disabled={notificationStatus === "checking" || notificationStatus === "unsupported"}
365 value={notificationStatus === "enabled"}
366 onValueChange={handleDeviceNotificationsChange}
367 />
368 <SettingsSwitchRow
369 disabled={
370 !isLoaded || liveActivityStatus === "checking" || liveActivityStatus === "linking"
371 }
372 icon="bolt.circle"
373 label="Live Activity Updates"
374 value={liveActivityStatus === "enabled" || liveActivityStatus === "linking"}
375 onValueChange={handleLiveActivitiesChange}
376 />
377 </SettingsSection>
378​
379 <ArchivedThreadsSettingsSection />
380​
381 <AppSettingsSection />
382 </ScrollView>
383 </View>
384 );
386​
387type SymbolName = ComponentProps<typeof SymbolView>["name"];
388​
389function SettingsSection(props: { readonly title: string; readonly children: ReactNode }) {
390 return (
391 <View className="gap-2">
392 <Text className="px-2 text-sm font-t3-medium text-foreground-muted">{props.title}</Text>
393 <View
394 className="overflow-hidden rounded-[28px] bg-card"
395 style={{ borderCurve: "continuous" }}
396 >
397 {props.children}
398 </View>
399 </View>
400 );
402​
403function AppSettingsSection() {
404 const icon = useThemeColor("--color-icon");
405​
406 return (
407 <SettingsSection title="App">
408 <View className="flex-row items-center gap-4 p-4">
409 <SymbolView
410 name="info.circle"
411 size={22}
412 tintColor={icon}
413 type="monochrome"
414 weight="regular"
415 />
416 <Text className="flex-1 text-lg text-foreground">Version</Text>
417 <Text className="text-lg text-foreground-muted">Alpha</Text>
418 </View>
419 </SettingsSection>
420 );
422​
423function ArchivedThreadsSettingsSection() {
424 return (
425 <SettingsSection title="Threads">
426 <SettingsRow icon="archivebox" label="Archived Threads" href="/settings/archive" />
427 </SettingsSection>
428 );
430​
431function SettingsRow(props: {
432 readonly disabled?: boolean;
433 readonly icon: SymbolName;
434 readonly label: string;
435 readonly value?: string;
436 readonly href?: "/settings/archive" | "/settings/environments";
437 readonly onPress?: () => void;
438}) {
439 const icon = useThemeColor("--color-icon");
440 const chevron = useThemeColor("--color-chevron");
441 const content = (
442 <View
443 className="flex-row items-center gap-4 p-4"
444 style={{ opacity: props.disabled ? 0.45 : 1 }}
445 >
446 <SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
447 <Text className="shrink-0 text-lg text-foreground" numberOfLines={1}>
448 {props.label}
449 </Text>
450 <View className="min-w-0 flex-1 items-end">
451 {props.value ? (
452 <Text
453 className="max-w-[180px] text-right text-base text-foreground-muted"
454 ellipsizeMode="middle"
455 numberOfLines={1}
456 >
457 {props.value}
458 </Text>
459 ) : null}
460 </View>
461 <SymbolView
462 name="chevron.right"
463 size={16}
464 tintColor={chevron}
465 type="monochrome"
466 weight="semibold"
467 />
468 </View>
469 );
470​
471 if (props.href) {
472 return (
473 <Link href={props.href} asChild>
474 <Pressable accessibilityLabel={props.label} accessibilityRole="button">
475 {content}
476 </Pressable>
477 </Link>
478 );
479 }
480​
481 return (
482 <Pressable accessibilityRole="button" disabled={props.disabled} onPress={props.onPress}>
483 {content}
484 </Pressable>
485 );
487​
488function SettingsSwitchRow(props: {
489 readonly disabled?: boolean;
490 readonly icon: SymbolName;
491 readonly label: string;
492 readonly value: boolean;
493 readonly onValueChange: (value: boolean) => void;
494}) {
495 const icon = useThemeColor("--color-icon");
496 const activeTrack = String(useThemeColor("--color-switch-active"));
497 const track = String(useThemeColor("--color-secondary-border"));
498​
499 return (
500 <View
501 className="flex-row items-center gap-4 p-4"
502 style={{ opacity: props.disabled ? 0.45 : 1 }}
503 >
504 <SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
505 <Text className="flex-1 text-lg text-foreground">{props.label}</Text>
506 <Switch
507 disabled={props.disabled}
508 ios_backgroundColor={track}
509 onValueChange={props.onValueChange}
510 trackColor={{ false: track, true: activeTrack }}
511 value={props.value}
512 />
513 </View>
514 );