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

projectFilesQueryState.ts

296 lines9.3 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/**
219 * An empty query is a valid request — the index answers it with
220 * frecency-ordered files, so the picker's initial view is recent files without
221 * transferring the full workspace listing.
222 */
223export function useProjectFilePickerQuery(
224 environmentId: EnvironmentId,
225 cwd: string,
226 query: string,
227 limit: number,
228 options?: { readonly imageOnly?: boolean },
229) {
230 const search = useProjectPathSearch(
231 {
232 environmentId,
233 cwd,
234 query,
235 kind: "file",
236 ...(options?.imageOnly ? { imageOnly: true } : {}),
237 },
238 limit,
239 { allowEmptyQuery: true },
240 );
241​
242 return {
243 entries: search.isPending ? [] : search.entries,
244 error: search.error,
245 isPending: search.isPending,
246 matchedQuery: search.searchedQuery,
247 };
249​
250export function useProjectFileQuery(
251 environmentId: EnvironmentId,
252 cwd: string,
253 relativePath: string | null,
254 enabled = true,
255): ProjectFileQueryState {
256 // A media path is not skipped here: a folder named `assets.png` is only
257 // knowable as a folder from the read failure.
258 const fileAccess = useFilesystemReadAccess(environmentId);
259 const { canReadFiles } = fileAccess;
260 const isQueryEnabled = enabled;
261 const atom =
262 enabled && canReadFiles
263 ? getProjectFileQueryAtom(environmentId, cwd, relativePath)
264 : EMPTY_PROJECT_FILE_QUERY_ATOM;
265 const result = useAtomValue(atom);
266 const refreshAtom = useAtomRefresh(atom);
267 const refresh = () => refreshAtom();
268 const readData = Option.getOrNull(AsyncResult.value(result));
269 const isMissing = readData?.exists === false;
270 const optimisticResult = useAtomValue(
271 optimisticFileAtom(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH),
272 );
273 const optimisticFile = relativePath === null ? null : optimisticResult;
274 const cause = failureCause(result);
275 const readError = isProjectReadFileError(cause) ? cause : null;
276 const data = canReadFiles ? (optimisticFile?.data ?? (isMissing ? null : readData)) : null;
277 const isNotFile = readError?.failure === "path_not_file";
278​
279 return {
280 data,
281 error:
282 !isQueryEnabled || fileAccess.isPending
283 ? null
284 : canReadFiles
285 ? isMissing && !optimisticFile
286 ? `'${relativePath}' does not exist.`
287 : errorMessage(cause)
288 : (fileAccess.error ?? "This connection cannot read host files."),
289 isPending: isQueryEnabled && (fileAccess.isPending || result.waiting),
290 readError,
291 isNotFile,
292 // A folder error overrides cached contents retained across failed refreshes.
293 isFile: !isNotFile && (data !== null || readError?.failure === "binary_file"),
294 refresh,
295 };