import { type FilesystemBrowseEntry, WS_METHODS } from "@t3tools/contracts"; import { Atom } from "effect/unstable/reactivity"; import type { EnvironmentConnectionPhase } from "../connection/presentation.ts"; import type { EnvironmentRegistry } from "../connection/registry.ts"; import { canNavigateUp, getBrowseDirectoryPath, getBrowseLeafPathSegment, getBrowseParentPath, hasTrailingPathSeparator, isFilesystemBrowseQuery, } from "./projects.ts"; import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; export function getFilesystemBrowsePath(query: string, platform = "", enabled = true) { const isBrowsing = enabled && isFilesystemBrowseQuery(query, platform); const directoryPath = isBrowsing ? getBrowseDirectoryPath(query) : ""; const filterQuery = isBrowsing && !hasTrailingPathSeparator(query) ? getBrowseLeafPathSegment(query) : ""; const parentPath = isBrowsing ? getBrowseParentPath(directoryPath) : null; return { isBrowsing, directoryPath, filterQuery, parentPath, canBrowseUp: isBrowsing && canNavigateUp(directoryPath), }; } export function filterFilesystemBrowseEntries( entries: ReadonlyArray, query: string, ) { const lowerQuery = query.toLowerCase(); const showHidden = query.startsWith("."); const visibleEntries = entries.filter( (entry) => entry.name.toLowerCase().startsWith(lowerQuery) && (showHidden || !entry.name.startsWith(".")), ); const exactEntry = query.length > 0 ? (visibleEntries.find((entry) => entry.name === query) ?? null) : null; return { visibleEntries, exactEntry }; } export function createBrowseNavigationCoordinator() { let generation = 0; return { invalidate: () => { generation += 1; }, run: async (load: () => Promise, commit: () => void) => { const navigationGeneration = ++generation; await load(); if (navigationGeneration !== generation) { return false; } commit(); return true; }, }; } export function canPreloadBrowsePath( connectionPhase: EnvironmentConnectionPhase | null | undefined, ): boolean { return connectionPhase === "connected"; } export function createFilesystemEnvironmentAtoms( runtime: Atom.AtomRuntime, ) { return { browse: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:filesystem:browse", tag: WS_METHODS.filesystemBrowse, }), }; }