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