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

projectFilesQueryState.ts

215 lines6.5 KB

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