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

projectFilesQueryState.ts

228 lines7.0 KB

1import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2import {
3 type EnvironmentId,
4 type ProjectListEntriesResult,
5 ProjectReadFileError,
6 type ProjectReadFileResult,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as Option from "effect/Option";
10import * as Schema from "effect/Schema";
11import { AsyncResult, Atom } from "effect/unstable/reactivity";
12import { useCallback } from "react";
13​
14import { appAtomRegistry } from "~/rpc/atomRegistry";
15import { projectEnvironment } from "~/state/projects";
16import { useProjectPathSearch } from "~/state/queries";
17import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
18​
19const EMPTY_PROJECT_FILE_PATH = "";
20const EMPTY_PROJECT_FILE_QUERY_ATOM = Atom.make(
21 AsyncResult.initial<ProjectReadFileResult, never>(false),
22).pipe(Atom.withLabel("project-file-query:empty"));
23/** A pending in-app write to the file, overlaying the query until confirmed. */
24export function optimisticFileAtom(
25 environmentId: EnvironmentId,
26 cwd: string,
27 relativePath: string,
28) {
29 return projectEnvironment.optimisticFile({ environmentId, cwd, relativePath });
31​
32interface ProjectQueryState<A> {
33 readonly data: A | null;
34 readonly error: string | null;
35 readonly isPending: boolean;
36 readonly refresh: () => void;
38​
39interface ProjectFileQueryState extends ProjectQueryState<ProjectReadFileResult> {
40 /** The path exists but is not a regular file, typically a directory. */
41 readonly isNotFile: boolean;
43​
44function getProjectEntriesQueryAtom(
45 environmentId: EnvironmentId,
46 cwd: string,
47 directoryPath?: string,
48) {
49 return projectEnvironment.listEntries({
50 environmentId,
51 input: { cwd, ...(directoryPath !== undefined ? { directoryPath } : {}) },
52 });
54​
55export function getProjectFileQueryAtom(
56 environmentId: EnvironmentId,
57 cwd: string,
58 relativePath: string | null,
59) {
60 return projectEnvironment.readFile({
61 environmentId,
62 input: { cwd, relativePath: relativePath ?? EMPTY_PROJECT_FILE_PATH },
63 });
65​
66export function setProjectFileQueryData(
67 environmentId: EnvironmentId,
68 cwd: string,
69 relativePath: string,
70 contents: string,
71): void {
72 appAtomRegistry.set(optimisticFileAtom(environmentId, cwd, relativePath), {
73 confirmedAgainst: undefined,
74 data: {
75 relativePath,
76 contents,
77 byteLength: new TextEncoder().encode(contents).byteLength,
78 truncated: false,
79 },
80 });
82​
83export function getOptimisticProjectFileQueryData(
84 environmentId: EnvironmentId,
85 cwd: string,
86 relativePath: string,
87): ProjectReadFileResult | null {
88 return appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath))?.data ?? null;
90​
91export function confirmProjectFileQueryData(
92 environmentId: EnvironmentId,
93 cwd: string,
94 relativePath: string,
95 contents: string,
96): boolean {
97 const atom = optimisticFileAtom(environmentId, cwd, relativePath);
98 const optimisticFile = appAtomRegistry.get(atom);
99 if (optimisticFile?.data.contents !== contents) return false;
100​
101 const queryAtom = getProjectFileQueryAtom(environmentId, cwd, relativePath);
102 const confirmed = {
103 ...optimisticFile,
104 confirmedAgainst: appAtomRegistry.get(queryAtom),
105 };
106 appAtomRegistry.set(atom, confirmed);
107 appAtomRegistry.refresh(queryAtom);
108 void executeAtomQuery(appAtomRegistry, queryAtom, {
109 reportDefect: false,
110 reportFailure: false,
111 }).then((result) => {
112 if (result._tag === "Success" && appAtomRegistry.get(atom) === confirmed) {
113 appAtomRegistry.set(atom, null);
114 }
115 });
116 return true;
118​
119export function resolveProjectFileQueryData(
120 environmentId: EnvironmentId,
121 cwd: string,
122 relativePath: string | null,
123 data: ProjectReadFileResult | null,
124): ProjectReadFileResult | null {
125 if (relativePath === null) return data;
126 return appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath))?.data ?? data;
128​
129export function clearProjectFileQueryData(
130 environmentId: EnvironmentId,
131 cwd: string,
132 relativePath: string,
133): void {
134 appAtomRegistry.set(optimisticFileAtom(environmentId, cwd, relativePath), null);
136​
137function failureCause<A>(result: AsyncResult.AsyncResult<A, unknown>): unknown {
138 return result._tag === "Failure" ? Cause.squash(result.cause) : null;
140​
141function errorMessage(cause: unknown): string | null {
142 if (cause === null) return null;
143 return cause instanceof Error ? cause.message : "Workspace query failed.";
145​
146const isProjectReadFileError = Schema.is(ProjectReadFileError);
147​
148export function useProjectEntriesQuery(
149 environmentId: EnvironmentId,
150 cwd: string,
151 directoryPath?: string,
152): ProjectQueryState<ProjectListEntriesResult> {
153 const atom = getProjectEntriesQueryAtom(environmentId, cwd, directoryPath);
154 const result = useAtomValue(atom);
155 const refreshAtom = useAtomRefresh(atom);
156 const refresh = useCallback(() => refreshAtom(), [refreshAtom]);
157 return {
158 data: Option.getOrNull(AsyncResult.value(result)),
159 error: errorMessage(failureCause(result)),
160 isPending: result.waiting,
161 refresh,
162 };
164​
165/**
166 * Backing query for the project file picker: a debounced, bounded, file-only
167 * server search. An empty query is a valid request — the index answers it
168 * with frecency-ordered files, so the picker's initial view is recent files
169 * without transferring the full workspace listing. `matchedQuery` is the
170 * query the returned entries were computed for, so the caller can highlight
171 * against results instead of half-typed input.
172 */
173export function useProjectFilePickerQuery(
174 environmentId: EnvironmentId,
175 cwd: string,
176 query: string,
177 limit: number,
178 options?: { readonly imageOnly?: boolean },
179) {
180 const search = useProjectPathSearch(
181 {
182 environmentId,
183 cwd,
184 query,
185 kind: "file",
186 ...(options?.imageOnly ? { imageOnly: true } : {}),
187 },
188 limit,
189 { allowEmptyQuery: true },
190 );
191​
192 return {
193 entries: search.isPending ? [] : search.entries,
194 error: search.error,
195 isPending: search.isPending,
196 matchedQuery: search.searchedQuery,
197 };
199​
200export function useProjectFileQuery(
201 environmentId: EnvironmentId,
202 cwd: string,
203 relativePath: string | null,
204 enabled = true,
205): ProjectFileQueryState {
206 // The caller decides what to read. A media path is not skipped here: a folder
207 // named `assets.png` is only knowable as a folder from the read failure.
208 const atom = enabled
209 ? getProjectFileQueryAtom(environmentId, cwd, relativePath)
210 : EMPTY_PROJECT_FILE_QUERY_ATOM;
211 const result = useAtomValue(atom);
212 const refreshAtom = useAtomRefresh(atom);
213 const refresh = useCallback(() => refreshAtom(), [refreshAtom]);
214 const data = Option.getOrNull(AsyncResult.value(result));
215 const optimisticResult = useAtomValue(
216 optimisticFileAtom(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH),
217 );
218 const optimisticFile = relativePath === null ? null : optimisticResult;
219 const cause = failureCause(result);
220​
221 return {
222 data: optimisticFile?.data ?? data,
223 error: errorMessage(cause),
224 isNotFile: isProjectReadFileError(cause) && cause.failure === "path_not_file",
225 isPending: result.waiting,
226 refresh,
227 };