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

useFileTreeEntries.ts

579 lines21.9 KB

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 { useCallback, 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 };
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 };
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");
80​
81function createRequests() {
82 return {
83 active: true,
84 refreshVersion: 0,
85 pending: new Map<string, AbortController>(),
86 };
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;
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 = useCallback(
166 (
167 update: (
168 current: ReturnType<typeof createDirectories>,
169 ) => ReturnType<typeof createDirectories>,
170 ) =>
171 setCache((current) => {
172 const previous = current.workspaces.get(workspaceKey);
173 if (!previous) return current;
174 const next = boundDirectories(update(previous));
175 if (next === previous) return current;
176 return { ...current, workspaces: new Map(current.workspaces).set(workspaceKey, next) };
177 }),
178 [workspaceKey],
179 );
180 const { target } = directories;
181 const requestsByTarget = useRef(new WeakMap<object, ReturnType<typeof createRequests>>());
182 // Cancel the old target before consumers' passive effects start new directory loads.
183 // 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
184 useLayoutEffect(() => {
185 const requests = getRequests(requestsByTarget.current, target);
186 requests.active = true;
187 refreshRoot();
188 return () => {
189 requests.active = false;
190 requests.refreshVersion++;
191 for (const controller of requests.pending.values()) controller.abort();
192 requests.pending.clear();
193 setDirectories((current) =>
194 current.target === target
195 ? { ...current, loading: new Set(), isRefreshing: false }
196 : current,
197 );
198 };
199 }, [target, setDirectories, requestsByTarget, refreshRoot]);
200 const updateDirectories = (
201 update: (current: ReturnType<typeof createDirectories>) => ReturnType<typeof createDirectories>,
202 ) => setDirectories((current) => (current.target === target ? update(current) : current));
203 const loadDirectory = (directoryPath: string, refresh = false) => {
204 const requests = getRequests(requestsByTarget.current, target);
205 if (
206 !requests.active ||
207 missingRoot ||
208 cwd === null ||
209 environmentId === null ||
210 (!refresh && directories.validatedDirectories.has(directoryPath)) ||
211 requests.pending.has(directoryPath)
212 ) {
213 return;
214 }
215 const controller = new AbortController();
216 requests.pending.set(directoryPath, controller);
217 updateDirectories((current) => {
218 const errors = new Map(current.errors);
219 errors.delete(directoryPath);
220 return { ...current, errors, loading: new Set(current.loading).add(directoryPath) };
221 });
222 const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
223 appAtomRegistry.refresh(atom);
224 return executeAtomQuery(appAtomRegistry, atom, {
225 signal: controller.signal,
226 reportFailure: false,
227 reportDefect: false,
228 }).then((result) => {
229 if (controller.signal.aborted) return;
230 requests.pending.delete(directoryPath);
231 updateDirectories((current) => {
232 const validatedDirectories = new Set(current.validatedDirectories).add(directoryPath);
233 const loading = new Set(current.loading);
234 loading.delete(directoryPath);
235 if (result._tag === "Success") {
236 const entries = new Map(current.entries);
237 entries.delete(directoryPath);
238 entries.set(
239 directoryPath,
240 result.value.entries.filter(
241 (entry) =>
242 entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
243 ),
244 );
245 const completeDirectories = new Set(current.completeDirectories);
246 if (result.value.truncated) completeDirectories.delete(directoryPath);
247 else completeDirectories.add(directoryPath);
248 return {
249 ...current,
250 entries,
251 loading,
252 completeDirectories,
253 discoveries: result.value.truncated
254 ? current.discoveries
255 : new Map(
256 [...current.discoveries].filter(
257 ([path]) => !contradictsListing(path, directoryPath, result.value.entries),
258 ),
259 ),
260 validatedDirectories,
261 listingCompletedAt: new Map(current.listingCompletedAt).set(
262 directoryPath,
263 result.timestamp,
264 ),
265 };
266 }
267 const error = Cause.squash(result.cause);
268 return {
269 ...current,
270 loading,
271 validatedDirectories,
272 errors: new Map(current.errors).set(
273 directoryPath,
274 error instanceof Error ? error.message : "Files unavailable",
275 ),
276 };
277 });
278 });
279 };
280 const missingRoot =
281 root.failure instanceof ProjectListEntriesError &&
282 root.failure.failure === "workspace_root_not_found";
283 const rootData = missingRoot ? null : root.data;
284 const rootListing = root.successResult ?? directories.rootListing;
285 if (
286 missingRoot &&
287 (directories.entries.size > 0 ||
288 directories.errors.size > 0 ||
289 directories.loading.size > 0 ||
290 directories.expandedPaths.size > 0 ||
291 directories.selectedPath !== null ||
292 directories.discoveries.size > 0)
293 ) {
294 setDirectories(() => createDirectories());
295 }
296 const { refresh: refreshSearch, data: searchData, successResult: searchResult } = search;
297 // A folder read fails at once while its environment is unreachable; read it again once a new
298 // session is up rather than leaving the error until someone refreshes.
299 const sessionGeneration =
300 environmentId === null
301 ? noSessionGeneration
302 : environmentCatalog.sessionGenerationAtom(environmentId);
303 // A listener alone does not compute the atom, so nothing would follow the connection.
304 useAtomMount(sessionGeneration);
305 useAtomSubscribe(sessionGeneration, () => {
306 for (const path of directories.errors.keys()) void loadDirectory(path, true);
307 });
308 const snapshot = (() => {
309 const merged = new Map(missingRoot ? [] : directories.discoveries);
310 if (searching && !missingRoot) {
311 for (const entry of searchData?.entries ?? []) merged.set(entry.path, entry);
312 }
313 const reachableDirectories = new Set<string>();
314 const visit = (items: ReadonlyArray<ProjectEntry>) => {
315 for (const entry of items) {
316 merged.set(entry.path, entry);
317 if (entry.kind === "directory") {
318 reachableDirectories.add(entry.path);
319 visit(directories.entries.get(entry.path) ?? []);
320 }
321 }
322 };
323 if (!missingRoot) {
324 const discoveries = new Map(directories.discoveries);
325 // Search can return only leaves; their inferred parents still own loaded children.
326 for (const entry of directories.discoveries.values()) {
327 const parts = entry.path.split("/");
328 for (let index = 1; index < parts.length; index++) {
329 const path = parts.slice(0, index).join("/");
330 if (!discoveries.has(path)) discoveries.set(path, { kind: "directory", path });
331 }
332 }
333 visit([...discoveries.values()]);
334 }
335 visit((rootData?.entries ?? []).filter((entry) => !entry.path.includes("/")));
336 return {
337 entries: [...merged.values()],
338 reachableDirectories,
339 searchResultPaths:
340 searching && !missingRoot
341 ? new Set((searchData?.entries ?? []).map((entry) => entry.path))
342 : null,
343 };
344 })();
345​
346 if (rootData) {
347 const deleted = (path: string, directory = false) => {
348 const parts = path.split("/");
349 for (let index = 0; index < parts.length; index++) {
350 const parent = parts.slice(0, index).join("/");
351 const listing = index === 0 ? rootData.entries : directories.entries.get(parent);
352 const child = parts.slice(0, index + 1).join("/");
353 const complete =
354 index === 0 ? !rootData.truncated : directories.completeDirectories.has(parent);
355 const entry = listing?.find((item) => item.path === child);
356 if (complete && listing && !entry) {
357 const listingCompletedAt =
358 index === 0 && directories.rootListing !== rootListing
359 ? rootListing?.timestamp
360 : directories.listingCompletedAt.get(parent);
361 // Cached queries keep their completion time across query switches.
362 // Equal-millisecond responses cannot prove a path postdates the listing.
363 const retained =
364 !(index === 0 && directories.rootListing !== rootListing) &&
365 [...directories.discoveries.keys()].some(
366 (path) => path === child || path.startsWith(`${child}/`),
367 );
368 const discovered =
369 retained ||
370 (searching &&
371 query === debouncedQuery &&
372 searchResult !== null &&
373 searchResult.timestamp > (listingCompletedAt ?? -Infinity) &&
374 searchData?.entries.some(
375 (item) => item.path === child || item.path.startsWith(`${child}/`),
376 ));
377 if (!discovered) return true;
378 }
379 if (entry && (directory || index < parts.length - 1) && entry.kind !== "directory")
380 return true;
381 }
382 return false;
383 };
384 const reconciled = (() => {
385 const current = directories;
386 const discoveries = new Map(current.discoveries);
387 if (current.rootListing !== rootListing && !rootData.truncated) {
388 for (const path of discoveries.keys()) {
389 if (contradictsListing(path, "", rootData.entries)) discoveries.delete(path);
390 }
391 }
392 if (searching && query === debouncedQuery && searchResult !== null) {
393 const ownedPaths = [
394 ...current.entries.keys(),
395 ...current.expandedPaths,
396 current.selectedPath,
397 ];
398 for (const entry of searchData?.entries ?? []) {
399 if (
400 ownedPaths.some((path) => path === entry.path || path?.startsWith(`${entry.path}/`)) &&
401 !deleted(entry.path, entry.kind === "directory")
402 )
403 discoveries.set(entry.path, entry);
404 }
405 }
406 const entries = new Map([...current.entries].filter(([path]) => !deleted(path, true)));
407 const errors = new Map([...current.errors].filter(([path]) => !deleted(path, true)));
408 const expandedPaths = new Set(
409 [...current.expandedPaths].filter((path) => !deleted(path, true)),
410 );
411 const selectedPath =
412 current.selectedPath !== null && deleted(current.selectedPath)
413 ? null
414 : current.selectedPath;
415 if (
416 entries.size === current.entries.size &&
417 errors.size === current.errors.size &&
418 expandedPaths.size === current.expandedPaths.size &&
419 selectedPath === current.selectedPath &&
420 current.rootListing === rootListing &&
421 discoveries.size === current.discoveries.size &&
422 [...discoveries].every(([path, entry]) => current.discoveries.get(path) === entry)
423 )
424 return current;
425 const completeDirectories = new Set(
426 [...current.completeDirectories].filter((path) => entries.has(path)),
427 );
428 return {
429 ...current,
430 rootListing,
431 discoveries,
432 listingCompletedAt: new Map(
433 [...current.listingCompletedAt].filter(([path]) => path === "" || entries.has(path)),
434 ).set(
435 "",
436 current.rootListing === rootListing
437 ? (current.listingCompletedAt.get("") ?? -Infinity)
438 : (rootListing?.timestamp ?? -Infinity),
439 ),
440 entries,
441 errors,
442 expandedPaths,
443 selectedPath,
444 completeDirectories,
445 validatedDirectories: new Set(
446 [...current.validatedDirectories].filter((path) => !deleted(path, true)),
447 ),
448 };
449 })();
450 if (reconciled !== directories) setDirectories(() => reconciled);
451 }
452​
453 const refresh = () => {
454 const requests = getRequests(requestsByTarget.current, target);
455 if (!requests.active) return Promise.resolve();
456 refreshRoot();
457 if (searching && !missingRoot) refreshSearch();
458 const paths = new Set(
459 [...directories.entries.keys(), ...directories.errors.keys(), ...directories.loading].filter(
460 (path) => snapshot.reachableDirectories.has(path),
461 ),
462 );
463 for (const controller of requests.pending.values()) controller.abort();
464 requests.pending.clear();
465 const version = ++requests.refreshVersion;
466 updateDirectories((current) => ({
467 ...current,
468 errors: new Map(),
469 loading: new Set(),
470 isRefreshing: true,
471 }));
472 const remaining = paths.values();
473 const worker = async () => {
474 while (requests.active && version === requests.refreshVersion) {
475 const next = remaining.next();
476 if (next.done) return;
477 await loadDirectory(next.value, true);
478 }
479 };
480 const queries =
481 cwd !== null && environmentId !== null
482 ? [
483 projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath: "" } }),
484 ...(searching && !missingRoot
485 ? [
486 projectEnvironment.searchEntries({
487 environmentId,
488 input: { cwd, query: debouncedQuery, limit: 200 },
489 }),
490 ]
491 : []),
492 ]
493 : [];
494 const work = [
495 ...queries.map((atom) =>
496 executeAtomQuery(appAtomRegistry, atom, { reportFailure: false, reportDefect: false }),
497 ),
498 ...Array.from({ length: Math.min(4, paths.size) }, () => worker()),
499 ];
500 return Promise.all(work).finally(() => {
501 if (version === requests.refreshVersion) {
502 updateDirectories((current) => ({ ...current, isRefreshing: false }));
503 }
504 });
505 };
506​
507 const revealSelection = (path: string | null) => {
508 if (missingRoot) return;
509 updateDirectories((current) => {
510 const previous = current.revealedSelection;
511 const handled = previous.path === path ? previous.ancestors : new Set<string>();
512 const parts = path?.split("/").filter(Boolean) ?? [];
513 const ancestors = parts
514 .slice(1)
515 .map((_, index) => parts.slice(0, index + 1).join("/"))
516 .filter(
517 (ancestor) =>
518 !handled.has(ancestor) &&
519 snapshot.entries.some(
520 (entry) =>
521 (entry.kind === "directory" && entry.path === ancestor) ||
522 (entry.path === path && entry.path.startsWith(`${ancestor}/`)),
523 ),
524 );
525 if (previous.path === path && ancestors.length === 0) return current;
526 return {
527 ...current,
528 discoveries: new Map([
529 ...current.discoveries,
530 ...snapshot.entries
531 .filter((entry) => entry.path === path)
532 .map((entry) => [entry.path, entry] as const),
533 ]),
534 selectedPath: path,
535 revealedSelection: { path, ancestors: new Set([...handled, ...ancestors]) },
536 expandedPaths: new Set([...current.expandedPaths, ...ancestors]),
537 };
538 });
539 };
540​
541 const setExpandedPaths = useCallback(
542 (update: (current: ReadonlySet<string>) => ReadonlySet<string>) =>
543 setDirectories((current) => {
544 const expandedPaths = update(current.expandedPaths);
545 return expandedPaths === current.expandedPaths
546 ? current
547 : { ...current, expandedPaths: new Set(expandedPaths) };
548 }),
549 [setDirectories],
550 );
551​
552 return {
553 revealSelection,
554 expandedPaths: directories.expandedPaths,
555 setExpandedPaths,
556 selectedPath: directories.selectedPath,
557 selectPath: (selectedPath: string) =>
558 updateDirectories((current) => ({ ...current, selectedPath })),
559 entries: snapshot.entries,
560 searchResultPaths: snapshot.searchResultPaths,
561 isRefreshing: directories.isRefreshing,
562 error:
563 root.error ??
564 (searching ? search.error : null) ??
565 [...directories.errors].find(([path]) => snapshot.reachableDirectories.has(path))?.[1] ??
566 null,
567 isPending:
568 !missingRoot &&
569 (root.isPending ||
570 directories.loading.size > 0 ||
571 (searching && (query !== debouncedQuery || search.isPending))),
572 searchTruncated: !missingRoot && searching && (search.data?.truncated ?? false),
573 loadedDirectories: new Set(directories.entries.keys()),
574 loadingDirectories: directories.loading,
575 loadDirectory: (path: string, retry = false) =>
576 loadDirectory(path, retry && directories.errors.has(path)),
577 refresh,
578 };