Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useDirectoryEntries.ts

136 lines4.7 KB

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