Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { EnvironmentPresentation } from "@t3tools/client-runtime/connection";
3import {
4 createEnvironmentPresentationAtoms,
5 createEnvironmentSummaryAtoms,
6} from "@t3tools/client-runtime/state/presentation";
7import type { EnvironmentId } from "@t3tools/contracts";
8import { Atom } from "effect/reactivity";
9
10import { environmentCatalog } from "../connection/catalog";
11import { serverEnvironment } from "./server";
12import { expectsPrimaryEnvironment } from "./shell";
13
14export const environmentPresentations = createEnvironmentPresentationAtoms({
15 catalogValueAtom: environmentCatalog.catalogValueAtom,
16 stateAtom: environmentCatalog.stateAtom,
17 serverConfigValueAtom: serverEnvironment.configValueAtom,
18});
19
20export const environmentSummaries = createEnvironmentSummaryAtoms({
21 catalogValueAtom: environmentCatalog.catalogValueAtom,
22 presentationAtom: environmentPresentations.presentationAtom,
23});
24
25const EMPTY_ENVIRONMENT_PRESENTATION_ATOM = Atom.make<EnvironmentPresentation | null>(null).pipe(
26 Atom.withLabel("web-environment-presentation:empty"),
27);
28
29/** The catalog has loaded without a usable connection to the environment (as `enabledEnvironmentIds` counts them). */
30export const environmentUnreachableAtom = Atom.family((environmentId: EnvironmentId | null) =>
31 Atom.make((get) => {
32 if (environmentId === null) return false;
33 const catalog = get(environmentCatalog.catalogValueAtom);
34 if (!catalog.isReady) return false;
35 // The catalog is ready before primary discovery lands; until then it cannot prove absence.
36 if (
37 expectsPrimaryEnvironment() &&
38 !Array.from(catalog.entries.values()).some(
39 (entry) => entry.target._tag === "PrimaryConnectionTarget",
40 )
41 ) {
42 return false;
43 }
44 const entry = catalog.entries.get(environmentId);
45 return !entry?.enabled || entry.unsupportedReason !== undefined;
46 }),
47);
48
49export function useEnvironmentPresentation(environmentId: EnvironmentId | null) {
50 const catalog = useAtomValue(environmentCatalog.catalogValueAtom);
51 const presentation = useAtomValue(
52 environmentId === null
53 ? EMPTY_ENVIRONMENT_PRESENTATION_ATOM
54 : environmentPresentations.presentationAtom(environmentId),
55 );
56 return {
57 isReady: catalog.isReady,
58 presentation,
59 };
60}