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