Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { EnvironmentId } from "@t3tools/contracts";
3import * as Cause from "effect/Cause";
4import { AsyncResult, Atom } from "effect/unstable/reactivity";
5import { useCallback, useMemo } from "react";
6import { Alert } from "react-native";
7
8import { useConnectionController } from "../features/connection/useConnectionController";
9import { environmentPresentations } from "./presentation";
10import { useWorkspaceState } from "../state/workspace";
11import type { SavedRemoteConnection } from "../lib/connection";
12import { appAtomRegistry } from "./atom-registry";
13import type { ConnectedEnvironmentSummary, EnvironmentRuntimeState } from "./remote-runtime-types";
14import { environmentSession } from "./session";
15import { environmentCatalog } from "../connection/catalog";
16import { createRemoteEnvironmentProjectionAtoms } from "./remote-environment-projections";
17import { serverEnvironment } from "./server";
18
19const connectionPairingUrlAtom = Atom.make("").pipe(
20 Atom.keepAlive,
21 Atom.withLabel("mobile:connection-pairing-url"),
22);
23
24const pendingConnectionErrorAtom = Atom.make<string | null>(null).pipe(
25 Atom.keepAlive,
26 Atom.withLabel("mobile:pending-connection-error"),
27);
28
29export function setPendingConnectionError(message: string | null): void {
30 appAtomRegistry.set(pendingConnectionErrorAtom, message);
31}
32
33const remoteEnvironmentProjections = createRemoteEnvironmentProjectionAtoms({
34 presentationAtom: environmentPresentations.presentationAtom,
35 preparedConnectionAtom: environmentSession.preparedConnectionValueAtom,
36 serverConfigAtom: serverEnvironment.configValueAtom,
37});
38
39const EMPTY_SAVED_CONNECTION_ATOM = Atom.make<SavedRemoteConnection | null>(null).pipe(
40 Atom.withLabel("mobile:saved-connection:empty"),
41);
42
43const EMPTY_RUNTIME_STATE_ATOM = Atom.make<EnvironmentRuntimeState | null>(null).pipe(
44 Atom.withLabel("mobile:environment-runtime-state:empty"),
45);
46
47const savedConnectionsByIdAtom = Atom.make((get) => {
48 const presentationById = get(environmentPresentations.presentationsAtom);
49 return Object.fromEntries(
50 [...presentationById.keys()].flatMap((environmentId) => {
51 const connection = get(remoteEnvironmentProjections.savedConnectionAtom(environmentId));
52 return connection === null ? [] : [[environmentId, connection]];
53 }),
54 ) as Record<EnvironmentId, SavedRemoteConnection>;
55}).pipe(Atom.withLabel("mobile:saved-connections-by-id"));
56
57export function useSavedRemoteConnections() {
58 const catalog = useAtomValue(environmentCatalog.catalogValueAtom);
59 const savedConnectionsById = useAtomValue(savedConnectionsByIdAtom);
60
61 return {
62 isLoadingSavedConnection: !catalog.isReady,
63 savedConnectionsById,
64 };
65}
66
67export function useSavedRemoteConnection(
68 environmentId: EnvironmentId | null,
69): SavedRemoteConnection | null {
70 return useAtomValue(
71 environmentId === null
72 ? EMPTY_SAVED_CONNECTION_ATOM
73 : remoteEnvironmentProjections.savedConnectionAtom(environmentId),
74 );
75}
76
77export function useRemoteEnvironmentRuntime(
78 environmentId: EnvironmentId | null,
79): EnvironmentRuntimeState | null {
80 return useAtomValue(
81 environmentId === null
82 ? EMPTY_RUNTIME_STATE_ATOM
83 : remoteEnvironmentProjections.runtimeStateAtom(environmentId),
84 );
85}
86
87export function useRemoteConnectionStatus() {
88 const workspace = useWorkspaceState();
89 const pendingConnectionError = useAtomValue(pendingConnectionErrorAtom);
90 const connectedEnvironments = useMemo<ReadonlyArray<ConnectedEnvironmentSummary>>(
91 () =>
92 workspace.environments.map((environment) => ({
93 environmentId: environment.environmentId,
94 environmentLabel: environment.environmentLabel,
95 displayUrl: environment.displayUrl,
96 isRelayManaged: environment.isRelayManaged,
97 isEnabled: environment.isEnabled,
98 connectionState: environment.connectionState,
99 connectionError: environment.connectionError,
100 connectionErrorTraceId: environment.connectionErrorTraceId,
101 })),
102 [workspace.environments],
103 );
104
105 return {
106 connectedEnvironments,
107 connectionState: workspace.state.connectionState,
108 connectionError: pendingConnectionError ?? workspace.state.connectionError,
109 };
110}
111
112export function useRemoteConnections() {
113 const controller = useConnectionController();
114 const connectionPairingUrl = useAtomValue(connectionPairingUrlAtom);
115 const pendingConnectionError = useAtomValue(pendingConnectionErrorAtom);
116 const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
117
118 const onChangeConnectionPairingUrl = useCallback((pairingUrl: string) => {
119 appAtomRegistry.set(connectionPairingUrlAtom, pairingUrl);
120 }, []);
121
122 const onConnectPress = useCallback(
123 async (pairingUrl?: string) => {
124 const nextPairingUrl = pairingUrl ?? connectionPairingUrl;
125 setPendingConnectionError(null);
126 const result = await controller.connectPairingUrl(nextPairingUrl);
127 if (AsyncResult.isFailure(result)) {
128 const error = Cause.squash(result.cause);
129 const message =
130 error instanceof Error ? error.message : "Failed to pair with the environment.";
131 if (
132 error !== null &&
133 typeof error === "object" &&
134 "reason" in error &&
135 error.reason === "unsupported"
136 ) {
137 Alert.alert("Client not supported", message);
138 } else {
139 setPendingConnectionError(message);
140 }
141 } else {
142 appAtomRegistry.set(connectionPairingUrlAtom, "");
143 }
144 return result;
145 },
146 [connectionPairingUrl, controller],
147 );
148
149 const onReconnectEnvironment = useCallback(
150 (environmentId: EnvironmentId) => controller.retryEnvironment(environmentId),
151 [controller],
152 );
153 const onSetEnvironmentEnabled = useCallback(
154 (environmentId: EnvironmentId, enabled: boolean) =>
155 controller.setEnvironmentEnabled(environmentId, enabled),
156 [controller],
157 );
158 const onUpdateEnvironment = useCallback(
159 (
160 environmentId: EnvironmentId,
161 updates: { readonly label: string; readonly displayUrl: string },
162 ) => controller.updateEnvironment(environmentId, updates),
163 [controller],
164 );
165
166 const onRemoveEnvironmentPress = useCallback(
167 (environmentId: EnvironmentId) => {
168 const environment = connectedEnvironments.find(
169 (candidate) => candidate.environmentId === environmentId,
170 );
171 if (!environment) {
172 return;
173 }
174 Alert.alert(
175 "Remove from this device?",
176 `Forget ${environment.environmentLabel} and its cached threads on this device. Switch it off instead to keep it saved.`,
177 [
178 { text: "Cancel", style: "cancel" },
179 {
180 text: "Remove",
181 style: "destructive",
182 onPress: () => {
183 void controller.removeEnvironment(environmentId);
184 },
185 },
186 ],
187 );
188 },
189 [connectedEnvironments, controller],
190 );
191
192 return {
193 connectionPairingUrl,
194 connectionState,
195 connectionError,
196 pairingConnectionError: pendingConnectionError,
197 connectedEnvironments,
198 connectedEnvironmentCount: connectedEnvironments.length,
199 onChangeConnectionPairingUrl,
200 onConnectPress,
201 onReconnectEnvironment,
202 onSetEnvironmentEnabled,
203 onUpdateEnvironment,
204 onRemoveEnvironmentPress,
205 };
206}