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

projectFilesQueryState.ts

207 lines6.4 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​
36export function getProjectEntriesQueryAtom(environmentId: EnvironmentId, cwd: string) {
37 return projectEnvironment.listEntries({ environmentId, input: { cwd } });
39​
40export function getProjectFileQueryAtom(
41 environmentId: EnvironmentId,
42 cwd: string,
43 relativePath: string | null,
44) {
45 return projectEnvironment.readFile({
46 environmentId,
47 input: { cwd, relativePath: relativePath ?? EMPTY_PROJECT_FILE_PATH },
48 });
50​
51export function setProjectFileQueryData(
52 environmentId: EnvironmentId,
53 cwd: string,
54 relativePath: string,
55 contents: string,
56): void {
57 appAtomRegistry.set(optimisticFileAtom(environmentId, cwd, relativePath), {
58 confirmedAgainst: undefined,
59 data: {
60 relativePath,
61 contents,
62 byteLength: new TextEncoder().encode(contents).byteLength,
63 truncated: false,
64 },
65 });
67​
68export function getOptimisticProjectFileQueryData(
69 environmentId: EnvironmentId,
70 cwd: string,
71 relativePath: string,
72): ProjectReadFileResult | null {
73 return appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath))?.data ?? null;
75​
76export function confirmProjectFileQueryData(
77 environmentId: EnvironmentId,
78 cwd: string,
79 relativePath: string,
80 contents: string,
81): boolean {
82 const atom = optimisticFileAtom(environmentId, cwd, relativePath);
83 const optimisticFile = appAtomRegistry.get(atom);
84 if (optimisticFile?.data.contents !== contents) return false;
85​
86 const queryAtom = getProjectFileQueryAtom(environmentId, cwd, relativePath);
87 const confirmed = {
88 ...optimisticFile,
89 confirmedAgainst: appAtomRegistry.get(queryAtom),
90 };
91 appAtomRegistry.set(atom, confirmed);
92 appAtomRegistry.refresh(queryAtom);
93 void executeAtomQuery(appAtomRegistry, queryAtom, {
94 reportDefect: false,
95 reportFailure: false,
96 }).then((result) => {
97 if (result._tag === "Success" && appAtomRegistry.get(atom) === confirmed) {
98 appAtomRegistry.set(atom, null);
99 }
100 });
101 return true;
103​
104export function resolveProjectFileQueryData(
105 environmentId: EnvironmentId,
106 cwd: string,
107 relativePath: string | null,
108 data: ProjectReadFileResult | null,
109): ProjectReadFileResult | null {
110 if (relativePath === null) return data;
111 return appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath))?.data ?? data;
113​
114export function clearProjectFileQueryData(
115 environmentId: EnvironmentId,
116 cwd: string,
117 relativePath: string,
118): void {
119 appAtomRegistry.set(optimisticFileAtom(environmentId, cwd, relativePath), null);
121​
122function errorMessage<A>(result: AsyncResult.AsyncResult<A, unknown>): string | null {
123 if (result._tag !== "Failure") return null;
124 const cause = Cause.squash(result.cause);
125 return cause instanceof Error ? cause.message : "Workspace query failed.";
127​
128export function useProjectEntriesQuery(
129 environmentId: EnvironmentId,
130 cwd: string,
131): ProjectQueryState<ProjectListEntriesResult> {
132 const atom = getProjectEntriesQueryAtom(environmentId, cwd);
133 const result = useAtomValue(atom);
134 const refreshAtom = useAtomRefresh(atom);
135 const refresh = useCallback(() => refreshAtom(), [refreshAtom]);
136 return {
137 data: Option.getOrNull(AsyncResult.value(result)),
138 error: errorMessage(result),
139 isPending: result.waiting,
140 refresh,
141 };
143​
144/**
145 * Backing query for the project file picker: a debounced, bounded, file-only
146 * server search. An empty query is a valid request — the index answers it
147 * with frecency-ordered files, so the picker's initial view is recent files
148 * without transferring the full workspace listing. `matchedQuery` is the
149 * query the returned entries were computed for, so the caller can highlight
150 * against results instead of half-typed input.
151 */
152export function useProjectFilePickerQuery(
153 environmentId: EnvironmentId,
154 cwd: string,
155 query: string,
156 limit: number,
157 options?: { readonly imageOnly?: boolean },
158) {
159 const search = useProjectPathSearch(
160 {
161 environmentId,
162 cwd,
163 query,
164 kind: "file",
165 ...(options?.imageOnly ? { imageOnly: true } : {}),
166 },
167 limit,
168 { allowEmptyQuery: true },
169 );
170​
171 return {
172 entries: search.isPending ? [] : search.entries,
173 error: search.error,
174 isPending: search.isPending,
175 matchedQuery: search.searchedQuery,
176 };
178​
179export function useProjectFileQuery(
180 environmentId: EnvironmentId,
181 cwd: string,
182 relativePath: string | null,
183 enabled = true,
184): ProjectQueryState<ProjectReadFileResult> {
185 const isMedia =
186 relativePath !== null &&
187 (isWorkspaceImagePreviewPath(relativePath) || isWorkspaceVideoPreviewPath(relativePath));
188 const atom =
189 enabled && !isMedia
190 ? getProjectFileQueryAtom(environmentId, cwd, relativePath)
191 : EMPTY_PROJECT_FILE_QUERY_ATOM;
192 const result = useAtomValue(atom);
193 const refreshAtom = useAtomRefresh(atom);
194 const refresh = useCallback(() => refreshAtom(), [refreshAtom]);
195 const data = Option.getOrNull(AsyncResult.value(result));
196 const optimisticResult = useAtomValue(
197 optimisticFileAtom(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH),
198 );
199 const optimisticFile = relativePath === null ? null : optimisticResult;
200​
201 return {
202 data: optimisticFile?.data ?? data,
203 error: errorMessage(result),
204 isPending: result.waiting,
205 refresh,
206 };