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