Open History to see the last commit
1import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
2import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
3import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
4import * as Cause from "effect/Cause";
5import { useEffect, useRef, useState } from "react";
6
7import { environmentCatalog } from "~/connection/catalog";
8import { appAtomRegistry } from "~/rpc/atomRegistry";
9import { projectEnvironment } from "~/state/projects";
10
11export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
12 const [directories, setDirectories] = useState(new Map<string, readonly ProjectEntry[]>());
13 const [errors, setErrors] = useState(new Map<string, string>());
14 const [pending, setPending] = useState(1);
15 const [loadingDirectories, setLoadingDirectories] = useState<ReadonlySet<string>>(
16 () => new Set([""]),
17 );
18 const requests = useRef(new Map<string, Promise<void>>());
19 const loaded = useRef(new Set<string>());
20 const requested = useRef(new Set<string>());
21 const active = useRef(true);
22 const running = useRef(0);
23 const waiting = useRef<Array<() => void>>([]);
24
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 const result = active.current
33 ? await executeAtomQuery(appAtomRegistry, atom, {
34 refresh: true,
35 reportFailure: false,
36 reportDefect: false,
37 })
38 : undefined;
39 const next = waiting.current.shift();
40 if (next) next();
41 else running.current--;
42 return result;
43 })()
44 .then((result) => {
45 if (!active.current || !result) return;
46 if (result._tag === "Success") {
47 setDirectories((previous) =>
48 new Map(previous).set(
49 directoryPath,
50 result.value.entries.filter(
51 (entry) =>
52 entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
53 ),
54 ),
55 );
56 setErrors((previous) => {
57 const next = new Map(previous);
58 next.delete(directoryPath);
59 return next;
60 });
61 } else {
62 loaded.current.delete(directoryPath);
63 const cause = Cause.squash(result.cause);
64 setErrors((previous) =>
65 new Map(previous).set(
66 directoryPath,
67 cause instanceof Error ? cause.message : "Unable to load folder.",
68 ),
69 );
70 }
71 })
72 .finally(() => {
73 requests.current.delete(directoryPath);
74 if (!active.current) return;
75 setPending((count) => count - 1);
76 if (!refresh)
77 setLoadingDirectories((previous) => {
78 const next = new Set(previous);
79 next.delete(directoryPath);
80 return next;
81 });
82 });
83 requests.current.set(directoryPath, request);
84 return request;
85 };
86
87 const load = function loadDirectory(directoryPath: string, refresh = false): Promise<void> {
88 const existing = requests.current.get(directoryPath);
89 if (existing)
90 return refresh ? existing.then(() => loadDirectory(directoryPath, true)) : existing;
91 if (!refresh && loaded.current.has(directoryPath)) return Promise.resolve();
92 setPending((count) => count + 1);
93 if (!refresh) setLoadingDirectories((previous) => new Set(previous).add(directoryPath));
94 return startRequest(directoryPath, refresh);
95 };
96
97 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the root directory read on mount and marks the hook inactive so late reads are ignored
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 // A folder read fails at once while its environment is unreachable; read it again once a new
107 // session is up rather than leaving the error until someone retries by hand.
108 const sessionGeneration = environmentCatalog.sessionGenerationAtom(environmentId);
109 // A listener alone does not compute the atom, so nothing would follow the connection.
110 useAtomMount(sessionGeneration);
111 useAtomSubscribe(sessionGeneration, () => {
112 for (const path of errors.keys()) void load(path);
113 });
114
115 const entries: ProjectEntry[] = [];
116 const visit = (path: string) => {
117 for (const entry of directories.get(path) ?? []) {
118 entries.push(entry);
119 if (entry.kind === "directory") visit(entry.path);
120 }
121 };
122 visit("");
123
124 const reachableDirectories = new Set([
125 "",
126 ...entries.filter((entry) => entry.kind === "directory").map((entry) => entry.path),
127 ]);
128
129 const refresh = () => {
130 const paths = [...requested.current].filter((path) => reachableDirectories.has(path));
131 const workerCount = Math.min(4, paths.length);
132 const worker = async () => {
133 while (active.current) {
134 const path = paths.shift();
135 if (path === undefined) return;
136 await load(path, true);
137 }
138 };
139 for (let index = 0; index < workerCount; index++) void worker();
140 };
141
142 return {
143 entries,
144 load,
145 refresh,
146 isPending: pending > 0,
147 loadingDirectories,
148 ready: directories.has(""),
149 error: [...errors].find(([path]) => reachableDirectories.has(path))?.[1] ?? null,
150 };
151}