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

vcsStatusRevalidation.ts

49 lines1.8 KB

1import type { EnvironmentId } from "@t3tools/contracts";
2import { Atom, type AtomRegistry } from "effect/reactivity";
3​
4import { type AtomCommand, type AtomCommandResult, runAtomCommand } from "./runtime.ts";
5​
6interface VcsStatusRevalidationTarget {
7 readonly environmentId: EnvironmentId;
8 readonly cwd: string;
9}
10​
11/**
12 * One atom per environment and cwd, shared by every subscriber, that refreshes
13 * VCS status while mounted: on mount and on each reconnect, once `connected`
14 * is true.
15 */
16export function createVcsStatusRevalidationAtomFamily<R>(input: {
17 readonly refreshStatus: AtomCommand<
18 { readonly environmentId: EnvironmentId; readonly input: { readonly cwd: string } },
19 R,
20 unknown
21 >;
22 readonly connected: (environmentId: EnvironmentId) => Atom.Atom<boolean>;
23 readonly onRefreshed?: (result: AtomCommandResult<R, unknown>) => void;
24}) {
25 const family = Atom.family((target: VcsStatusRevalidationTarget) => {
26 const { environmentId, cwd } = target;
27 const key = `${environmentId}:${cwd}`;
28​
29 const refresh = async (registry: AtomRegistry.AtomRegistry) => {
30 const result = await runAtomCommand(
31 registry,
32 input.refreshStatus,
33 { environmentId, input: { cwd } },
34 { reportFailure: false },
35 );
36 input.onRefreshed?.(result);
37 };
38​
39 return Atom.make((get) => {
40 // Rebuilds only when the connection flag flips, so each reconnect refreshes once.
41 if (get(input.connected(environmentId))) {
42 void refresh(get.registry);
43 }
44 }).pipe(Atom.withLabel(`vcs-status-revalidation:${key}`));
45 });
46 const idle = Atom.make<void>(undefined).pipe(Atom.withLabel("vcs-status-revalidation:idle"));
47 return (target: VcsStatusRevalidationTarget | null): Atom.Atom<void> =>
48 target === null ? idle : family({ environmentId: target.environmentId, cwd: target.cwd });