Skip to content
Source
Sign inSign up

primaryEnvironment.ts

49 lines1.9 KB

1import type { EnvironmentId } from "@t3tools/contracts";
2import { Atom } from "effect/reactivity";
3​
4import { environmentCatalog } from "../connection/catalog";
5import { appAtomRegistry } from "../rpc/atomRegistry";
6​
7export const primaryEnvironmentIdAtom = Atom.make((get) => {
8 for (const [environmentId, entry] of get(environmentCatalog.catalogValueAtom).entries) {
9 if (entry.target._tag === "PrimaryConnectionTarget") {
10 return environmentId;
11 }
12 }
13 return null;
14}).pipe(Atom.withLabel("web-primary-environment-id"));
15​
16export const hostEnvironmentIdAtom = Atom.make<string | null>(null).pipe(
17 Atom.keepAlive,
18 Atom.withLabel("web-host-environment-id"),
19);
20​
21// Without a primary, only the service sharing the desktop app's T3 home supplies themes.
22export function createThemeEnvironmentIdAtom(input: {
23 readonly primaryEnvironmentIdAtom: Atom.Atom<EnvironmentId | null>;
24 readonly hostEnvironmentIdAtom: Atom.Atom<string | null>;
25 readonly catalogValueAtom: Atom.Atom<{ readonly entries: ReadonlyMap<EnvironmentId, unknown> }>;
26}) {
27 return Atom.make((get) => {
28 const primaryEnvironmentId = get(input.primaryEnvironmentIdAtom);
29 if (primaryEnvironmentId !== null) return primaryEnvironmentId;
30 const hostEnvironmentId = get(input.hostEnvironmentIdAtom);
31 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
32 if (environmentId === hostEnvironmentId) return environmentId;
33 }
34 return null;
35 }).pipe(Atom.withLabel("web-theme-environment-id"));
37​
38export const themeEnvironmentIdAtom = createThemeEnvironmentIdAtom({
39 primaryEnvironmentIdAtom,
40 hostEnvironmentIdAtom,
41 catalogValueAtom: environmentCatalog.catalogValueAtom,
42});
43​
44export function startHostEnvironmentLookup(): void {
45 void window.desktopBridge
46 ?.getHostEnvironmentId?.()
47 .then((environmentId) => appAtomRegistry.set(hostEnvironmentIdAtom, environmentId))
48 .catch(() => {});