Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { type GitManagerServiceError, type GitStatusResult } from "@t3tools/contracts";
3import { Cause } from "effect";
4import { Atom } from "effect/unstable/reactivity";
5import { useEffect } from "react";
6
7import { appAtomRegistry } from "../rpc/atomRegistry";
8import { getWsRpcClient, type WsRpcClient } from "../wsRpcClient";
9
10export type GitStatusStreamError = GitManagerServiceError;
11
12export interface GitStatusState {
13 readonly data: GitStatusResult | null;
14 readonly error: GitStatusStreamError | null;
15 readonly cause: Cause.Cause<GitStatusStreamError> | null;
16 readonly isPending: boolean;
17}
18
19type GitStatusClient = Pick<WsRpcClient["git"], "onStatus" | "refreshStatus">;
20
21interface WatchedGitStatus {
22 refCount: number;
23 unsubscribe: () => void;
24}
25
26const EMPTY_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
27 data: null,
28 error: null,
29 cause: null,
30 isPending: false,
31});
32const INITIAL_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
33 ...EMPTY_GIT_STATUS_STATE,
34 isPending: true,
35});
36const EMPTY_GIT_STATUS_ATOM = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
37 Atom.keepAlive,
38 Atom.withLabel("git-status:null"),
39);
40
41const NOOP: () => void = () => undefined;
42const watchedGitStatuses = new Map<string, WatchedGitStatus>();
43const knownGitStatusCwds = new Set<string>();
44const gitStatusRefreshInFlight = new Map<string, Promise<GitStatusResult>>();
45const gitStatusLastRefreshAtByCwd = new Map<string, number>();
46
47const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
48
49let sharedGitStatusClient: GitStatusClient | null = null;
50
51const gitStatusStateAtom = Atom.family((cwd: string) => {
52 knownGitStatusCwds.add(cwd);
53 return Atom.make(INITIAL_GIT_STATUS_STATE).pipe(
54 Atom.keepAlive,
55 Atom.withLabel(`git-status:${cwd}`),
56 );
57});
58
59export function getGitStatusSnapshot(cwd: string | null): GitStatusState {
60 if (cwd === null) {
61 return EMPTY_GIT_STATUS_STATE;
62 }
63
64 return appAtomRegistry.get(gitStatusStateAtom(cwd));
65}
66
67export function watchGitStatus(
68 cwd: string | null,
69 client: GitStatusClient = getWsRpcClient().git,
70): () => void {
71 if (cwd === null) {
72 return NOOP;
73 }
74
75 ensureGitStatusClient(client);
76
77 const watched = watchedGitStatuses.get(cwd);
78 if (watched) {
79 watched.refCount += 1;
80 return () => unwatchGitStatus(cwd);
81 }
82
83 watchedGitStatuses.set(cwd, {
84 refCount: 1,
85 unsubscribe: subscribeToGitStatus(cwd),
86 });
87
88 return () => unwatchGitStatus(cwd);
89}
90
91export function refreshGitStatus(
92 cwd: string | null,
93 client: GitStatusClient = getWsRpcClient().git,
94): Promise<GitStatusResult | null> {
95 if (cwd === null) {
96 return Promise.resolve(null);
97 }
98
99 ensureGitStatusClient(client);
100
101 const currentInFlight = gitStatusRefreshInFlight.get(cwd);
102 if (currentInFlight) {
103 return currentInFlight;
104 }
105
106 const lastRequestedAt = gitStatusLastRefreshAtByCwd.get(cwd) ?? 0;
107 if (Date.now() - lastRequestedAt < GIT_STATUS_REFRESH_DEBOUNCE_MS) {
108 return Promise.resolve(getGitStatusSnapshot(cwd).data);
109 }
110
111 gitStatusLastRefreshAtByCwd.set(cwd, Date.now());
112 const refreshPromise = client.refreshStatus({ cwd }).finally(() => {
113 gitStatusRefreshInFlight.delete(cwd);
114 });
115 gitStatusRefreshInFlight.set(cwd, refreshPromise);
116 return refreshPromise;
117}
118
119export function resetGitStatusStateForTests(): void {
120 for (const watched of watchedGitStatuses.values()) {
121 watched.unsubscribe();
122 }
123 watchedGitStatuses.clear();
124 gitStatusRefreshInFlight.clear();
125 gitStatusLastRefreshAtByCwd.clear();
126 sharedGitStatusClient = null;
127
128 for (const cwd of knownGitStatusCwds) {
129 appAtomRegistry.set(gitStatusStateAtom(cwd), INITIAL_GIT_STATUS_STATE);
130 }
131 knownGitStatusCwds.clear();
132}
133
134export function useGitStatus(cwd: string | null): GitStatusState {
135 useEffect(() => watchGitStatus(cwd), [cwd]);
136
137 const state = useAtomValue(cwd !== null ? gitStatusStateAtom(cwd) : EMPTY_GIT_STATUS_ATOM);
138 return cwd === null ? EMPTY_GIT_STATUS_STATE : state;
139}
140
141function ensureGitStatusClient(client: GitStatusClient): void {
142 if (sharedGitStatusClient === client) {
143 return;
144 }
145
146 if (sharedGitStatusClient !== null) {
147 resetLiveGitStatusSubscriptions();
148 }
149
150 sharedGitStatusClient = client;
151}
152
153function resetLiveGitStatusSubscriptions(): void {
154 for (const watched of watchedGitStatuses.values()) {
155 watched.unsubscribe();
156 }
157 watchedGitStatuses.clear();
158}
159
160function unwatchGitStatus(cwd: string): void {
161 const watched = watchedGitStatuses.get(cwd);
162 if (!watched) {
163 return;
164 }
165
166 watched.refCount -= 1;
167 if (watched.refCount > 0) {
168 return;
169 }
170
171 watched.unsubscribe();
172 watchedGitStatuses.delete(cwd);
173}
174
175function subscribeToGitStatus(cwd: string): () => void {
176 const client = sharedGitStatusClient;
177 if (!client) {
178 return NOOP;
179 }
180
181 markGitStatusPending(cwd);
182 return client.onStatus(
183 { cwd },
184 (status) => {
185 appAtomRegistry.set(gitStatusStateAtom(cwd), {
186 data: status,
187 error: null,
188 cause: null,
189 isPending: false,
190 });
191 },
192 {
193 onResubscribe: () => {
194 markGitStatusPending(cwd);
195 },
196 },
197 );
198}
199
200function markGitStatusPending(cwd: string): void {
201 const atom = gitStatusStateAtom(cwd);
202 const current = appAtomRegistry.get(atom);
203 const next =
204 current.data === null
205 ? INITIAL_GIT_STATUS_STATE
206 : {
207 ...current,
208 error: null,
209 cause: null,
210 isPending: true,
211 };
212
213 if (
214 current.data === next.data &&
215 current.error === next.error &&
216 current.cause === next.cause &&
217 current.isPending === next.isPending
218 ) {
219 return;
220 }
221
222 appAtomRegistry.set(atom, next);
223}