diff --git a/app/components/Code/FileTree.vue b/app/components/Code/FileTree.vue index b2bcbf20e6..5f750eb57e 100644 --- a/app/components/Code/FileTree.vue +++ b/app/components/Code/FileTree.vue @@ -10,6 +10,11 @@ const props = defineProps<{ baseUrl: string baseRoute: Pick depth?: number + loadingDirs?: ReadonlySet +}>() + +const emit = defineEmits<{ + expandDir: [path: string] }>() const depth = computed(() => props.depth ?? 0) @@ -37,18 +42,63 @@ function getFileRoute(nodePath: string): RouteLocationRaw { const { toggleDir, isExpanded, autoExpandAncestors } = useFileTreeState(props.baseUrl) -const scrollIntoView = () => { +const autoExpanded = new Set() + +function expandLoadedAncestors(path: string, force: boolean) { + let prefix = '' + + for (const segment of path.split('/').filter(Boolean)) { + prefix = prefix ? `${prefix}/${segment}` : segment + const node = findTreeNode(props.tree, prefix) + if (!node) return + if (node.type !== 'directory') continue + if (node.children === undefined) return + if (!force && !isExpanded(prefix) && autoExpanded.has(prefix)) return + + autoExpanded.add(prefix) + autoExpandAncestors(prefix) + } +} + +function handleToggleDir(node: PackageFileTree) { + const willExpand = !isExpanded(node.path) + toggleDir(node.path) + if (willExpand && node.children === undefined) { + emit('expandDir', node.path) + } +} + +let lastScrolledPath = '' + +const scrollIntoView = (path: string) => { const el = treeRoot.value?.querySelector('[aria-current="true"]') - el?.scrollIntoView({ block: 'center', behavior: 'smooth' }) + if (el) { + lastScrolledPath = path + el.scrollIntoView({ block: 'center', behavior: 'smooth' }) + } } -// Auto-expand directories in the current path watch( - () => props.currentPath, - path => { + () => [props.currentPath, props.tree] as const, + ([path, nodes], previous) => { if (depth.value === 0 && path) { - autoExpandAncestors(path) - nextTick(scrollIntoView) + expandLoadedAncestors(path, previous?.[0] !== path) + } + + for (const node of nodes) { + if ( + node.type === 'directory' && + node.children === undefined && + isExpanded(node.path) && + !isNodeActive(node) && + !props.loadingDirs?.has(node.path) + ) { + emit('expandDir', node.path) + } + } + + if (depth.value === 0 && path && lastScrolledPath !== path) { + nextTick(() => scrollIntoView(path)) } }, { immediate: true }, @@ -64,14 +114,21 @@ watch( class="w-full justify-start! rounded-none! border-none! transition-[color,background-color]! duration-100!" block :aria-pressed="isNodeActive(node)" + :aria-busy="loadingDirs?.has(node.path) || undefined" :aria-label=" isPossiblyUnnecessaryContent(node.name, 'directory') ? `${node.name} - ${$t('code.possibly_unnecessary')}` : undefined " :style="{ paddingLeft: `${depth * 12 + 12}px` }" - @click="toggleDir(node.path)" - :classicon="isExpanded(node.path) ? 'i-lucide:chevron-down' : 'i-lucide:chevron-right'" + @click="handleToggleDir(node)" + :classicon=" + loadingDirs?.has(node.path) + ? 'i-svg-spinners:ring-resize' + : isExpanded(node.path) + ? 'i-lucide:chevron-down' + : 'i-lucide:chevron-right' + " > diff --git a/app/components/Code/MobileTreeDrawer.vue b/app/components/Code/MobileTreeDrawer.vue index dd524bf635..07cb9c96d7 100644 --- a/app/components/Code/MobileTreeDrawer.vue +++ b/app/components/Code/MobileTreeDrawer.vue @@ -6,6 +6,11 @@ defineProps<{ currentPath: string baseUrl: string baseRoute: Pick + loadingDirs?: ReadonlySet +}>() + +const emit = defineEmits<{ + expandDir: [path: string] }>() const isOpen = shallowRef(false) @@ -74,6 +79,8 @@ defineExpose({ :current-path="currentPath" :base-url="baseUrl" :base-route="baseRoute" + :loading-dirs="loadingDirs" + @expand-dir="emit('expandDir', $event)" /> diff --git a/app/composables/useFileTreeState.ts b/app/composables/useFileTreeState.ts index 7c49eac5ca..4144432e4e 100644 --- a/app/composables/useFileTreeState.ts +++ b/app/composables/useFileTreeState.ts @@ -9,6 +9,10 @@ export function useFileTreeState(baseUrl: string) { } } + function collapseDir(path: string) { + expanded.value.delete(path) + } + function isExpanded(path: string) { return expanded.value.has(path) } @@ -25,6 +29,7 @@ export function useFileTreeState(baseUrl: string) { return { toggleDir, + collapseDir, isExpanded, autoExpandAncestors, } diff --git a/app/pages/package-code/[[org]]/[packageName]/v/[version]/[...filePath].vue b/app/pages/package-code/[[org]]/[packageName]/v/[version]/[...filePath].vue index 80d9916427..056a275e32 100644 --- a/app/pages/package-code/[[org]]/[packageName]/v/[version]/[...filePath].vue +++ b/app/pages/package-code/[[org]]/[packageName]/v/[version]/[...filePath].vue @@ -110,8 +110,50 @@ function codeVersionRoute(nextVersion: string): RouteLocationRaw { useCommandPaletteVersionCommands(commandPalettePackageContext, codeVersionRoute) // Fetch file tree -const treeRequest = useFetch( - () => `/api/registry/files/${packageName.value}/v/${version.value}`, +const filesBaseUrl = computed(() => `/api/registry/files/${packageName.value}/v/${version.value}`) +const initialExpandDir = getInitialExpandDir(filePathOrig.value) + +const loadingDirs = shallowRef(new Set()) +const inFlightDirRequests = new Map>() +const failedPathLoads = new Map() +const isLoadingPath = shallowRef(false) +const pathLoadError = shallowRef(false) + +function getErrorStatus(error: unknown): number | undefined { + if (typeof error !== 'object' || error === null) return undefined + return ( + (error as { statusCode?: number; status?: number }).statusCode ?? + (error as { status?: number }).status + ) +} + +async function fetchInitialFileTree(): Promise { + let response: PackageFileTreeWireResponse + + try { + response = await $fetch( + filesBaseUrl.value, + initialExpandDir ? { query: { expand: initialExpandDir } } : {}, + ) + } catch (error: unknown) { + if (!initialExpandDir || getErrorStatus(error) !== 404) { + throw error + } + failedPathLoads.set(`expand:${initialExpandDir}`, 'not-found') + response = await $fetch(filesBaseUrl.value) + } + + return { + package: response.package, + version: response.version, + default: response.default, + tree: hydrateFileTree(response.tree), + } +} + +const treeRequest = useAsyncData( + `file-tree:${packageName.value}@${version.value}:${initialExpandDir ?? ''}`, + fetchInitialFileTree, { immediate: !!version.value, server: false, @@ -124,33 +166,161 @@ if (useNuxtApp().isHydrating) { await Promise.all([packageRequest, treeRequest]) } -// Determine what to show based on the current path -// Note: This needs fileTree to be loaded first -const currentNode = computed(() => { - if (!fileTree.value?.tree || !filePathOrig.value) return null +function setDirLoading(dirPath: string, loading: boolean) { + const next = new Set(loadingDirs.value) + if (loading) { + next.add(dirPath) + } else { + next.delete(dirPath) + } + loadingDirs.value = next +} + +async function loadDirectory(dirPath: string): Promise { + if (!fileTree.value) return + const key = `dir:${dirPath}` + const existing = inFlightDirRequests.get(key) + if (existing) return existing + + setDirLoading(dirPath, true) + const request = $fetch(filesBaseUrl.value, { + query: { dir: dirPath }, + }) + .then(res => { + if (!fileTree.value) return + const children = hydrateFileTree(res.tree, dirPath) + fileTree.value = { + ...fileTree.value, + tree: attachDirectoryChildren(fileTree.value.tree, dirPath, children), + } + }) + .finally(() => { + inFlightDirRequests.delete(key) + setDirLoading(dirPath, false) + }) + + inFlightDirRequests.set(key, request) + return request +} + +async function expandDirectory(dirPath: string): Promise { + if (!fileTree.value) return + const key = `expand:${dirPath}` + const existing = inFlightDirRequests.get(key) + if (existing) return existing + + const request = $fetch(filesBaseUrl.value, { + query: { expand: dirPath }, + }) + .then(res => { + if (!fileTree.value) return + const incoming = hydrateFileTree(res.tree) + fileTree.value = { + ...fileTree.value, + tree: mergeFileTrees(fileTree.value.tree, incoming), + } + }) + .finally(() => { + inFlightDirRequests.delete(key) + }) + + inFlightDirRequests.set(key, request) + return request +} + +function handleExpandDir(dirPath: string) { + failedPathLoads.delete(`dir:${dirPath}`) + void loadDirectory(dirPath).catch(() => { + useFileTreeState(getCurrentCodeUrlWithPath()).collapseDir(dirPath) + }) +} - // We use original file path to correctly handle trailing slashes for file tree navigation - // - /src/index.ts - correct file path - // - /src/index.ts/ - incorrect file path (but formally can exist as a directory) - // - /src/index and /src/index/ - correct directory paths - const parts = filePathOrig.value.split('/') - let current: PackageFileTree[] | undefined = fileTree.value.tree - let lastFound: PackageFileTree | null = null - const partsLength = parts.length - - for (let i = 0; i < partsLength; i++) { - const part = parts[i] - const isLast = i === partsLength - 1 - // If the previous part is a directory and the last one is empty (like /lib/) then return the previous directory - if (!part && isLast && lastFound?.type === 'directory') return lastFound - const found: PackageFileTree | undefined = current?.find(n => n.name === part) - if (!found) return null - lastFound = found - if (found.type === 'file' && isLast) return found - current = found.children +function sliceKey(missing: MissingDirectoryFetch): string { + return `${missing.mode}:${missing.dirPath}` +} + +function nextMissingSlice(pathOrig: string): MissingDirectoryFetch | null { + const tree = fileTree.value?.tree + if (!tree) return null + const missing = resolveMissingDirectoryFetch(tree, pathOrig) + return missing && !failedPathLoads.has(sliceKey(missing)) ? missing : null +} + +async function loadMissingPath(pathOrig: string): Promise { + isLoadingPath.value = true + pathLoadError.value = false + const attempted = new Set() + let attemptKey: string | null = null + + try { + let missing = nextMissingSlice(pathOrig) + while (missing && !attempted.has(sliceKey(missing))) { + attemptKey = sliceKey(missing) + attempted.add(attemptKey) + await (missing.mode === 'dir' + ? loadDirectory(missing.dirPath) + : expandDirectory(missing.dirPath)) + missing = nextMissingSlice(pathOrig) + } + } catch (error: unknown) { + const kind = getErrorStatus(error) === 404 ? 'not-found' : 'error' + if (attemptKey) failedPathLoads.set(attemptKey, kind) + if (filePathOrig.value === pathOrig) pathLoadError.value = kind === 'error' + } finally { + if (filePathOrig.value === pathOrig) isLoadingPath.value = false + } +} + +function retryPathLoad() { + const pathOrig = filePathOrig.value + const tree = fileTree.value?.tree + if (!pathOrig || !tree) return + + const missing = resolveMissingDirectoryFetch(tree, pathOrig) + if (!missing) { + pathLoadError.value = false + return } + failedPathLoads.delete(sliceKey(missing)) + void loadMissingPath(pathOrig) +} + +watch( + () => [filePathOrig.value, fileTree.value?.tree] as const, + ([pathOrig, tree], previous) => { + if (!pathOrig || !tree) { + isLoadingPath.value = false + pathLoadError.value = false + return + } + + const missing = resolveMissingDirectoryFetch(tree, pathOrig) + if (!missing) { + isLoadingPath.value = false + pathLoadError.value = false + return + } + + const attemptKey = sliceKey(missing) + if (previous?.[0] !== pathOrig && failedPathLoads.get(attemptKey) === 'error') { + failedPathLoads.delete(attemptKey) + } + + const priorFailure = failedPathLoads.get(attemptKey) + if (priorFailure) { + isLoadingPath.value = false + pathLoadError.value = priorFailure === 'error' + return + } + + void loadMissingPath(pathOrig) + }, + { immediate: true }, +) - return lastFound +const currentNode = computed(() => { + if (!fileTree.value?.tree || !filePathOrig.value) return null + return findTreeNode(fileTree.value.tree, filePathOrig.value) }) const isViewingFile = computed(() => currentNode.value?.type === 'file') @@ -193,7 +363,7 @@ const { // Loading skeleton state const isLoading = computed(() => { if (!isViewingFile.value) { - return treeStatus.value !== 'success' && treeStatus.value !== 'error' + return isLoadingPath.value || (treeStatus.value !== 'success' && treeStatus.value !== 'error') } if (isFileTooLarge.value) return false @@ -488,6 +658,8 @@ useCommandPaletteContextCommands( :current-path="filePath ?? ''" :base-url="getCurrentCodeUrlWithPath()" :base-route="route" + :loading-dirs="loadingDirs" + @expand-dir="handleExpandDir" /> @@ -590,6 +762,13 @@ useCommandPaletteContextCommands( + +