Open History to see the last commit
1import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
2import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
3import { ProjectListEntriesError, type EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
4import * as Cause from "effect/Cause";
5import { useLayoutEffect, useRef, useState } from "react";
6import { Atom } from "effect/reactivity";
7
8import { environmentCatalog } from "../../connection/catalog";
9import { appAtomRegistry } from "../../state/atom-registry";
10import { projectEnvironment } from "../../state/projects";
11import { useDebouncedValue } from "../../state/queries";
12import { useEnvironmentQuery } from "../../state/query";
13
14function createDirectories() {
15 return {
16 target: {},
17 entries: new Map<string, ReadonlyArray<ProjectEntry>>(),
18 errors: new Map<string, string>(),
19 completeDirectories: new Set<string>(),
20 listingCompletedAt: new Map<string, number>(),
21 discoveries: new Map<string, ProjectEntry>(),
22 rootListing: null as { readonly timestamp: number } | null,
23 validatedDirectories: new Set<string>(),
24 loading: new Set<string>(),
25 expandedPaths: new Set<string>(),
26 selectedPath: null as string | null,
27 revealedSelection: { path: null as string | null, ancestors: new Set<string>() },
28 isRefreshing: false,
29 };
30}
31
32function boundDirectories(current: ReturnType<typeof createDirectories>, preserveVisible = true) {
33 const visible = (path: string) => {
34 const parts = path.split("/");
35 return parts.every((_, index) =>
36 current.expandedPaths.has(parts.slice(0, index + 1).join("/")),
37 );
38 };
39 const inactive = [...new Set([...current.entries.keys(), ...current.errors.keys()])].filter(
40 (path) => !preserveVisible || !visible(path),
41 );
42 const ownedPaths = [
43 ...current.entries.keys(),
44 ...current.expandedPaths,
45 current.selectedPath,
46 ].filter((path) => path !== null);
47 const discoveries = new Map(
48 [...current.discoveries].filter(([path]) =>
49 ownedPaths.some((owned) => owned === path || owned.startsWith(`${path}/`)),
50 ),
51 );
52 if (inactive.length <= 64)
53 return discoveries.size === current.discoveries.size ? current : { ...current, discoveries };
54 const evicted = new Set(inactive.slice(0, -64));
55 // Evict listing data, not the user's expansion and selection. A missing parent reloads on return.
56 return {
57 ...current,
58 discoveries,
59 entries: new Map([...current.entries].filter(([path]) => !evicted.has(path))),
60 errors: new Map([...current.errors].filter(([path]) => !evicted.has(path))),
61 completeDirectories: new Set(
62 [...current.completeDirectories].filter((path) => !evicted.has(path)),
63 ),
64 validatedDirectories: new Set(
65 [...current.validatedDirectories].filter((path) => !evicted.has(path)),
66 ),
67 listingCompletedAt: new Map(
68 [...current.listingCompletedAt].filter(([path]) => !evicted.has(path)),
69 ),
70 };
71}
72
73function contradictsListing(path: string, parent: string, entries: ReadonlyArray<ProjectEntry>) {
74 if (parent !== "" && !path.startsWith(`${parent}/`)) return false;
75 const child = path.slice(parent === "" ? 0 : parent.length + 1).split("/")[0];
76 const childPath = parent === "" ? child : `${parent}/${child}`;
77 const entry = entries.find((item) => item.path === childPath);
78 return !entry || (path !== childPath && entry.kind !== "directory");
79}
80
81function createRequests() {
82 return {
83 active: true,
84 refreshVersion: 0,
85 pending: new Map<string, AbortController>(),
86 };
87}
88
89function getRequests(
90 requestsByTarget: WeakMap<object, ReturnType<typeof createRequests>>,
91 target: object,
92) {
93 let requests = requestsByTarget.get(target);
94 if (!requests) {
95 requests = createRequests();
96 requestsByTarget.set(target, requests);
97 }
98 return requests;
99}
100const noSessionGeneration = Atom.make(0);
101
102export function useFileTreeEntries(input: {
103 readonly cwd: string | null;
104 readonly environmentId: EnvironmentId | null;
105 readonly searchQuery: string;
106}) {
107 const { cwd, environmentId } = input;
108 const searching = input.searchQuery.trim().length > 0;
109 const query = input.searchQuery.trim().slice(0, 256);
110 const debouncedQuery = useDebouncedValue(query, 200);
111 const root = useEnvironmentQuery(
112 cwd !== null && environmentId !== null
113 ? projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath: "" } })
114 : null,
115 );
116 const { refresh: refreshRoot } = root;
117 const search = useEnvironmentQuery(
118 searching && debouncedQuery.length > 0 && cwd !== null && environmentId !== null
119 ? projectEnvironment.searchEntries({
120 environmentId,
121 input: { cwd, query: debouncedQuery, limit: 200 },
122 })
123 : null,
124 );
125 const workspaceKey = JSON.stringify([environmentId, cwd]);
126 const [cache, setCache] = useState(() => ({
127 key: workspaceKey,
128 workspaces: new Map([[workspaceKey, createDirectories()]]),
129 }));
130 const savedDirectories = cache.workspaces.get(workspaceKey) ?? createDirectories();
131 // Requests belong to a visit, so returning cannot revive an old completion.
132 const directories =
133 cache.key === workspaceKey
134 ? savedDirectories
135 : {
136 ...savedDirectories,
137 target: {},
138 validatedDirectories: new Set<string>(),
139 errors: new Map<string, string>(),
140 loading: new Set<string>(),
141 isRefreshing: false,
142 };
143 if (cache.key !== workspaceKey) {
144 const workspaces = new Map(cache.workspaces);
145 const previous = workspaces.get(cache.key);
146 if (previous) {
147 workspaces.set(
148 cache.key,
149 boundDirectories(
150 {
151 ...previous,
152 errors: new Map(),
153 loading: new Set(),
154 isRefreshing: false,
155 },
156 false,
157 ),
158 );
159 }
160 workspaces.delete(workspaceKey);
161 workspaces.set(workspaceKey, directories);
162 if (workspaces.size > 8) workspaces.delete(workspaces.keys().next().value!);
163 setCache({ key: workspaceKey, workspaces });
164 }
165 const setDirectories = (
166 update: (current: ReturnType<typeof createDirectories>) => ReturnType<typeof createDirectories>,
167 ) =>
168 setCache((current) => {
169 const previous = current.workspaces.get(workspaceKey);
170 if (!previous) return current;
171 const next = boundDirectories(update(previous));
172 if (next === previous) return current;
173 return { ...current, workspaces: new Map(current.workspaces).set(workspaceKey, next) };
174 });
175 const { target } = directories;
176 const requestsByTarget = useRef(new WeakMap<object, ReturnType<typeof createRequests>>());
177 // Cancel the old target before consumers' passive effects start new directory loads.
178 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads the root and aborts the old target's directory requests before consumers start new loads
179 useLayoutEffect(() => {
180 const requests = getRequests(requestsByTarget.current, target);
181 requests.active = true;
182 refreshRoot();
183 return () => {
184 requests.active = false;
185 requests.refreshVersion++;
186 for (const controller of requests.pending.values()) controller.abort();
187 requests.pending.clear();
188 setDirectories((current) =>
189 current.target === target
190 ? { ...current, loading: new Set(), isRefreshing: false }
191 : current,
192 );
193 };
194 }, [target, setDirectories, requestsByTarget, refreshRoot]);
195 const updateDirectories = (
196 update: (current: ReturnType<typeof createDirectories>) => ReturnType<typeof createDirectories>,
197 ) => setDirectories((current) => (current.target === target ? update(current) : current));
198 const loadDirectory = (directoryPath: string, refresh = false) => {
199 const requests = getRequests(requestsByTarget.current, target);
200 if (
201 !requests.active ||
202 missingRoot ||
203 cwd === null ||
204 environmentId === null ||
205 (!refresh && directories.validatedDirectories.has(directoryPath)) ||
206 requests.pending.has(directoryPath)
207 ) {
208 return;
209 }
210 const controller = new AbortController();
211 requests.pending.set(directoryPath, controller);
212 updateDirectories((current) => {
213 const errors = new Map(current.errors);
214 errors.delete(directoryPath);
215 return { ...current, errors, loading: new Set(current.loading).add(directoryPath) };
216 });
217 const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
218 appAtomRegistry.refresh(atom);
219 return executeAtomQuery(appAtomRegistry, atom, {
220 signal: controller.signal,
221 reportFailure: false,
222 reportDefect: false,
223 }).then((result) => {
224 if (controller.signal.aborted) return;
225 requests.pending.delete(directoryPath);
226 updateDirectories((current) => {
227 const validatedDirectories = new Set(current.validatedDirectories).add(directoryPath);
228 const loading = new Set(current.loading);
229 loading.delete(directoryPath);
230 if (result._tag === "Success") {
231 const entries = new Map(current.entries);
232 entries.delete(directoryPath);
233 entries.set(
234 directoryPath,
235 result.value.entries.filter(
236 (entry) =>
237 entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
238 ),
239 );
240 const completeDirectories = new Set(current.completeDirectories);
241 if (result.value.truncated) completeDirectories.delete(directoryPath);
242 else completeDirectories.add(directoryPath);
243 return {
244 ...current,
245 entries,
246 loading,
247 completeDirectories,
248 discoveries: result.value.truncated
249 ? current.discoveries
250 : new Map(
251 [...current.discoveries].filter(
252 ([path]) => !contradictsListing(path, directoryPath, result.value.entries),
253 ),
254 ),
255 validatedDirectories,
256 listingCompletedAt: new Map(current.listingCompletedAt).set(
257 directoryPath,
258 result.timestamp,
259 ),
260 };
261 }
262 const error = Cause.squash(result.cause);
263 return {
264 ...current,
265 loading,
266 validatedDirectories,
267 errors: new Map(current.errors).set(
268 directoryPath,
269 error instanceof Error ? error.message : "Files unavailable",
270 ),
271 };
272 });
273 });
274 };
275 const missingRoot =
276 root.failure instanceof ProjectListEntriesError &&
277 root.failure.failure === "workspace_root_not_found";
278 const rootData = missingRoot ? null : root.data;
279 const rootListing = root.successResult ?? directories.rootListing;
280 if (
281 missingRoot &&
282 (directories.entries.size > 0 ||
283 directories.errors.size > 0 ||
284 directories.loading.size > 0 ||
285 directories.expandedPaths.size > 0 ||
286 directories.selectedPath !== null ||
287 directories.discoveries.size > 0)
288 ) {
289 setDirectories(() => createDirectories());
290 }
291 const { refresh: refreshSearch, data: searchData, successResult: searchResult } = search;
292 // A folder read fails at once while its environment is unreachable; read it again once a new
293 // session is up rather than leaving the error until someone refreshes.
294 const sessionGeneration =
295 environmentId === null
296 ? noSessionGeneration
297 : environmentCatalog.sessionGenerationAtom(environmentId);
298 // A listener alone does not compute the atom, so nothing would follow the connection.
299 useAtomMount(sessionGeneration);
300 useAtomSubscribe(sessionGeneration, () => {
301 for (const path of directories.errors.keys()) void loadDirectory(path, true);
302 });
303 const snapshot = (() => {
304 const merged = new Map(missingRoot ? [] : directories.discoveries);
305 if (searching && !missingRoot) {
306 for (const entry of searchData?.entries ?? []) merged.set(entry.path, entry);
307 }
308 const reachableDirectories = new Set<string>();
309 const visit = (items: ReadonlyArray<ProjectEntry>) => {
310 for (const entry of items) {
311 merged.set(entry.path, entry);
312 if (entry.kind === "directory") {
313 reachableDirectories.add(entry.path);
314 visit(directories.entries.get(entry.path) ?? []);
315 }
316 }
317 };
318 if (!missingRoot) {
319 const discoveries = new Map(directories.discoveries);
320 // Search can return only leaves; their inferred parents still own loaded children.
321 for (const entry of directories.discoveries.values()) {
322 const parts = entry.path.split("/");
323 for (let index = 1; index < parts.length; index++) {
324 const path = parts.slice(0, index).join("/");
325 if (!discoveries.has(path)) discoveries.set(path, { kind: "directory", path });
326 }
327 }
328 visit([...discoveries.values()]);
329 }
330 visit((rootData?.entries ?? []).filter((entry) => !entry.path.includes("/")));
331 return {
332 entries: [...merged.values()],
333 reachableDirectories,
334 searchResultPaths:
335 searching && !missingRoot
336 ? new Set((searchData?.entries ?? []).map((entry) => entry.path))
337 : null,
338 };
339 })();
340
341 if (rootData) {
342 const deleted = (path: string, directory = false) => {
343 const parts = path.split("/");
344 for (let index = 0; index < parts.length; index++) {
345 const parent = parts.slice(0, index).join("/");
346 const listing = index === 0 ? rootData.entries : directories.entries.get(parent);
347 const child = parts.slice(0, index + 1).join("/");
348 const complete =
349 index === 0 ? !rootData.truncated : directories.completeDirectories.has(parent);
350 const entry = listing?.find((item) => item.path === child);
351 if (complete && listing && !entry) {
352 const listingCompletedAt =
353 index === 0 && directories.rootListing !== rootListing
354 ? rootListing?.timestamp
355 : directories.listingCompletedAt.get(parent);
356 // Cached queries keep their completion time across query switches.
357 // Equal-millisecond responses cannot prove a path postdates the listing.
358 const retained =
359 !(index === 0 && directories.rootListing !== rootListing) &&
360 [...directories.discoveries.keys()].some(
361 (path) => path === child || path.startsWith(`${child}/`),
362 );
363 const discovered =
364 retained ||
365 (searching &&
366 query === debouncedQuery &&
367 searchResult !== null &&
368 searchResult.timestamp > (listingCompletedAt ?? -Infinity) &&
369 searchData?.entries.some(
370 (item) => item.path === child || item.path.startsWith(`${child}/`),
371 ));
372 if (!discovered) return true;
373 }
374 if (entry && (directory || index < parts.length - 1) && entry.kind !== "directory")
375 return true;
376 }
377 return false;
378 };
379 const reconciled = (() => {
380 const current = directories;
381 const discoveries = new Map(current.discoveries);
382 if (current.rootListing !== rootListing && !rootData.truncated) {
383 for (const path of discoveries.keys()) {
384 if (contradictsListing(path, "", rootData.entries)) discoveries.delete(path);
385 }
386 }
387 if (searching && query === debouncedQuery && searchResult !== null) {
388 const ownedPaths = [
389 ...current.entries.keys(),
390 ...current.expandedPaths,
391 current.selectedPath,
392 ];
393 for (const entry of searchData?.entries ?? []) {
394 if (
395 ownedPaths.some((path) => path === entry.path || path?.startsWith(`${entry.path}/`)) &&
396 !deleted(entry.path, entry.kind === "directory")
397 )
398 discoveries.set(entry.path, entry);
399 }
400 }
401 const entries = new Map([...current.entries].filter(([path]) => !deleted(path, true)));
402 const errors = new Map([...current.errors].filter(([path]) => !deleted(path, true)));
403 const expandedPaths = new Set(
404 [...current.expandedPaths].filter((path) => !deleted(path, true)),
405 );
406 const selectedPath =
407 current.selectedPath !== null && deleted(current.selectedPath)
408 ? null
409 : current.selectedPath;
410 if (
411 entries.size === current.entries.size &&
412 errors.size === current.errors.size &&
413 expandedPaths.size === current.expandedPaths.size &&
414 selectedPath === current.selectedPath &&
415 current.rootListing === rootListing &&
416 discoveries.size === current.discoveries.size &&
417 [...discoveries].every(([path, entry]) => current.discoveries.get(path) === entry)
418 )
419 return current;
420 const completeDirectories = new Set(
421 [...current.completeDirectories].filter((path) => entries.has(path)),
422 );
423 return {
424 ...current,
425 rootListing,
426 discoveries,
427 listingCompletedAt: new Map(
428 [...current.listingCompletedAt].filter(([path]) => path === "" || entries.has(path)),
429 ).set(
430 "",
431 current.rootListing === rootListing
432 ? (current.listingCompletedAt.get("") ?? -Infinity)
433 : (rootListing?.timestamp ?? -Infinity),
434 ),
435 entries,
436 errors,
437 expandedPaths,
438 selectedPath,
439 completeDirectories,
440 validatedDirectories: new Set(
441 [...current.validatedDirectories].filter((path) => !deleted(path, true)),
442 ),
443 };
444 })();
445 if (reconciled !== directories) setDirectories(() => reconciled);
446 }
447
448 const refresh = () => {
449 const requests = getRequests(requestsByTarget.current, target);
450 if (!requests.active) return Promise.resolve();
451 refreshRoot();
452 if (searching && !missingRoot) refreshSearch();
453 const paths = new Set(
454 [...directories.entries.keys(), ...directories.errors.keys(), ...directories.loading].filter(
455 (path) => snapshot.reachableDirectories.has(path),
456 ),
457 );
458 for (const controller of requests.pending.values()) controller.abort();
459 requests.pending.clear();
460 const version = ++requests.refreshVersion;
461 updateDirectories((current) => ({
462 ...current,
463 errors: new Map(),
464 loading: new Set(),
465 isRefreshing: true,
466 }));
467 const remaining = paths.values();
468 const worker = async () => {
469 while (requests.active && version === requests.refreshVersion) {
470 const next = remaining.next();
471 if (next.done) return;
472 await loadDirectory(next.value, true);
473 }
474 };
475 const queries =
476 cwd !== null && environmentId !== null
477 ? [
478 projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath: "" } }),
479 ...(searching && !missingRoot
480 ? [
481 projectEnvironment.searchEntries({
482 environmentId,
483 input: { cwd, query: debouncedQuery, limit: 200 },
484 }),
485 ]
486 : []),
487 ]
488 : [];
489 const work = [
490 ...queries.map((atom) =>
491 executeAtomQuery(appAtomRegistry, atom, { reportFailure: false, reportDefect: false }),
492 ),
493 ...Array.from({ length: Math.min(4, paths.size) }, () => worker()),
494 ];
495 return Promise.all(work).finally(() => {
496 if (version === requests.refreshVersion) {
497 updateDirectories((current) => ({ ...current, isRefreshing: false }));
498 }
499 });
500 };
501
502 const revealSelection = (path: string | null) => {
503 if (missingRoot) return;
504 updateDirectories((current) => {
505 const previous = current.revealedSelection;
506 const handled = previous.path === path ? previous.ancestors : new Set<string>();
507 const parts = path?.split("/").filter(Boolean) ?? [];
508 const ancestors = parts
509 .slice(1)
510 .map((_, index) => parts.slice(0, index + 1).join("/"))
511 .filter(
512 (ancestor) =>
513 !handled.has(ancestor) &&
514 snapshot.entries.some(
515 (entry) =>
516 (entry.kind === "directory" && entry.path === ancestor) ||
517 (entry.path === path && entry.path.startsWith(`${ancestor}/`)),
518 ),
519 );
520 if (previous.path === path && ancestors.length === 0) return current;
521 return {
522 ...current,
523 discoveries: new Map([
524 ...current.discoveries,
525 ...snapshot.entries
526 .filter((entry) => entry.path === path)
527 .map((entry) => [entry.path, entry] as const),
528 ]),
529 selectedPath: path,
530 revealedSelection: { path, ancestors: new Set([...handled, ...ancestors]) },
531 expandedPaths: new Set([...current.expandedPaths, ...ancestors]),
532 };
533 });
534 };
535
536 const setExpandedPaths = (update: (current: ReadonlySet<string>) => ReadonlySet<string>) =>
537 setDirectories((current) => {
538 const expandedPaths = update(current.expandedPaths);
539 return expandedPaths === current.expandedPaths
540 ? current
541 : { ...current, expandedPaths: new Set(expandedPaths) };
542 });
543
544 return {
545 revealSelection,
546 expandedPaths: directories.expandedPaths,
547 setExpandedPaths,
548 selectedPath: directories.selectedPath,
549 selectPath: (selectedPath: string) =>
550 updateDirectories((current) => ({ ...current, selectedPath })),
551 entries: snapshot.entries,
552 searchResultPaths: snapshot.searchResultPaths,
553 isRefreshing: directories.isRefreshing,
554 error:
555 root.error ??
556 (searching ? search.error : null) ??
557 [...directories.errors].find(([path]) => snapshot.reachableDirectories.has(path))?.[1] ??
558 null,
559 isPending:
560 !missingRoot &&
561 (root.isPending ||
562 directories.loading.size > 0 ||
563 (searching && (query !== debouncedQuery || search.isPending))),
564 searchTruncated: !missingRoot && searching && (search.data?.truncated ?? false),
565 loadedDirectories: new Set(directories.entries.keys()),
566 loadingDirectories: directories.loading,
567 loadDirectory: (path: string, retry = false) =>
568 loadDirectory(path, retry && directories.errors.has(path)),
569 refresh,
570 };
571}