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

filesystem.ts

248 lines8.7 KB

1import {
2 AuthFilesystemReadScope,
3 type FilesystemBrowseEntry,
4 WS_METHODS,
5 sessionGrantsScope,
6 type SessionGrantInput,
7} from "@t3tools/contracts";
8import { scoreQueryMatch } from "@t3tools/shared/searchRanking";
9import { Atom } from "effect/reactivity";
10​
11import { mFallback, msg } from "gt-i18n";
12import type { MFunctionType } from "gt-i18n/types";
13​
14import {
15 connectionErrorText,
16 type EnvironmentConnectionPhase,
17 type EnvironmentConnectionPresentation,
18} from "../connection/presentation.ts";
19import type { EnvironmentRegistry } from "../connection/registry.ts";
20import {
21 canNavigateUp,
22 getBrowseDirectoryPath,
23 getBrowseLeafPathSegment,
24 getBrowseParentPath,
25 hasTrailingPathSeparator,
26 isFilesystemBrowseQuery,
27} from "./projects.ts";
28import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
29​
30const BROWSE_IDLE_TTL_MS = 5_000;
31​
32export function resolveFilesystemReadAccess(
33 input: {
34 readonly isCatalogReady: boolean;
35 readonly connection: Pick<
36 EnvironmentConnectionPresentation,
37 "phase" | "error" | "i18nError"
38 > | null;
39 readonly session: SessionGrantInput | null;
40 readonly sessionError: string | null;
41 },
42 resolve: MFunctionType = mFallback,
43) {
44 if (input.sessionError !== null) {
45 return { canReadFiles: false, isPending: false, error: input.sessionError };
46 }
47 if (input.session === null) {
48 // Wait for the catalog before interpreting a missing presentation as offline.
49 // Once ready, an offline environment cannot finish its session check.
50 const isPending =
51 !input.isCatalogReady ||
52 input.connection?.phase === "connected" ||
53 input.connection?.phase === "connecting" ||
54 input.connection?.phase === "reconnecting";
55 return {
56 canReadFiles: false,
57 isPending,
58 error: isPending
59 ? null
60 : ((input.connection === null ? null : connectionErrorText(input.connection, resolve)) ??
61 resolve(msg("This environment is not connected."))),
62 };
63 }
64 return {
65 canReadFiles: sessionGrantsScope(input.session, AuthFilesystemReadScope),
66 isPending: false,
67 error: null,
68 };
70​
71export function getFilesystemBrowsePath(query: string, platform = "", enabled = true) {
72 const isBrowsing = enabled && isFilesystemBrowseQuery(query, platform);
73 // A bare drive has no separator, so it would otherwise filter its own listing by "D:".
74 const browseQuery = /^[a-zA-Z]:$/.test(query) ? `${query}\\` : query;
75 const directoryPath = isBrowsing ? getBrowseDirectoryPath(browseQuery) : "";
76 const filterQuery =
77 isBrowsing && !hasTrailingPathSeparator(browseQuery)
78 ? getBrowseLeafPathSegment(browseQuery)
79 : "";
80 const parentPath = isBrowsing ? getBrowseParentPath(directoryPath) : null;
81​
82 return {
83 isBrowsing,
84 directoryPath,
85 filterQuery,
86 parentPath,
87 canBrowseUp: isBrowsing && canNavigateUp(directoryPath),
88 };
90​
91export function filterFilesystemBrowseEntries(
92 entries: ReadonlyArray<FilesystemBrowseEntry>,
93 query: string,
94) {
95 // macOS Finder stores names decomposed (NFD), while typed text is composed (NFC).
96 const normalizedQuery = query.normalize("NFC");
97 const lowerQuery = query.toLowerCase();
98 const lowerNormalizedQuery = normalizedQuery.toLowerCase();
99 const showHidden = query.startsWith(".");
100 const candidates = entries.filter((entry) => showHidden || !entry.name.startsWith("."));
101 const visibleEntries =
102 lowerQuery.length === 0
103 ? candidates
104 : candidates
105 .map((entry) => {
106 const options = {
107 // Position penalties stay under 1000 for 255-character names, so tiers never overlap.
108 query: lowerNormalizedQuery,
109 exactBase: 0,
110 prefixBase: 1000,
111 boundaryBase: 2000,
112 includesBase: 3000,
113 fuzzyBase: 4000,
114 boundaryMarkers: [" ", "-", "_", "."],
115 };
116 const rawScore = scoreQueryMatch({
117 ...options,
118 value: entry.name.toLowerCase(),
119 query: lowerQuery,
120 });
121 const normalizedScore = scoreQueryMatch({
122 ...options,
123 value: entry.name.normalize("NFC").toLowerCase(),
124 });
125 const score =
126 rawScore === null
127 ? normalizedScore
128 : normalizedScore === null
129 ? rawScore
130 : Math.min(rawScore, normalizedScore);
131 return { entry, score };
132 })
133 .filter((match): match is { entry: FilesystemBrowseEntry; score: number } => {
134 return match.score !== null;
135 })
136 .sort((left, right) => left.score - right.score)
137 .map((match) => match.entry);
138 const normalizedMatches = visibleEntries.filter(
139 (entry) => entry.name.normalize("NFC") === normalizedQuery,
140 );
141 const exactEntry =
142 query.length > 0
143 ? (visibleEntries.find((entry) => entry.name === query) ??
144 (normalizedMatches.length === 1 ? normalizedMatches[0] : null))
145 : null;
146​
147 return { visibleEntries, exactEntry };
149​
150/** Shell-style Tab: a single match enters the directory, several extend to their common prefix. */
151export function getFilesystemBrowseTabCompletion(
152 visibleEntries: ReadonlyArray<FilesystemBrowseEntry>,
153 filterQuery: string,
154): { readonly name: string; readonly isComplete: boolean } | null {
155 const lowerQuery = filterQuery.toLowerCase();
156 const lowerNormalizedQuery = filterQuery.normalize("NFC").toLowerCase();
157 const prefixEntries = visibleEntries.filter(
158 (entry) =>
159 entry.name.toLowerCase().startsWith(lowerQuery) ||
160 entry.name.normalize("NFC").toLowerCase().startsWith(lowerNormalizedQuery),
161 );
162 const [first, ...rest] = prefixEntries;
163 if (first === undefined) return null;
164 if (rest.length === 0) return { name: first.name, isComplete: true };
165 let prefix = Array.from(first.name);
166 for (const entry of rest) {
167 const characters = Array.from(entry.name);
168 let length = 0;
169 while (
170 length < prefix.length &&
171 prefix[length]?.toLowerCase() === characters[length]?.toLowerCase()
172 )
173 length += 1;
174 prefix = prefix.slice(0, length);
175 }
176 const name = prefix.join("");
177 const lowerName = name.toLowerCase();
178 return lowerName.length > lowerQuery.length &&
179 prefixEntries.every((entry) => entry.name.toLowerCase().startsWith(lowerName))
180 ? { name, isComplete: false }
181 : null;
183​
184export function createBrowseNavigationCoordinator() {
185 let generation = 0;
186​
187 return {
188 invalidate: () => {
189 generation += 1;
190 },
191 run: async (load: () => Promise<void>, commit: () => void) => {
192 const navigationGeneration = ++generation;
193 await load();
194 if (navigationGeneration !== generation) {
195 return false;
196 }
197 commit();
198 return true;
199 },
200 };
202​
203export function canPreloadBrowsePath(
204 connectionPhase: EnvironmentConnectionPhase | null | undefined,
205): boolean {
206 return connectionPhase === "connected";
208​
209export function createFilesystemEnvironmentAtoms<R, E>(
210 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
211) {
212 return {
213 getMetadata: createEnvironmentRpcQueryAtomFamily(runtime, {
214 label: "environment-data:filesystem:get-metadata",
215 tag: WS_METHODS.filesystemGetMetadata,
216 }),
217 browse: createEnvironmentRpcQueryAtomFamily(runtime, {
218 label: "environment-data:filesystem:browse",
219 tag: WS_METHODS.filesystemBrowse,
220 // A listing mirrors a directory that can change outside the app, so reopening a picker
221 // lists it again. The short TTL only keeps the old listing on screen while it refreshes.
222 idleTtlMs: BROWSE_IDLE_TTL_MS,
223 staleTimeMs: 0,
224 }),
225 /** Repositories under a folder and in its `.code-workspace` file, read from disk each time. */
226 scanFolders: createEnvironmentRpcQueryAtomFamily(runtime, {
227 label: "environment-data:workspace:scan-folders",
228 tag: WS_METHODS.workspaceScanFolders,
229 staleTimeMs: 0,
230 }),
231 /** A project's tracked folders with what is on disk now: a repository, plain files, or gone. */
232 listFolders: createEnvironmentRpcQueryAtomFamily(runtime, {
233 label: "environment-data:workspace:list-folders",
234 tag: WS_METHODS.workspaceListFolders,
235 staleTimeMs: 0,
236 }),
237 /** The task folder a thread's `worktreePath` belongs to, with each repository's worktree. */
238 taskFolder: createEnvironmentRpcQueryAtomFamily(runtime, {
239 label: "environment-data:workspace:task-folder",
240 tag: WS_METHODS.workspaceTaskFolder,
241 staleTimeMs: 0,
242 }),
243 addTaskFolderRepository: createEnvironmentRpcCommand(runtime, {
244 label: "environment-data:workspace:add-task-folder-repository",
245 tag: WS_METHODS.workspaceAddTaskFolderRepository,
246 }),
247 };