Open History to see the last commit
1import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
2import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
3import * as Cause from "effect/Cause";
4import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
6import { appAtomRegistry } from "~/rpc/atomRegistry";
7import { projectEnvironment } from "~/state/projects";
8
9/** Loads only requested directories; collapsing a folder keeps its children cached. */
10export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
11 const [directories, setDirectories] = useState(new Map<string, readonly ProjectEntry[]>());
12 const [errors, setErrors] = useState(new Map<string, string>());
13 const [pending, setPending] = useState(0);
14 // First loads only: a refresh keeps showing the cached children, so it gets no row spinner.
15 const [loadingDirectories, setLoadingDirectories] = useState<ReadonlySet<string>>(new Set());
16 const requests = useRef(new Map<string, Promise<void>>());
17 const loaded = useRef(new Set<string>());
18 const requested = useRef(new Set<string>());
19 const active = useRef(true);
20 const running = useRef(0);
21 const waiting = useRef<Array<() => void>>([]);
22
23 const load = useCallback(
24 function loadDirectory(directoryPath: string, refresh = false): Promise<void> {
25 const existing = requests.current.get(directoryPath);
26 if (existing)
27 return refresh ? existing.then(() => loadDirectory(directoryPath, true)) : existing;
28 if (!refresh && loaded.current.has(directoryPath)) return Promise.resolve();
29 loaded.current.add(directoryPath);
30 requested.current.add(directoryPath);
31 const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
32 setPending((count) => count + 1);
33 if (!refresh) setLoadingDirectories((previous) => new Set(previous).add(directoryPath));
34 const request = (async () => {
35 if (running.current >= 4)
36 await new Promise<void>((resolve) => waiting.current.push(resolve));
37 else running.current++;
38 try {
39 if (!active.current) return undefined;
40 return await executeAtomQuery(appAtomRegistry, atom, {
41 refresh: true,
42 reportFailure: false,
43 reportDefect: false,
44 });
45 } finally {
46 const next = waiting.current.shift();
47 if (next) next();
48 else running.current--;
49 }
50 })()
51 .then((result) => {
52 if (!active.current || !result) return;
53 if (result._tag === "Success") {
54 setDirectories((previous) =>
55 new Map(previous).set(
56 directoryPath,
57 result.value.entries.filter(
58 (entry) =>
59 entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
60 ),
61 ),
62 );
63 setErrors((previous) => {
64 const next = new Map(previous);
65 next.delete(directoryPath);
66 return next;
67 });
68 } else {
69 loaded.current.delete(directoryPath);
70 const cause = Cause.squash(result.cause);
71 setErrors((previous) =>
72 new Map(previous).set(
73 directoryPath,
74 cause instanceof Error ? cause.message : "Unable to load folder.",
75 ),
76 );
77 }
78 })
79 .finally(() => {
80 requests.current.delete(directoryPath);
81 if (!active.current) return;
82 setPending((count) => count - 1);
83 if (!refresh)
84 setLoadingDirectories((previous) => {
85 const next = new Set(previous);
86 next.delete(directoryPath);
87 return next;
88 });
89 });
90 requests.current.set(directoryPath, request);
91 return request;
92 },
93 [cwd, environmentId],
94 );
95
96 useEffect(() => {
97 active.current = true;
98 void load("");
99 return () => {
100 active.current = false;
101 };
102 }, [load]);
103
104 const entries = useMemo(() => {
105 const result: ProjectEntry[] = [];
106 const visit = (path: string) => {
107 for (const entry of directories.get(path) ?? []) {
108 result.push(entry);
109 if (entry.kind === "directory") visit(entry.path);
110 }
111 };
112 visit("");
113 return result;
114 }, [directories]);
115
116 const reachableDirectories = useMemo(
117 () =>
118 new Set([
119 "",
120 ...entries.filter((entry) => entry.kind === "directory").map((entry) => entry.path),
121 ]),
122 [entries],
123 );
124
125 const refresh = useCallback(() => {
126 // Refresh folders already visited, preserving the current expansion state.
127 const paths = [...requested.current].filter((path) => reachableDirectories.has(path));
128 let next = 0;
129 const worker = async () => {
130 while (next < paths.length && active.current) {
131 const path = paths[next++];
132 if (path !== undefined) await load(path, true);
133 }
134 };
135 for (let index = 0; index < Math.min(4, paths.length); index++) void worker();
136 }, [load, reachableDirectories]);
137
138 return {
139 entries,
140 load,
141 refresh,
142 isPending: pending > 0,
143 loadingDirectories,
144 ready: directories.has(""),
145 error: [...errors].find(([path]) => reachableDirectories.has(path))?.[1] ?? null,
146 };
147}