-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathFilePicker.tsx
More file actions
494 lines (435 loc) · 15.6 KB
/
FilePicker.tsx
File metadata and controls
494 lines (435 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import React, { useState, useEffect, useRef } from "react";
import { motion } from "framer-motion";
import { Button } from "@/components/ui/button";
import { api } from "@/lib/api";
import {
X,
Folder,
File,
ArrowLeft,
FileCode,
FileText,
FileImage,
Search,
ChevronRight
} from "lucide-react";
import type { FileEntry } from "@/lib/api";
import { cn } from "@/lib/utils";
// Global caches that persist across component instances
const globalDirectoryCache = new Map<string, FileEntry[]>();
const globalSearchCache = new Map<string, FileEntry[]>();
// Note: These caches persist for the lifetime of the application.
// In a production app, you might want to:
// 1. Add TTL (time-to-live) to expire old entries
// 2. Implement LRU (least recently used) eviction
// 3. Clear caches when the working directory changes
// 4. Add a maximum cache size limit
interface FilePickerProps {
/**
* The base directory path to browse
*/
basePath: string;
/**
* Callback when a file/directory is selected
*/
onSelect: (entry: FileEntry) => void;
/**
* Callback to close the picker
*/
onClose: () => void;
/**
* Initial search query
*/
initialQuery?: string;
/**
* Optional className for styling
*/
className?: string;
}
// File icon mapping based on extension
const getFileIcon = (entry: FileEntry) => {
if (entry.is_directory) return Folder;
const ext = entry.extension?.toLowerCase();
if (!ext) return File;
// Code files
if (['ts', 'tsx', 'js', 'jsx', 'py', 'rs', 'go', 'java', 'cpp', 'c', 'h'].includes(ext)) {
return FileCode;
}
// Text/Markdown files
if (['md', 'txt', 'json', 'yaml', 'yml', 'toml', 'xml', 'html', 'css'].includes(ext)) {
return FileText;
}
// Image files
if (['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico'].includes(ext)) {
return FileImage;
}
return File;
};
// Format file size to human readable
const formatFileSize = (bytes: number): string => {
if (bytes === 0) return '';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
};
/**
* FilePicker component - File browser with fuzzy search
*
* @example
* <FilePicker
* basePath="/Users/example/project"
* onSelect={(entry) => console.log('Selected:', entry)}
* onClose={() => setShowPicker(false)}
* />
*/
export const FilePicker: React.FC<FilePickerProps> = ({
basePath,
onSelect,
onClose,
initialQuery = "",
className,
}) => {
const searchQuery = initialQuery;
const [currentPath, setCurrentPath] = useState(basePath);
const [entries, setEntries] = useState<FileEntry[]>(() =>
searchQuery.trim() ? [] : globalDirectoryCache.get(basePath) || []
);
const [searchResults, setSearchResults] = useState<FileEntry[]>(() => {
if (searchQuery.trim()) {
const cacheKey = `${basePath}:${searchQuery}`;
return globalSearchCache.get(cacheKey) || [];
}
return [];
});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [pathHistory, setPathHistory] = useState<string[]>([basePath]);
const [selectedIndex, setSelectedIndex] = useState(0);
const [isShowingCached, setIsShowingCached] = useState(() => {
// Check if we're showing cached data on mount
if (searchQuery.trim()) {
const cacheKey = `${basePath}:${searchQuery}`;
return globalSearchCache.has(cacheKey);
}
return globalDirectoryCache.has(basePath);
});
const searchDebounceRef = useRef<NodeJS.Timeout | null>(null);
const fileListRef = useRef<HTMLDivElement>(null);
// Computed values
const displayEntries = searchQuery.trim() ? searchResults : entries;
const canGoBack = pathHistory.length > 1;
// Get relative path for display
const relativePath = currentPath.startsWith(basePath)
? currentPath.slice(basePath.length) || '/'
: currentPath;
// Load directory contents
useEffect(() => {
loadDirectory(currentPath);
}, [currentPath]);
// Debounced search
useEffect(() => {
if (searchDebounceRef.current) {
clearTimeout(searchDebounceRef.current);
}
if (searchQuery.trim()) {
const cacheKey = `${basePath}:${searchQuery}`;
// Immediately show cached results if available
if (globalSearchCache.has(cacheKey)) {
console.log('[FilePicker] Immediately showing cached search results for:', searchQuery);
setSearchResults(globalSearchCache.get(cacheKey) || []);
setIsShowingCached(true);
setError(null);
}
// Schedule fresh search after debounce
searchDebounceRef.current = setTimeout(() => {
performSearch(searchQuery);
}, 300);
} else {
setSearchResults([]);
setIsShowingCached(false);
}
return () => {
if (searchDebounceRef.current) {
clearTimeout(searchDebounceRef.current);
}
};
}, [searchQuery, basePath]);
// Reset selected index when entries change
useEffect(() => {
setSelectedIndex(0);
}, [entries, searchResults]);
// Keyboard navigation
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const displayEntries = searchQuery.trim() ? searchResults : entries;
switch (e.key) {
case 'Escape':
e.preventDefault();
onClose();
break;
case 'Enter':
e.preventDefault();
// Enter always selects the current item (file or directory)
if (displayEntries.length > 0 && selectedIndex < displayEntries.length) {
onSelect(displayEntries[selectedIndex]);
}
break;
case 'ArrowUp':
e.preventDefault();
setSelectedIndex(prev => Math.max(0, prev - 1));
break;
case 'ArrowDown':
e.preventDefault();
setSelectedIndex(prev => Math.min(displayEntries.length - 1, prev + 1));
break;
case 'ArrowRight':
e.preventDefault();
// Right arrow enters directories
if (displayEntries.length > 0 && selectedIndex < displayEntries.length) {
const entry = displayEntries[selectedIndex];
if (entry.is_directory) {
navigateToDirectory(entry.path);
}
}
break;
case 'ArrowLeft':
e.preventDefault();
// Left arrow goes back to parent directory
if (canGoBack) {
navigateBack();
}
break;
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [entries, searchResults, selectedIndex, searchQuery, canGoBack]);
// Scroll selected item into view
useEffect(() => {
if (fileListRef.current) {
const selectedElement = fileListRef.current.querySelector(`[data-index="${selectedIndex}"]`);
if (selectedElement) {
selectedElement.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
}
}, [selectedIndex]);
const loadDirectory = async (path: string) => {
try {
console.log('[FilePicker] Loading directory:', path);
// Check cache first and show immediately
if (globalDirectoryCache.has(path)) {
console.log('[FilePicker] Showing cached contents for:', path);
setEntries(globalDirectoryCache.get(path) || []);
setIsShowingCached(true);
setError(null);
} else {
// Only show loading if we don't have cached data
setIsLoading(true);
}
// Always fetch fresh data in background
const contents = await api.listDirectoryContents(path);
console.log('[FilePicker] Loaded fresh contents:', contents.length, 'items');
// Cache the results
globalDirectoryCache.set(path, contents);
// Update with fresh data
setEntries(contents);
setIsShowingCached(false);
setError(null);
} catch (err) {
console.error('[FilePicker] Failed to load directory:', path, err);
console.error('[FilePicker] Error details:', err);
// Only set error if we don't have cached data to show
if (!globalDirectoryCache.has(path)) {
setError(err instanceof Error ? err.message : 'Failed to load directory');
}
} finally {
setIsLoading(false);
}
};
const performSearch = async (query: string) => {
try {
console.log('[FilePicker] Searching for:', query, 'in:', basePath);
// Create cache key that includes both query and basePath
const cacheKey = `${basePath}:${query}`;
// Check cache first and show immediately
if (globalSearchCache.has(cacheKey)) {
console.log('[FilePicker] Showing cached search results for:', query);
setSearchResults(globalSearchCache.get(cacheKey) || []);
setIsShowingCached(true);
setError(null);
} else {
// Only show loading if we don't have cached data
setIsLoading(true);
}
// Always fetch fresh results in background
const results = await api.searchFiles(basePath, query);
console.log('[FilePicker] Fresh search results:', results.length, 'items');
// Cache the results
globalSearchCache.set(cacheKey, results);
// Update with fresh results
setSearchResults(results);
setIsShowingCached(false);
setError(null);
} catch (err) {
console.error('[FilePicker] Search failed:', query, err);
// Only set error if we don't have cached data to show
const cacheKey = `${basePath}:${query}`;
if (!globalSearchCache.has(cacheKey)) {
setError(err instanceof Error ? err.message : 'Search failed');
}
} finally {
setIsLoading(false);
}
};
const navigateToDirectory = (path: string) => {
setCurrentPath(path);
setPathHistory(prev => [...prev, path]);
};
const navigateBack = () => {
if (pathHistory.length > 1) {
const newHistory = [...pathHistory];
newHistory.pop(); // Remove current
const previousPath = newHistory[newHistory.length - 1];
// Don't go beyond the base path
if (previousPath.startsWith(basePath) || previousPath === basePath) {
setCurrentPath(previousPath);
setPathHistory(newHistory);
}
}
};
const handleEntryClick = (entry: FileEntry) => {
// Single click always selects (file or directory)
onSelect(entry);
};
const handleEntryDoubleClick = (entry: FileEntry) => {
// Double click navigates into directories
if (entry.is_directory) {
navigateToDirectory(entry.path);
}
};
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
className={cn(
"absolute bottom-full mb-2 left-0 z-50",
"w-[500px] h-[400px]",
"bg-background border border-border rounded-lg shadow-lg",
"flex flex-col overflow-hidden",
className
)}
>
{/* Header */}
<div className="border-b border-border p-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="icon"
onClick={navigateBack}
disabled={!canGoBack}
className="h-8 w-8"
>
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Navigate up</span>
</Button>
<span className="text-sm font-mono text-muted-foreground truncate max-w-[300px]">
{relativePath}
</span>
</div>
<Button
variant="ghost"
size="icon"
onClick={onClose}
className="h-8 w-8"
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</div>
</div>
{/* File List */}
<div className="flex-1 overflow-y-auto relative">
{/* Show loading only if no cached data */}
{isLoading && displayEntries.length === 0 && (
<div className="flex items-center justify-center h-full">
<span className="text-sm text-muted-foreground">Loading...</span>
</div>
)}
{/* Show subtle indicator when displaying cached data while fetching fresh */}
{isShowingCached && isLoading && displayEntries.length > 0 && (
<div className="absolute top-1 right-2 text-xs text-muted-foreground/50 italic">
updating...
</div>
)}
{error && displayEntries.length === 0 && (
<div className="flex items-center justify-center h-full">
<span className="text-sm text-destructive">{error}</span>
</div>
)}
{!isLoading && !error && displayEntries.length === 0 && (
<div className="flex flex-col items-center justify-center h-full">
<Search className="h-8 w-8 text-muted-foreground mb-2" />
<span className="text-sm text-muted-foreground">
{searchQuery.trim() ? 'No files found' : 'Empty directory'}
</span>
</div>
)}
{displayEntries.length > 0 && (
<div className="p-2 space-y-0.5" ref={fileListRef}>
{displayEntries.map((entry, index) => {
const Icon = getFileIcon(entry);
const isSearching = searchQuery.trim() !== '';
const isSelected = index === selectedIndex;
return (
<button
key={entry.path}
data-index={index}
onClick={() => handleEntryClick(entry)}
onDoubleClick={() => handleEntryDoubleClick(entry)}
onMouseEnter={() => setSelectedIndex(index)}
className={cn(
"w-full flex items-center gap-2 px-2 py-1.5 rounded-md",
"hover:bg-accent transition-colors",
"text-left text-sm",
isSelected && "bg-accent"
)}
title={entry.is_directory ? "Click to select • Double-click to enter" : "Click to select"}
>
<Icon className={cn(
"h-4 w-4 flex-shrink-0",
entry.is_directory ? "text-blue-500" : "text-muted-foreground"
)} />
<span className="flex-1 truncate">
{entry.name}
</span>
{!entry.is_directory && entry.size > 0 && (
<span className="text-xs text-muted-foreground">
{formatFileSize(entry.size)}
</span>
)}
{entry.is_directory && (
<ChevronRight className="h-4 w-4 text-muted-foreground" />
)}
{isSearching && (
<span className="text-xs text-muted-foreground font-mono truncate max-w-[150px]">
{entry.path.replace(basePath, '').replace(/^\//, '')}
</span>
)}
</button>
);
})}
</div>
)}
</div>
{/* Footer */}
<div className="border-t border-border p-2">
<p className="text-xs text-muted-foreground text-center">
↑↓ Navigate • Enter Select • → Enter Directory • ← Go Back • Esc Close
</p>
</div>
</motion.div>
);
};