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