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