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

projectFilesQueryState.ts

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