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

useFileTreeEntries.ts

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