|
| 1 | +import { useState, useEffect, useCallback } from "react"; |
| 2 | + |
| 3 | +interface FileItem { |
| 4 | + name: string; |
| 5 | + path: string; |
| 6 | + isDirectory: boolean; |
| 7 | + size?: number; |
| 8 | + mimeType?: string | null; |
| 9 | +} |
| 10 | + |
| 11 | +interface DirectoryListing { |
| 12 | + path: string; |
| 13 | + files: FileItem[]; |
| 14 | +} |
| 15 | + |
| 16 | +export function useDirectoryListing( |
| 17 | + initialPath: string = "/", |
| 18 | + onPathChange?: (path: string) => void, |
| 19 | + batchSize: number = 50, |
| 20 | +) { |
| 21 | + const [currentPath, setCurrentPath] = useState(initialPath); |
| 22 | + const [directoryListing, setDirectoryListing] = |
| 23 | + useState<DirectoryListing | null>(null); |
| 24 | + const [loading, setLoading] = useState(false); |
| 25 | + const [error, setError] = useState<string | null>(null); |
| 26 | + |
| 27 | + const fetchPath = useCallback( |
| 28 | + async (path: string) => { |
| 29 | + setLoading(true); |
| 30 | + setError(null); |
| 31 | + setDirectoryListing(null); |
| 32 | + |
| 33 | + // Batch-related variables accessible to both try and catch blocks |
| 34 | + const files: FileItem[] = []; |
| 35 | + let dirPath = path; |
| 36 | + let batchBuffer: FileItem[] = []; |
| 37 | + const effectiveBatchSize = Math.max(1, batchSize); // Clamp to minimum 1 |
| 38 | + |
| 39 | + // Flush function - centralized batch update logic |
| 40 | + const flushBatch = () => { |
| 41 | + if (batchBuffer.length > 0) { |
| 42 | + files.push(...batchBuffer); |
| 43 | + setDirectoryListing({ path: dirPath, files: [...files] }); |
| 44 | + batchBuffer = []; |
| 45 | + } |
| 46 | + }; |
| 47 | + |
| 48 | + try { |
| 49 | + // Stream directory listing from NDJSON response |
| 50 | + const response = await fetch(`/api/volume-serving${path}`); |
| 51 | + |
| 52 | + if (!response.ok) { |
| 53 | + throw new Error(`HTTP error! status: ${response.status}`); |
| 54 | + } |
| 55 | + |
| 56 | + // Read the stream line by line |
| 57 | + const reader = response.body?.getReader(); |
| 58 | + const decoder = new TextDecoder(); |
| 59 | + let buffer = ""; |
| 60 | + |
| 61 | + if (reader) { |
| 62 | + while (true) { |
| 63 | + const { done, value } = await reader.read(); |
| 64 | + |
| 65 | + if (done) { |
| 66 | + flushBatch(); // Flush remaining files |
| 67 | + break; |
| 68 | + } |
| 69 | + |
| 70 | + buffer += decoder.decode(value, { stream: true }); |
| 71 | + const lines = buffer.split("\n"); |
| 72 | + |
| 73 | + // Process all complete lines |
| 74 | + for (let i = 0; i < lines.length - 1; i++) { |
| 75 | + const line = lines[i].trim(); |
| 76 | + if (line) { |
| 77 | + const data = JSON.parse(line); |
| 78 | + |
| 79 | + if (data.type === "metadata") { |
| 80 | + dirPath = data.path; |
| 81 | + } else if (data.type === "file") { |
| 82 | + const fileItem: FileItem = { |
| 83 | + name: data.name, |
| 84 | + path: data.path, |
| 85 | + isDirectory: data.isDirectory, |
| 86 | + size: data.size, |
| 87 | + mimeType: data.mimeType, |
| 88 | + }; |
| 89 | + |
| 90 | + batchBuffer.push(fileItem); |
| 91 | + |
| 92 | + // Flush when batch is full |
| 93 | + if (batchBuffer.length >= effectiveBatchSize) { |
| 94 | + flushBatch(); |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + // Keep the last incomplete line in the buffer |
| 101 | + buffer = lines[lines.length - 1]; |
| 102 | + } |
| 103 | + } |
| 104 | + } catch (err) { |
| 105 | + flushBatch(); // Flush partial batch before error state |
| 106 | + setError(err instanceof Error ? err.message : "Failed to fetch path"); |
| 107 | + } finally { |
| 108 | + setLoading(false); |
| 109 | + } |
| 110 | + }, |
| 111 | + [batchSize], |
| 112 | + ); |
| 113 | + |
| 114 | + const navigateUp = () => { |
| 115 | + // Remove trailing slash if present |
| 116 | + const cleanPath = |
| 117 | + currentPath.endsWith("/") && currentPath !== "/" |
| 118 | + ? currentPath.slice(0, -1) |
| 119 | + : currentPath; |
| 120 | + |
| 121 | + // Get parent directory |
| 122 | + const parentPath = |
| 123 | + cleanPath.substring(0, cleanPath.lastIndexOf("/")) || "/"; |
| 124 | + const normalizedParent = parentPath === "/" ? "/" : `${parentPath}/`; |
| 125 | + |
| 126 | + setCurrentPath(normalizedParent); |
| 127 | + onPathChange?.(normalizedParent); |
| 128 | + fetchPath(normalizedParent); |
| 129 | + }; |
| 130 | + |
| 131 | + const handleNavigate = (file: FileItem) => { |
| 132 | + // Handle ".." navigation |
| 133 | + if (file.name === "..") { |
| 134 | + navigateUp(); |
| 135 | + return; |
| 136 | + } |
| 137 | + |
| 138 | + if (file.isDirectory) { |
| 139 | + // Navigate to directory |
| 140 | + const newPath = file.path; |
| 141 | + setCurrentPath(newPath); |
| 142 | + onPathChange?.(newPath); |
| 143 | + fetchPath(newPath); |
| 144 | + } else { |
| 145 | + // Open file in new window |
| 146 | + window.open(`/api/volume-serving${file.path}`, "_blank"); |
| 147 | + } |
| 148 | + }; |
| 149 | + |
| 150 | + // Load directory when initialPath changes (including from URL) |
| 151 | + useEffect(() => { |
| 152 | + setCurrentPath(initialPath); |
| 153 | + fetchPath(initialPath); |
| 154 | + }, [initialPath, fetchPath]); |
| 155 | + |
| 156 | + // Prepare files list with ".." entry if not in root, sorted with folders first |
| 157 | + const filesWithNavigation = directoryListing |
| 158 | + ? [ |
| 159 | + ...(currentPath !== "/" |
| 160 | + ? [ |
| 161 | + { |
| 162 | + name: "..", |
| 163 | + path: "", |
| 164 | + isDirectory: true, |
| 165 | + size: undefined, |
| 166 | + mimeType: null, |
| 167 | + }, |
| 168 | + ] |
| 169 | + : []), |
| 170 | + // Sort: directories first, then by name |
| 171 | + ...directoryListing.files.sort((a, b) => { |
| 172 | + if (a.isDirectory === b.isDirectory) { |
| 173 | + return a.name.localeCompare(b.name); |
| 174 | + } |
| 175 | + return a.isDirectory ? -1 : 1; |
| 176 | + }), |
| 177 | + ] |
| 178 | + : []; |
| 179 | + |
| 180 | + return { |
| 181 | + currentPath, |
| 182 | + directoryListing, |
| 183 | + loading, |
| 184 | + error, |
| 185 | + filesWithNavigation, |
| 186 | + fetchPath, |
| 187 | + navigateUp, |
| 188 | + handleNavigate, |
| 189 | + }; |
| 190 | +} |
0 commit comments