Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
3import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
4import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
5import * as Cause from "effect/Cause";
6import { msg } from "gt-react";
7import { useEffect, useRef, useState } from "react";
8
9import { environmentCatalog } from "~/connection/catalog";
10import { m } from "~/i18n/messages";
11import { appAtomRegistry } from "~/rpc/atomRegistry";
12import { projectEnvironment } from "~/state/projects";
13
14export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
15 const [directories, setDirectories] = useState(new Map<string, readonly ProjectEntry[]>());
16 const [errors, setErrors] = useState(new Map<string, string>());
17 const [pending, setPending] = useState(1);
18 const [loadingDirectories, setLoadingDirectories] = useState<ReadonlySet<string>>(
19 () => new Set([""]),
20 );
21 // Source of truth for `directories`, so a listing can purge folders it no longer holds.
22 const listings = useRef(new Map<string, readonly ProjectEntry[]>());
23 const requests = useRef(new Map<string, Promise<void>>());
24 const detachedRequests = useRef(new Map<string, Promise<void>>());
25 const followUpRefreshes = useRef(new Map<string, Promise<void>>());
26 const loaded = useRef(new Set<string>());
27 const requested = useRef(new Set<string>());
28 // Listed folders a refresh has not read again yet. `revalidate` reads one once it is on screen.
29 const stale = useRef(new Set<string>());
30 const active = useRef(true);
31 const running = useRef(0);
32 const waiting = useRef<Array<() => void>>([]);
33
34 const startRequest = (directoryPath: string, refresh: boolean): Promise<void> => {
35 loaded.current.add(directoryPath);
36 requested.current.add(directoryPath);
37 stale.current.delete(directoryPath);
38 const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
39 const detached = detachedRequests.current.get(directoryPath);
40 const request = (async () => {
41 // A shared query still waiting would join the removed folder's read.
42 if (detached) await detached;
43 if (running.current >= 4) await new Promise<void>((resolve) => waiting.current.push(resolve));
44 else running.current++;
45 const result = active.current
46 ? await executeAtomQuery(appAtomRegistry, atom, {
47 refresh: true,
48 reportFailure: false,
49 reportDefect: false,
50 })
51 : undefined;
52 const next = waiting.current.shift();
53 if (next) next();
54 else running.current--;
55 return result;
56 })()
57 .then((result) => {
58 // A request is dropped from `requests` when its folder disappears, so its read is stale.
59 if (!active.current || !result || requests.current.get(directoryPath) !== request) return;
60 if (result._tag === "Success") {
61 const children = result.value.entries.filter(
62 (entry) =>
63 entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
64 );
65 const listed = listings.current.get(directoryPath);
66 const next = new Map(listings.current).set(directoryPath, children);
67 const childDirectories = new Set(
68 children.filter((entry) => entry.kind === "directory").map((entry) => entry.path),
69 );
70 const prefix = directoryPath === "" ? "" : `${directoryPath}/`;
71 const removed = [...requested.current].filter((path) => {
72 if (path === directoryPath || !path.startsWith(prefix)) return false;
73 const slash = path.indexOf("/", prefix.length);
74 return !childDirectories.has(slash === -1 ? path : path.slice(0, slash));
75 });
76 for (const path of removed) {
77 next.delete(path);
78 loaded.current.delete(path);
79 requested.current.delete(path);
80 stale.current.delete(path);
81 const detachedRequest = requests.current.get(path);
82 if (detachedRequest) detachedRequests.current.set(path, detachedRequest);
83 requests.current.delete(path);
84 followUpRefreshes.current.delete(path);
85 }
86 // A refresh that finds a folder as it was publishes nothing, so the tree is not rebuilt.
87 const unchanged =
88 removed.length === 0 &&
89 listed?.length === children.length &&
90 children.every((entry, index) => {
91 const known = listed[index]!;
92 return (
93 entry.path === known.path &&
94 entry.kind === known.kind &&
95 entry.ignored === known.ignored
96 );
97 });
98 if (!unchanged) {
99 listings.current = next;
100 setDirectories(next);
101 }
102 if (removed.length > 0)
103 setLoadingDirectories((previous) => {
104 const remaining = new Set(previous);
105 for (const path of removed) remaining.delete(path);
106 return remaining;
107 });
108 setErrors((previous) => {
109 const cleared = [directoryPath, ...removed].filter((path) => previous.has(path));
110 if (cleared.length === 0) return previous;
111 const remaining = new Map(previous);
112 for (const path of cleared) remaining.delete(path);
113 return remaining;
114 });
115 } else {
116 loaded.current.delete(directoryPath);
117 const cause = Cause.squash(result.cause);
118 setErrors((previous) =>
119 new Map(previous).set(
120 directoryPath,
121 thrownErrorMessage(cause, m) ?? m(msg("Unable to load folder.")),
122 ),
123 );
124 }
125 })
126 .finally(() => {
127 if (detachedRequests.current.get(directoryPath) === request)
128 detachedRequests.current.delete(directoryPath);
129 const current = requests.current.get(directoryPath) === request;
130 if (current) requests.current.delete(directoryPath);
131 if (!active.current) return;
132 setPending((count) => count - 1);
133 if (!refresh && current)
134 setLoadingDirectories((previous) => {
135 const next = new Set(previous);
136 next.delete(directoryPath);
137 return next;
138 });
139 });
140 requests.current.set(directoryPath, request);
141 return request;
142 };
143
144 const load = function loadDirectory(directoryPath: string, refresh = false): Promise<void> {
145 const existing = requests.current.get(directoryPath);
146 if (existing) {
147 if (!refresh) return existing;
148 let followUp = followUpRefreshes.current.get(directoryPath);
149 if (!followUp) {
150 followUp = existing.then(() => {
151 if (followUpRefreshes.current.get(directoryPath) !== followUp) return;
152 followUpRefreshes.current.delete(directoryPath);
153 if (active.current && requested.current.has(directoryPath))
154 return loadDirectory(directoryPath, true);
155 });
156 followUpRefreshes.current.set(directoryPath, followUp);
157 }
158 return followUp;
159 }
160 if (!refresh && loaded.current.has(directoryPath)) return Promise.resolve();
161 setPending((count) => count + 1);
162 if (!refresh) setLoadingDirectories((previous) => new Set(previous).add(directoryPath));
163 return startRequest(directoryPath, refresh);
164 };
165
166 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the root directory read on mount and marks the hook inactive so late reads are ignored
167 useEffect(() => {
168 active.current = true;
169 if (!requests.current.has("") && !loaded.current.has("")) void startRequest("", false);
170 return () => {
171 active.current = false;
172 };
173 }, [startRequest]);
174
175 // A folder read fails at once while its environment is unreachable; read it again once a new
176 // session is up rather than leaving the error until someone retries by hand.
177 const sessionGeneration = environmentCatalog.sessionGenerationAtom(environmentId);
178 // A listener alone does not compute the atom, so nothing would follow the connection.
179 useAtomMount(sessionGeneration);
180 useAtomSubscribe(sessionGeneration, () => {
181 for (const path of errors.keys()) void load(path);
182 });
183
184 const entries: ProjectEntry[] = [];
185 const visit = (path: string) => {
186 for (const entry of directories.get(path) ?? []) {
187 entries.push(entry);
188 if (entry.kind === "directory") visit(entry.path);
189 }
190 };
191 visit("");
192
193 const reachableDirectories = new Set([
194 "",
195 ...entries.filter((entry) => entry.kind === "directory").map((entry) => entry.path),
196 ]);
197
198 // Reads the root again and leaves every other listed folder to `revalidate`, so a refresh costs
199 // what is on screen rather than every folder the tree has listed.
200 const refresh = () => {
201 if (!active.current) return;
202 for (const path of requested.current) if (path !== "") stale.current.add(path);
203 void load("", true);
204 };
205
206 /** Reads again the stale listings that put a row on screen: `directoryPath` and its ancestors. */
207 const revalidate = (directoryPath: string) => {
208 if (!active.current) return;
209 for (
210 let end = directoryPath.length;
211 end > 0 && stale.current.size > 0;
212 end = directoryPath.lastIndexOf("/", end - 1)
213 ) {
214 const path = directoryPath.slice(0, end);
215 if (stale.current.delete(path)) void load(path, true);
216 }
217 };
218
219 return {
220 entries,
221 load,
222 refresh,
223 revalidate,
224 isPending: pending > 0,
225 loadingDirectories,
226 ready: directories.has(""),
227 error: [...errors].find(([path]) => reachableDirectories.has(path))?.[1] ?? null,
228 };
229}