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