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

projectFilesQueryState.ts

291 lines9.2 KB

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";
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 });
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?.();
43​
44interface ProjectQueryState<A> {
45 readonly data: A | null;
46 readonly error: string | null;
47 readonly isPending: boolean;
48 readonly refresh: () => void;
50​
51interface ProjectFileQueryState extends ProjectQueryState<ProjectReadFileResult> {
52 readonly readError: ProjectReadFileError | null;
53 readonly isNotFile: boolean;
54 readonly isFile: boolean;
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 });
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 });
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 confirmedAgainst: undefined,
95 data: {
96 relativePath,
97 contents,
98 byteLength: new TextEncoder().encode(contents).byteLength,
99 truncated: false,
100 },
101 });
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;
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;
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?.confirmedAgainst === undefined ? (optimistic?.data ?? null) : null;
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 const confirmed = {
145 ...optimisticFile,
146 confirmedAgainst: appAtomRegistry.get(queryAtom),
147 };
148 appAtomRegistry.set(atom, confirmed);
149 releaseUnsavedFile(atom);
150 appAtomRegistry.refresh(queryAtom);
151 void executeAtomQuery(appAtomRegistry, queryAtom, {
152 reportDefect: false,
153 reportFailure: false,
154 }).then((result) => {
155 if (result._tag === "Success" && appAtomRegistry.get(atom) === confirmed) {
156 appAtomRegistry.set(atom, null);
157 }
158 });
159 return true;
161​
162export function resolveProjectFileQueryData(
163 environmentId: EnvironmentId,
164 cwd: string,
165 relativePath: string | null,
166 data: ProjectReadFileResult | null,
167): ProjectReadFileResult | null {
168 if (relativePath === null) return data;
169 return appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath))?.data ?? data;
171​
172export function clearProjectFileQueryData(
173 environmentId: EnvironmentId,
174 cwd: string,
175 relativePath: string,
176): void {
177 const atom = optimisticFileAtom(environmentId, cwd, relativePath);
178 appAtomRegistry.set(atom, null);
179 releaseUnsavedFile(atom);
181​
182function failureCause<A>(result: AsyncResult.AsyncResult<A, unknown>): unknown {
183 return result._tag === "Failure" ? Cause.squash(result.cause) : null;
185​
186function errorMessage(cause: unknown): string | null {
187 if (cause === null) return null;
188 return cause instanceof Error ? cause.message : "Workspace query failed.";
190​
191const isProjectReadFileError = Schema.is(ProjectReadFileError);
192​
193export function useProjectEntriesQuery(
194 environmentId: EnvironmentId,
195 cwd: string,
196 directoryPath?: string,
197): ProjectQueryState<ProjectListEntriesResult> {
198 const fileAccess = useFilesystemReadAccess(environmentId);
199 const { canReadFiles } = fileAccess;
200 const atom = canReadFiles
201 ? getProjectEntriesQueryAtom(environmentId, cwd, directoryPath)
202 : EMPTY_PROJECT_ENTRIES_QUERY_ATOM;
203 const result = useAtomValue(atom);
204 const refreshAtom = useAtomRefresh(atom);
205 const refresh = () => refreshAtom();
206 return {
207 data: Option.getOrNull(AsyncResult.value(result)),
208 error: fileAccess.isPending
209 ? null
210 : canReadFiles
211 ? errorMessage(failureCause(result))
212 : (fileAccess.error ?? "This connection cannot read host files."),
213 isPending: fileAccess.isPending || result.waiting,
214 refresh,
215 };
217​
218/** Empty queries return frecency-ranked files without transferring the full workspace listing. */
219export function useProjectFilePickerQuery(
220 environmentId: EnvironmentId,
221 cwd: string,
222 query: string,
223 limit: number,
224 options?: { readonly imageOnly?: boolean },
225) {
226 const search = useProjectPathSearch(
227 {
228 environmentId,
229 cwd,
230 query,
231 kind: "file",
232 ...(options?.imageOnly ? { imageOnly: true } : {}),
233 },
234 limit,
235 { allowEmptyQuery: true },
236 );
237​
238 return {
239 entries: search.isPending ? [] : search.entries,
240 error: search.error,
241 isPending: search.isPending,
242 matchedQuery: search.searchedQuery,
243 };
245​
246export function useProjectFileQuery(
247 environmentId: EnvironmentId,
248 cwd: string,
249 relativePath: string | null,
250 enabled = true,
251): ProjectFileQueryState {
252 // Read media-like paths too; a failed read is how folders with those names are detected.
253 const fileAccess = useFilesystemReadAccess(environmentId);
254 const { canReadFiles } = fileAccess;
255 const isQueryEnabled = enabled;
256 const atom =
257 enabled && canReadFiles
258 ? getProjectFileQueryAtom(environmentId, cwd, relativePath)
259 : EMPTY_PROJECT_FILE_QUERY_ATOM;
260 const result = useAtomValue(atom);
261 const refreshAtom = useAtomRefresh(atom);
262 const refresh = () => refreshAtom();
263 const readData = Option.getOrNull(AsyncResult.value(result));
264 const isMissing = readData?.exists === false;
265 const optimisticResult = useAtomValue(
266 optimisticFileAtom(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH),
267 );
268 const optimisticFile = relativePath === null ? null : optimisticResult;
269 const cause = failureCause(result);
270 const readError = isProjectReadFileError(cause) ? cause : null;
271 const data = canReadFiles ? (optimisticFile?.data ?? (isMissing ? null : readData)) : null;
272 const isNotFile = readError?.failure === "path_not_file";
273​
274 return {
275 data,
276 error:
277 !isQueryEnabled || fileAccess.isPending
278 ? null
279 : canReadFiles
280 ? isMissing && !optimisticFile
281 ? `'${relativePath}' does not exist.`
282 : errorMessage(cause)
283 : (fileAccess.error ?? "This connection cannot read host files."),
284 isPending: isQueryEnabled && (fileAccess.isPending || result.waiting),
285 readError,
286 isNotFile,
287 // A folder error overrides cached contents retained across failed refreshes.
288 isFile: !isNotFile && (data !== null || readError?.failure === "binary_file"),
289 refresh,
290 };