Open History to see the last commit
1import { enabledEnvironmentIds } from "@t3tools/client-runtime/state/connections";
2import {
3 createEnvironmentShellAtoms,
4 createEnvironmentShellSummaryAtom,
5 createEnvironmentSnapshotAtom,
6 createShellEnvironmentAtoms,
7 EMPTY_SHELL_STATE,
8 type EnvironmentShellState,
9} from "@t3tools/client-runtime/state/shell";
10import { useAtomValue } from "@effect/atom-react";
11import type { EnvironmentId } from "@t3tools/contracts";
12import * as Option from "effect/Option";
13import { Atom } from "effect/reactivity";
14
15import { environmentCatalog } from "../connection/catalog";
16import { connectionAtomRuntime } from "../connection/runtime";
17
18export const shellEnvironment = createShellEnvironmentAtoms(connectionAtomRuntime);
19export const environmentShell = createEnvironmentShellAtoms(connectionAtomRuntime);
20export const environmentSnapshotAtom = createEnvironmentSnapshotAtom(environmentShell.stateAtom);
21export const environmentShellSummaryAtom = createEnvironmentShellSummaryAtom({
22 catalogValueAtom: environmentCatalog.catalogValueAtom,
23 shellStateValueAtom: environmentShell.stateValueAtom,
24});
25
26const EMPTY_ENVIRONMENT_SHELL_STATE_ATOM = Atom.make<EnvironmentShellState>(EMPTY_SHELL_STATE);
27
28const shellStatus = (state: EnvironmentShellState) => state.status;
29const shellHasError = (state: EnvironmentShellState) => Option.isSome(state.error);
30// The empty placeholder stands until the environment has read its cached shell.
31const shellCacheRead = (state: EnvironmentShellState) => state !== EMPTY_SHELL_STATE;
32
33const shellCacheReadAtom = Atom.family((environmentId: EnvironmentId) =>
34 Atom.make((get) => shellCacheRead(get(environmentShell.stateValueAtom(environmentId)))),
35);
36
37/**
38 * True once every enabled environment has read its cached shell. A list that paints before
39 * then gets the cached rows of one environment at a time.
40 */
41export const shellCachesReadAtom = Atom.make((get) => {
42 const catalog = get(environmentCatalog.catalogValueAtom);
43 if (!catalog.isReady) return false;
44 // Reads every environment, so each one loads its cache now and not after the one before it.
45 let allRead = true;
46 for (const environmentId of enabledEnvironmentIds(catalog)) {
47 if (!get(shellCacheReadAtom(environmentId))) allRead = false;
48 }
49 return allRead;
50}).pipe(Atom.withLabel("mobile-shell-caches-read"));
51
52export function useEnvironmentShellReadiness(environmentId: EnvironmentId | null) {
53 const atom =
54 environmentId === null
55 ? EMPTY_ENVIRONMENT_SHELL_STATE_ATOM
56 : environmentShell.stateValueAtom(environmentId);
57 return {
58 status: useAtomValue(atom, shellStatus),
59 hasError: useAtomValue(atom, shellHasError),
60 cacheRead: useAtomValue(atom, shellCacheRead),
61 };
62}