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

presentation.ts

70 lines2.5 KB

1import type { EnvironmentId, ServerConfig } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import { AsyncResult, Atom } from "effect/unstable/reactivity";
4​
5import { AVAILABLE_CONNECTION_STATE, type SupervisorConnectionState } from "../connection/model.ts";
6import {
7 presentEnvironmentConnection,
8 type EnvironmentPresentation,
9} from "../connection/presentation.ts";
10import type { EnvironmentCatalogState } from "./connections.ts";
11​
12function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
13 if (left.size !== right.size) {
14 return false;
15 }
16 for (const [key, value] of left) {
17 if (right.get(key) !== value) {
18 return false;
19 }
20 }
21 return true;
23​
24export function createEnvironmentPresentationAtoms<E>(input: {
25 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
26 readonly stateAtom: (
27 environmentId: EnvironmentId,
28 ) => Atom.Atom<AsyncResult.AsyncResult<SupervisorConnectionState, E>>;
29 /** Authoritative live server config, including streamed provider/settings updates. */
30 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
31}) {
32 const presentationAtom = Atom.family((environmentId: EnvironmentId) =>
33 Atom.make((get) => {
34 const entry = get(input.catalogValueAtom).entries.get(environmentId);
35 if (entry === undefined) {
36 return null;
37 }
38 const state = Option.getOrElse(
39 AsyncResult.value(get(input.stateAtom(environmentId))),
40 () => AVAILABLE_CONNECTION_STATE,
41 );
42 return {
43 entry,
44 connection: presentEnvironmentConnection(state),
45 serverConfig: get(input.serverConfigValueAtom(environmentId)),
46 } satisfies EnvironmentPresentation;
47 }).pipe(Atom.withLabel(`environment-presentation:${environmentId}`)),
48 );
49​
50 let previous: ReadonlyMap<EnvironmentId, EnvironmentPresentation> = new Map();
51 const presentationsAtom = Atom.make((get) => {
52 const next = new Map<EnvironmentId, EnvironmentPresentation>();
53 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
54 const presentation = get(presentationAtom(environmentId));
55 if (presentation !== null) {
56 next.set(environmentId, presentation);
57 }
58 }
59 if (mapsEqual(previous, next)) {
60 return previous;
61 }
62 previous = next;
63 return previous;
64 }).pipe(Atom.withLabel("environment-presentations"));
65​
66 return {
67 presentationAtom,
68 presentationsAtom,
69 };