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

entities.ts

85 lines2.8 KB

1import { useAtomValue } from "@effect/atom-react";
2​
3import { appAtomRegistry } from "./atom-registry";
4import type {
5 EnvironmentProject,
6 EnvironmentThreadShell,
7} from "@t3tools/client-runtime/state/shell";
8import type {
9 EnvironmentId,
10 ScopedProjectRef,
11 ScopedThreadRef,
12 ServerConfig,
13} from "@t3tools/contracts";
14import { Atom } from "effect/unstable/reactivity";
15​
16import { environmentProjects } from "./projects";
17import { environmentServerConfigsAtom, serverEnvironment } from "./server";
18import { environmentThreadShells } from "./threads";
19​
20const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
21 Atom.withLabel("mobile-project:empty"),
22);
23const EMPTY_THREAD_SHELL_ATOM = Atom.make<EnvironmentThreadShell | null>(null).pipe(
24 Atom.withLabel("mobile-thread-shell:empty"),
25);
26const EMPTY_SERVER_CONFIG_ATOM = Atom.make<ServerConfig | null>(null).pipe(
27 Atom.withLabel("mobile-server-config:empty"),
28);
29​
30/** Resolves when the project event reaches the live client store. */
31export function waitForProject(
32 ref: ScopedProjectRef,
33 timeoutMs = 10_000,
34): Promise<EnvironmentProject | null> {
35 const atom = environmentProjects.projectAtom(ref);
36 const current = appAtomRegistry.get(atom);
37 if (current !== null) return Promise.resolve(current);
38 return new Promise((resolve) => {
39 let unsubscribe: (() => void) | null = null;
40 const timeout = setTimeout(() => {
41 unsubscribe?.();
42 resolve(null);
43 }, timeoutMs);
44 const finish = (project: EnvironmentProject | null) => {
45 if (project === null) return;
46 clearTimeout(timeout);
47 unsubscribe?.();
48 resolve(project);
49 };
50 unsubscribe = appAtomRegistry.subscribe(atom, finish);
51 finish(appAtomRegistry.get(atom));
52 });
54​
55export function useProjects(): ReadonlyArray<EnvironmentProject> {
56 return useAtomValue(environmentProjects.projectsAtom);
58​
59export function useThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
60 return useAtomValue(environmentThreadShells.threadShellsAtom);
62​
63export function useProject(ref: ScopedProjectRef | null): EnvironmentProject | null {
64 return useAtomValue(ref === null ? EMPTY_PROJECT_ATOM : environmentProjects.projectAtom(ref));
66​
67export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
68 return useAtomValue(
69 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.threadShellAtom(ref),
70 );
72​
73export function useEnvironmentServerConfig(
74 environmentId: EnvironmentId | null,
75): ServerConfig | null {
76 return useAtomValue(
77 environmentId === null
78 ? EMPTY_SERVER_CONFIG_ATOM
79 : serverEnvironment.configValueAtom(environmentId),
80 );
82​
83export function useServerConfigs(): ReadonlyMap<EnvironmentId, ServerConfig> {
84 return useAtomValue(environmentServerConfigsAtom);