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

useDirectoryEntries.ts

157 lines5.8 KB

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 followUpRefreshes = useRef(new Map<string, Promise<void>>());
20 const loaded = useRef(new Set<string>());
21 const requested = useRef(new Set<string>());
22 const active = useRef(true);
23 const running = useRef(0);
24 const waiting = useRef<Array<() => void>>([]);
25​
26 const startRequest = (directoryPath: string, refresh: boolean): Promise<void> => {
27 loaded.current.add(directoryPath);
28 requested.current.add(directoryPath);
29 const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
30 const request = (async () => {
31 if (running.current >= 4) await new Promise<void>((resolve) => waiting.current.push(resolve));
32 else running.current++;
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 if (!refresh) return existing;
92 let followUp = followUpRefreshes.current.get(directoryPath);
93 if (!followUp) {
94 followUp = existing.then(() => {
95 followUpRefreshes.current.delete(directoryPath);
96 if (active.current) return loadDirectory(directoryPath, true);
97 });
98 followUpRefreshes.current.set(directoryPath, followUp);
99 }
100 return followUp;
101 }
102 if (!refresh && loaded.current.has(directoryPath)) return Promise.resolve();
103 setPending((count) => count + 1);
104 if (!refresh) setLoadingDirectories((previous) => new Set(previous).add(directoryPath));
105 return startRequest(directoryPath, refresh);
106 };
107​
108 // 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
109 useEffect(() => {
110 active.current = true;
111 if (!requests.current.has("") && !loaded.current.has("")) void startRequest("", false);
112 return () => {
113 active.current = false;
114 };
115 }, [startRequest]);
116​
117 // A folder read fails at once while its environment is unreachable; read it again once a new
118 // session is up rather than leaving the error until someone retries by hand.
119 const sessionGeneration = environmentCatalog.sessionGenerationAtom(environmentId);
120 // A listener alone does not compute the atom, so nothing would follow the connection.
121 useAtomMount(sessionGeneration);
122 useAtomSubscribe(sessionGeneration, () => {
123 for (const path of errors.keys()) void load(path);
124 });
125​
126 const entries: ProjectEntry[] = [];
127 const visit = (path: string) => {
128 for (const entry of directories.get(path) ?? []) {
129 entries.push(entry);
130 if (entry.kind === "directory") visit(entry.path);
131 }
132 };
133 visit("");
134​
135 const reachableDirectories = new Set([
136 "",
137 ...entries.filter((entry) => entry.kind === "directory").map((entry) => entry.path),
138 ]);
139​
140 const refresh = () => {
141 const paths = [...requested.current].filter((path) => reachableDirectories.has(path));
142 for (const path of paths) {
143 if (!active.current) break;
144 void load(path, true);
145 }
146 };
147​
148 return {
149 entries,
150 load,
151 refresh,
152 isPending: pending > 0,
153 loadingDirectories,
154 ready: directories.has(""),
155 error: [...errors].find(([path]) => reachableDirectories.has(path))?.[1] ?? null,
156 };