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

use-remote-environment-registry.ts

190 lines6.7 KB

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);
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 };
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 );
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 );
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 connectionState: environment.connectionState,
98 connectionError: environment.connectionError,
99 connectionErrorTraceId: environment.connectionErrorTraceId,
100 })),
101 [workspace.environments],
102 );
103​
104 return {
105 connectedEnvironments,
106 connectionState: workspace.state.connectionState,
107 connectionError: pendingConnectionError ?? workspace.state.connectionError,
108 };
110​
111export function useRemoteConnections() {
112 const controller = useConnectionController();
113 const connectionPairingUrl = useAtomValue(connectionPairingUrlAtom);
114 const pendingConnectionError = useAtomValue(pendingConnectionErrorAtom);
115 const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
116​
117 const onChangeConnectionPairingUrl = useCallback((pairingUrl: string) => {
118 appAtomRegistry.set(connectionPairingUrlAtom, pairingUrl);
119 }, []);
120​
121 const onConnectPress = useCallback(
122 async (pairingUrl?: string) => {
123 const nextPairingUrl = pairingUrl ?? connectionPairingUrl;
124 setPendingConnectionError(null);
125 const result = await controller.connectPairingUrl(nextPairingUrl);
126 if (AsyncResult.isFailure(result)) {
127 const error = Cause.squash(result.cause);
128 const message =
129 error instanceof Error ? error.message : "Failed to pair with the environment.";
130 setPendingConnectionError(message);
131 } else {
132 appAtomRegistry.set(connectionPairingUrlAtom, "");
133 }
134 return result;
135 },
136 [connectionPairingUrl, controller],
137 );
138​
139 const onReconnectEnvironment = useCallback(
140 (environmentId: EnvironmentId) => controller.retryEnvironment(environmentId),
141 [controller],
142 );
143 const onUpdateEnvironment = useCallback(
144 (
145 environmentId: EnvironmentId,
146 updates: { readonly label: string; readonly displayUrl: string },
147 ) => controller.updateEnvironment(environmentId, updates),
148 [controller],
149 );
150​
151 const onRemoveEnvironmentPress = useCallback(
152 (environmentId: EnvironmentId) => {
153 const environment = connectedEnvironments.find(
154 (candidate) => candidate.environmentId === environmentId,
155 );
156 if (!environment) {
157 return;
158 }
159 Alert.alert(
160 "Remove environment?",
161 `Disconnect and forget ${environment.environmentLabel} on this device.`,
162 [
163 { text: "Cancel", style: "cancel" },
164 {
165 text: "Remove",
166 style: "destructive",
167 onPress: () => {
168 void controller.removeEnvironment(environmentId);
169 },
170 },
171 ],
172 );
173 },
174 [connectedEnvironments, controller],
175 );
176​
177 return {
178 connectionPairingUrl,
179 connectionState,
180 connectionError,
181 pairingConnectionError: pendingConnectionError,
182 connectedEnvironments,
183 connectedEnvironmentCount: connectedEnvironments.length,
184 onChangeConnectionPairingUrl,
185 onConnectPress,
186 onReconnectEnvironment,
187 onUpdateEnvironment,
188 onRemoveEnvironmentPress,
189 };