Open History to see the last commit
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 type {
12 EnvironmentConnectionPhase,
13 EnvironmentConnectionPresentation,
14} from "../connection/presentation.ts";
15import type { EnvironmentRegistry } from "../connection/registry.ts";
16import {
17 canNavigateUp,
18 getBrowseDirectoryPath,
19 getBrowseLeafPathSegment,
20 getBrowseParentPath,
21 hasTrailingPathSeparator,
22 isFilesystemBrowseQuery,
23} from "./projects.ts";
24import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
25
26const BROWSE_IDLE_TTL_MS = 5_000;
27
28export function resolveFilesystemReadAccess(input: {
29 readonly isCatalogReady: boolean;
30 readonly connection: Pick<EnvironmentConnectionPresentation, "phase" | "error"> | null;
31 readonly session: SessionGrantInput | null;
32 readonly sessionError: string | null;
33}) {
34 if (input.sessionError !== null) {
35 return { canReadFiles: false, isPending: false, error: input.sessionError };
36 }
37 if (input.session === null) {
38 // Wait for the catalog before interpreting a missing presentation as offline.
39 // Once ready, an offline environment cannot finish its session check.
40 const isPending =
41 !input.isCatalogReady ||
42 input.connection?.phase === "connected" ||
43 input.connection?.phase === "connecting" ||
44 input.connection?.phase === "reconnecting";
45 return {
46 canReadFiles: false,
47 isPending,
48 error: isPending ? null : (input.connection?.error ?? "This environment is not connected."),
49 };
50 }
51 return {
52 canReadFiles: sessionGrantsScope(input.session, AuthFilesystemReadScope),
53 isPending: false,
54 error: null,
55 };
56}
57
58export function getFilesystemBrowsePath(query: string, platform = "", enabled = true) {
59 const isBrowsing = enabled && isFilesystemBrowseQuery(query, platform);
60 const directoryPath = isBrowsing ? getBrowseDirectoryPath(query) : "";
61 const filterQuery =
62 isBrowsing && !hasTrailingPathSeparator(query) ? getBrowseLeafPathSegment(query) : "";
63 const parentPath = isBrowsing ? getBrowseParentPath(directoryPath) : null;
64
65 return {
66 isBrowsing,
67 directoryPath,
68 filterQuery,
69 parentPath,
70 canBrowseUp: isBrowsing && canNavigateUp(directoryPath),
71 };
72}
73
74export function filterFilesystemBrowseEntries(
75 entries: ReadonlyArray<FilesystemBrowseEntry>,
76 query: string,
77) {
78 // macOS Finder stores names decomposed (NFD), while typed text is composed (NFC).
79 const normalizedQuery = query.normalize("NFC");
80 const lowerQuery = query.toLowerCase();
81 const lowerNormalizedQuery = normalizedQuery.toLowerCase();
82 const showHidden = query.startsWith(".");
83 const candidates = entries.filter((entry) => showHidden || !entry.name.startsWith("."));
84 const visibleEntries =
85 lowerQuery.length === 0
86 ? candidates
87 : candidates
88 .map((entry) => {
89 const options = {
90 // Position penalties stay under 1000 for 255-character names, so tiers never overlap.
91 query: lowerNormalizedQuery,
92 exactBase: 0,
93 prefixBase: 1000,
94 boundaryBase: 2000,
95 includesBase: 3000,
96 fuzzyBase: 4000,
97 boundaryMarkers: [" ", "-", "_", "."],
98 };
99 const rawScore = scoreQueryMatch({
100 ...options,
101 value: entry.name.toLowerCase(),
102 query: lowerQuery,
103 });
104 const normalizedScore = scoreQueryMatch({
105 ...options,
106 value: entry.name.normalize("NFC").toLowerCase(),
107 });
108 const score =
109 rawScore === null
110 ? normalizedScore
111 : normalizedScore === null
112 ? rawScore
113 : Math.min(rawScore, normalizedScore);
114 return { entry, score };
115 })
116 .filter((match): match is { entry: FilesystemBrowseEntry; score: number } => {
117 return match.score !== null;
118 })
119 .sort((left, right) => left.score - right.score)
120 .map((match) => match.entry);
121 const normalizedMatches = visibleEntries.filter(
122 (entry) => entry.name.normalize("NFC") === normalizedQuery,
123 );
124 const exactEntry =
125 query.length > 0
126 ? (visibleEntries.find((entry) => entry.name === query) ??
127 (normalizedMatches.length === 1 ? normalizedMatches[0] : null))
128 : null;
129
130 return { visibleEntries, exactEntry };
131}
132
133/** Shell-style Tab: a single match enters the directory, several extend to their common prefix. */
134export function getFilesystemBrowseTabCompletion(
135 visibleEntries: ReadonlyArray<FilesystemBrowseEntry>,
136 filterQuery: string,
137): { readonly name: string; readonly isComplete: boolean } | null {
138 const [first, ...rest] = visibleEntries;
139 if (first === undefined) return null;
140 if (rest.length === 0) return { name: first.name, isComplete: true };
141 let prefix = Array.from(first.name);
142 for (const entry of rest) {
143 const characters = Array.from(entry.name);
144 let length = 0;
145 while (
146 length < prefix.length &&
147 prefix[length]?.toLowerCase() === characters[length]?.toLowerCase()
148 )
149 length += 1;
150 prefix = prefix.slice(0, length);
151 }
152 const name = prefix.join("");
153 const lowerName = name.toLowerCase();
154 return lowerName.length > filterQuery.toLowerCase().length &&
155 visibleEntries.every((entry) => entry.name.toLowerCase().startsWith(lowerName))
156 ? { name, isComplete: false }
157 : null;
158}
159
160export function createBrowseNavigationCoordinator() {
161 let generation = 0;
162
163 return {
164 invalidate: () => {
165 generation += 1;
166 },
167 run: async (load: () => Promise<void>, commit: () => void) => {
168 const navigationGeneration = ++generation;
169 await load();
170 if (navigationGeneration !== generation) {
171 return false;
172 }
173 commit();
174 return true;
175 },
176 };
177}
178
179export function canPreloadBrowsePath(
180 connectionPhase: EnvironmentConnectionPhase | null | undefined,
181): boolean {
182 return connectionPhase === "connected";
183}
184
185export function createFilesystemEnvironmentAtoms<R, E>(
186 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
187) {
188 return {
189 getMetadata: createEnvironmentRpcQueryAtomFamily(runtime, {
190 label: "environment-data:filesystem:get-metadata",
191 tag: WS_METHODS.filesystemGetMetadata,
192 }),
193 browse: createEnvironmentRpcQueryAtomFamily(runtime, {
194 label: "environment-data:filesystem:browse",
195 tag: WS_METHODS.filesystemBrowse,
196 // A listing mirrors a directory that can change outside the app, so reopening a picker
197 // lists it again. The short TTL only keeps the old listing on screen while it refreshes.
198 idleTtlMs: BROWSE_IDLE_TTL_MS,
199 staleTimeMs: 0,
200 }),
201 };
202}