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}
54
55function getProjectEntriesQueryAtom(
56 environmentId: EnvironmentId,
57 cwd: string,
58 directoryPath?: string,
59) {
60 return projectEnvironment.listEntries({
61 environmentId,
62 input: { cwd, ...(directoryPath !== undefined ? { directoryPath } : {}) },
63 });
64}
65
66export function getProjectFileQueryAtom(
67 environmentId: EnvironmentId,
68 cwd: string,
69 relativePath: string | null,
70) {
71 return projectEnvironment.readFile({
72 environmentId,
73 input: { cwd, relativePath: relativePath ?? EMPTY_PROJECT_FILE_PATH },
74 });
75}
76
77export function setProjectFileQueryData(
78 environmentId: EnvironmentId,
79 cwd: string,
80 relativePath: string,
81 contents: string,
82): void {
83 const atom = optimisticFileAtom(environmentId, cwd, relativePath);
84 if (!unsavedFileMounts.has(atom)) {
85 unsavedFileMounts.set(atom, appAtomRegistry.mount(atom));
86 }
87 appAtomRegistry.set(atom, {
88 confirmedAgainst: undefined,
89 data: {
90 relativePath,
91 contents,
92 byteLength: new TextEncoder().encode(contents).byteLength,
93 truncated: false,
94 },
95 });
96}
97
98export function getOptimisticProjectFileQueryData(
99 environmentId: EnvironmentId,
100 cwd: string,
101 relativePath: string,
102): ProjectReadFileResult | null {
103 return appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath))?.data ?? null;
104}
105
106export function getProjectFileContents(
107 environmentId: EnvironmentId,
108 cwd: string,
109 relativePath: string,
110): string | undefined {
111 const optimistic = getOptimisticProjectFileQueryData(environmentId, cwd, relativePath);
112 if (optimistic) return optimistic.contents;
113 const result = appAtomRegistry.get(getProjectFileQueryAtom(environmentId, cwd, relativePath));
114 return Option.getOrUndefined(AsyncResult.value(result))?.contents;
115}
116
117export function getUnsavedProjectFileQueryData(
118 environmentId: EnvironmentId,
119 cwd: string,
120 relativePath: string,
121): ProjectReadFileResult | null {
122 const optimistic = appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath));
123 return optimistic?.confirmedAgainst === undefined ? (optimistic?.data ?? null) : null;
124}
125
126export function confirmProjectFileQueryData(
127 environmentId: EnvironmentId,
128 cwd: string,
129 relativePath: string,
130 contents: string,
131): boolean {
132 const atom = optimisticFileAtom(environmentId, cwd, relativePath);
133 const optimisticFile = appAtomRegistry.get(atom);
134 if (optimisticFile?.data.contents !== contents) return false;
135
136 const queryAtom = getProjectFileQueryAtom(environmentId, cwd, relativePath);
137 const confirmed = {
138 ...optimisticFile,
139 confirmedAgainst: appAtomRegistry.get(queryAtom),
140 };
141 appAtomRegistry.set(atom, confirmed);
142 releaseUnsavedFile(atom);
143 appAtomRegistry.refresh(queryAtom);
144 void executeAtomQuery(appAtomRegistry, queryAtom, {
145 reportDefect: false,
146 reportFailure: false,
147 }).then((result) => {
148 if (result._tag === "Success" && appAtomRegistry.get(atom) === confirmed) {
149 appAtomRegistry.set(atom, null);
150 }
151 });
152 return true;
153}
154
155export function resolveProjectFileQueryData(
156 environmentId: EnvironmentId,
157 cwd: string,
158 relativePath: string | null,
159 data: ProjectReadFileResult | null,
160): ProjectReadFileResult | null {
161 if (relativePath === null) return data;
162 return appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath))?.data ?? data;
163}
164
165export function clearProjectFileQueryData(
166 environmentId: EnvironmentId,
167 cwd: string,
168 relativePath: string,
169): void {
170 const atom = optimisticFileAtom(environmentId, cwd, relativePath);
171 appAtomRegistry.set(atom, null);
172 releaseUnsavedFile(atom);
173}
174
175function failureCause<A>(result: AsyncResult.AsyncResult<A, unknown>): unknown {
176 return result._tag === "Failure" ? Cause.squash(result.cause) : null;
177}
178
179function errorMessage(cause: unknown): string | null {
180 if (cause === null) return null;
181 return cause instanceof Error ? cause.message : "Workspace query failed.";
182}
183
184const isProjectReadFileError = Schema.is(ProjectReadFileError);
185
186export function useProjectEntriesQuery(
187 environmentId: EnvironmentId,
188 cwd: string,
189 directoryPath?: string,
190): ProjectQueryState<ProjectListEntriesResult> {
191 const fileAccess = useFilesystemReadAccess(environmentId);
192 const { canReadFiles } = fileAccess;
193 const atom = canReadFiles
194 ? getProjectEntriesQueryAtom(environmentId, cwd, directoryPath)
195 : EMPTY_PROJECT_ENTRIES_QUERY_ATOM;
196 const result = useAtomValue(atom);
197 const refreshAtom = useAtomRefresh(atom);
198 const refresh = () => refreshAtom();
199 return {
200 data: Option.getOrNull(AsyncResult.value(result)),
201 error: fileAccess.isPending
202 ? null
203 : canReadFiles
204 ? errorMessage(failureCause(result))
205 : (fileAccess.error ?? "This connection cannot read host files."),
206 isPending: fileAccess.isPending || result.waiting,
207 refresh,
208 };
209}
210
211/**
212 * An empty query is a valid request — the index answers it with
213 * frecency-ordered files, so the picker's initial view is recent files without
214 * transferring the full workspace listing.
215 */
216export function useProjectFilePickerQuery(
217 environmentId: EnvironmentId,
218 cwd: string,
219 query: string,
220 limit: number,
221 options?: { readonly imageOnly?: boolean },
222) {
223 const search = useProjectPathSearch(
224 {
225 environmentId,
226 cwd,
227 query,
228 kind: "file",
229 ...(options?.imageOnly ? { imageOnly: true } : {}),
230 },
231 limit,
232 { allowEmptyQuery: true },
233 );
234
235 return {
236 entries: search.isPending ? [] : search.entries,
237 error: search.error,
238 isPending: search.isPending,
239 matchedQuery: search.searchedQuery,
240 };
241}
242
243export function useProjectFileQuery(
244 environmentId: EnvironmentId,
245 cwd: string,
246 relativePath: string | null,
247 enabled = true,
248): ProjectFileQueryState {
249 // A media path is not skipped here: a folder named `assets.png` is only
250 // knowable as a folder from the read failure.
251 const fileAccess = useFilesystemReadAccess(environmentId);
252 const { canReadFiles } = fileAccess;
253 const isQueryEnabled = enabled;
254 const atom =
255 enabled && canReadFiles
256 ? getProjectFileQueryAtom(environmentId, cwd, relativePath)
257 : EMPTY_PROJECT_FILE_QUERY_ATOM;
258 const result = useAtomValue(atom);
259 const refreshAtom = useAtomRefresh(atom);
260 const refresh = () => refreshAtom();
261 const data = Option.getOrNull(AsyncResult.value(result));
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
269 return {
270 data: canReadFiles ? (optimisticFile?.data ?? data) : null,
271 error:
272 !isQueryEnabled || fileAccess.isPending
273 ? null
274 : canReadFiles
275 ? errorMessage(cause)
276 : (fileAccess.error ?? "This connection cannot read host files."),
277 isPending: isQueryEnabled && (fileAccess.isPending || result.waiting),
278 readError,
279 isNotFile: readError?.failure === "path_not_file",
280 refresh,
281 };
282}