Open History to see the last commit
1import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2import {
3 type EnvironmentId,
4 type ProjectListEntriesResult,
5 ProjectReadFileError,
6 type ProjectReadFileResult,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as Option from "effect/Option";
10import * as Schema from "effect/Schema";
11import { AsyncResult, Atom } from "effect/reactivity";
12
13import { appAtomRegistry } from "~/rpc/atomRegistry";
14import { useFilesystemReadAccess } from "~/state/filesystem";
15import { projectEnvironment } from "~/state/projects";
16import { useProjectPathSearch } from "~/state/queries";
17import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
18
19const EMPTY_PROJECT_FILE_PATH = "";
20const EMPTY_PROJECT_ENTRIES_QUERY_ATOM = Atom.make(
21 AsyncResult.initial<ProjectListEntriesResult, never>(false),
22);
23const EMPTY_PROJECT_FILE_QUERY_ATOM = Atom.make(
24 AsyncResult.initial<ProjectReadFileResult, never>(false),
25).pipe(Atom.withLabel("project-file-query:empty"));
26export function optimisticFileAtom(
27 environmentId: EnvironmentId,
28 cwd: string,
29 relativePath: string,
30) {
31 return projectEnvironment.optimisticFile({ environmentId, cwd, relativePath });
32}
33
34// Dirty contents must survive a closed preview, including failed or unauthorized saves.
35const unsavedFileMounts = new Map<ReturnType<typeof optimisticFileAtom>, () => void>();
36
37function releaseUnsavedFile(atom: ReturnType<typeof optimisticFileAtom>): void {
38 const unmount = unsavedFileMounts.get(atom);
39 unsavedFileMounts.delete(atom);
40 unmount?.();
41}
42
43interface ProjectQueryState<A> {
44 readonly data: A | null;
45 readonly error: string | null;
46 readonly isPending: boolean;
47 readonly refresh: () => void;
48}
49
50interface ProjectFileQueryState extends ProjectQueryState<ProjectReadFileResult> {
51 readonly readError: ProjectReadFileError | null;
52 readonly isNotFile: boolean;
53 readonly isFile: boolean;
54}
55
56function getProjectEntriesQueryAtom(
57 environmentId: EnvironmentId,
58 cwd: string,
59 directoryPath?: string,
60) {
61 return projectEnvironment.listEntries({
62 environmentId,
63 input: { cwd, ...(directoryPath !== undefined ? { directoryPath } : {}) },
64 });
65}
66
67export function getProjectFileQueryAtom(
68 environmentId: EnvironmentId,
69 cwd: string,
70 relativePath: string | null,
71) {
72 return projectEnvironment.readFile({
73 environmentId,
74 input: { cwd, relativePath: relativePath ?? EMPTY_PROJECT_FILE_PATH },
75 });
76}
77
78export function setProjectFileQueryData(
79 environmentId: EnvironmentId,
80 cwd: string,
81 relativePath: string,
82 contents: string,
83): void {
84 const atom = optimisticFileAtom(environmentId, cwd, relativePath);
85 if (!unsavedFileMounts.has(atom)) {
86 unsavedFileMounts.set(atom, appAtomRegistry.mount(atom));
87 }
88 appAtomRegistry.set(atom, {
89 confirmedAgainst: undefined,
90 data: {
91 relativePath,
92 contents,
93 byteLength: new TextEncoder().encode(contents).byteLength,
94 truncated: false,
95 },
96 });
97}
98
99export function getOptimisticProjectFileQueryData(
100 environmentId: EnvironmentId,
101 cwd: string,
102 relativePath: string,
103): ProjectReadFileResult | null {
104 return appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath))?.data ?? null;
105}
106
107export function getProjectFileContents(
108 environmentId: EnvironmentId,
109 cwd: string,
110 relativePath: string,
111): string | undefined {
112 const optimistic = getOptimisticProjectFileQueryData(environmentId, cwd, relativePath);
113 if (optimistic) return optimistic.contents;
114 const result = appAtomRegistry.get(getProjectFileQueryAtom(environmentId, cwd, relativePath));
115 return Option.getOrUndefined(AsyncResult.value(result))?.contents;
116}
117
118export function getUnsavedProjectFileQueryData(
119 environmentId: EnvironmentId,
120 cwd: string,
121 relativePath: string,
122): ProjectReadFileResult | null {
123 const optimistic = appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath));
124 return optimistic?.confirmedAgainst === undefined ? (optimistic?.data ?? null) : null;
125}
126
127export function confirmProjectFileQueryData(
128 environmentId: EnvironmentId,
129 cwd: string,
130 relativePath: string,
131 contents: string,
132): boolean {
133 const atom = optimisticFileAtom(environmentId, cwd, relativePath);
134 const optimisticFile = appAtomRegistry.get(atom);
135 if (optimisticFile?.data.contents !== contents) return false;
136
137 const queryAtom = getProjectFileQueryAtom(environmentId, cwd, relativePath);
138 const confirmed = {
139 ...optimisticFile,
140 confirmedAgainst: appAtomRegistry.get(queryAtom),
141 };
142 appAtomRegistry.set(atom, confirmed);
143 releaseUnsavedFile(atom);
144 appAtomRegistry.refresh(queryAtom);
145 void executeAtomQuery(appAtomRegistry, queryAtom, {
146 reportDefect: false,
147 reportFailure: false,
148 }).then((result) => {
149 if (result._tag === "Success" && appAtomRegistry.get(atom) === confirmed) {
150 appAtomRegistry.set(atom, null);
151 }
152 });
153 return true;
154}
155
156export function resolveProjectFileQueryData(
157 environmentId: EnvironmentId,
158 cwd: string,
159 relativePath: string | null,
160 data: ProjectReadFileResult | null,
161): ProjectReadFileResult | null {
162 if (relativePath === null) return data;
163 return appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath))?.data ?? data;
164}
165
166export function clearProjectFileQueryData(
167 environmentId: EnvironmentId,
168 cwd: string,
169 relativePath: string,
170): void {
171 const atom = optimisticFileAtom(environmentId, cwd, relativePath);
172 appAtomRegistry.set(atom, null);
173 releaseUnsavedFile(atom);
174}
175
176function failureCause<A>(result: AsyncResult.AsyncResult<A, unknown>): unknown {
177 return result._tag === "Failure" ? Cause.squash(result.cause) : null;
178}
179
180function errorMessage(cause: unknown): string | null {
181 if (cause === null) return null;
182 return cause instanceof Error ? cause.message : "Workspace query failed.";
183}
184
185const isProjectReadFileError = Schema.is(ProjectReadFileError);
186
187export function useProjectEntriesQuery(
188 environmentId: EnvironmentId,
189 cwd: string,
190 directoryPath?: string,
191): ProjectQueryState<ProjectListEntriesResult> {
192 const fileAccess = useFilesystemReadAccess(environmentId);
193 const { canReadFiles } = fileAccess;
194 const atom = canReadFiles
195 ? getProjectEntriesQueryAtom(environmentId, cwd, directoryPath)
196 : EMPTY_PROJECT_ENTRIES_QUERY_ATOM;
197 const result = useAtomValue(atom);
198 const refreshAtom = useAtomRefresh(atom);
199 const refresh = () => refreshAtom();
200 return {
201 data: Option.getOrNull(AsyncResult.value(result)),
202 error: fileAccess.isPending
203 ? null
204 : canReadFiles
205 ? errorMessage(failureCause(result))
206 : (fileAccess.error ?? "This connection cannot read host files."),
207 isPending: fileAccess.isPending || result.waiting,
208 refresh,
209 };
210}
211
212/**
213 * An empty query is a valid request — the index answers it with
214 * frecency-ordered files, so the picker's initial view is recent files without
215 * transferring the full workspace listing.
216 */
217export function useProjectFilePickerQuery(
218 environmentId: EnvironmentId,
219 cwd: string,
220 query: string,
221 limit: number,
222 options?: { readonly imageOnly?: boolean },
223) {
224 const search = useProjectPathSearch(
225 {
226 environmentId,
227 cwd,
228 query,
229 kind: "file",
230 ...(options?.imageOnly ? { imageOnly: true } : {}),
231 },
232 limit,
233 { allowEmptyQuery: true },
234 );
235
236 return {
237 entries: search.isPending ? [] : search.entries,
238 error: search.error,
239 isPending: search.isPending,
240 matchedQuery: search.searchedQuery,
241 };
242}
243
244export function useProjectFileQuery(
245 environmentId: EnvironmentId,
246 cwd: string,
247 relativePath: string | null,
248 enabled = true,
249): ProjectFileQueryState {
250 // A media path is not skipped here: a folder named `assets.png` is only
251 // knowable as a folder from the read failure.
252 const fileAccess = useFilesystemReadAccess(environmentId);
253 const { canReadFiles } = fileAccess;
254 const isQueryEnabled = enabled;
255 const atom =
256 enabled && canReadFiles
257 ? getProjectFileQueryAtom(environmentId, cwd, relativePath)
258 : EMPTY_PROJECT_FILE_QUERY_ATOM;
259 const result = useAtomValue(atom);
260 const refreshAtom = useAtomRefresh(atom);
261 const refresh = () => refreshAtom();
262 const optimisticResult = useAtomValue(
263 optimisticFileAtom(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH),
264 );
265 const optimisticFile = relativePath === null ? null : optimisticResult;
266 const cause = failureCause(result);
267 const readError = isProjectReadFileError(cause) ? cause : null;
268 const data = canReadFiles
269 ? (optimisticFile?.data ?? Option.getOrNull(AsyncResult.value(result)))
270 : null;
271 const isNotFile = readError?.failure === "path_not_file";
272
273 return {
274 data,
275 error:
276 !isQueryEnabled || fileAccess.isPending
277 ? null
278 : canReadFiles
279 ? errorMessage(cause)
280 : (fileAccess.error ?? "This connection cannot read host files."),
281 isPending: isQueryEnabled && (fileAccess.isPending || result.waiting),
282 readError,
283 isNotFile,
284 // A folder error overrides cached contents retained across failed refreshes.
285 isFile: !isNotFile && (data !== null || readError?.failure === "binary_file"),
286 refresh,
287 };
288}