Spaces:
Running
Running
Download frontend/src/features/file-manager/components/FileExplorerView.tsx from Shadowfilebot/Bot: direct link, hf CLI and curl.
- Browser
- Download file 46.9 kB
-
https://huggingface.co/spaces/Shadowfilebot/Bot/resolve/main/frontend/src/features/file-manager/components/FileExplorerView.tsx
- Command line
-
hf download hf://spaces/Shadowfilebot/Bot/frontend/src/features/file-manager/components/FileExplorerView.tsx
-
curl -L -o FileExplorerView.tsx https://huggingface.co/spaces/Shadowfilebot/Bot/resolve/main/frontend/src/features/file-manager/components/FileExplorerView.tsx
46.9 kB
'use client';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
formatBytes,
formatDateVi,
getFileCategory,
joinPath,
} from '@/shared/lib/format';
import { useToast } from '@/shared/hooks/useToast';
import { Button } from '@/shared/components/Button';
import { Skeleton } from '@/shared/components/Card';
import { Input, Select } from '@/shared/components/Input';
import { ConfirmModal, Modal } from '@/shared/components/Modal';
import { useWorkspaceStore } from '@/features/workspace';
import {
Archive,
ChevronRight,
ClipboardPaste,
Copy,
Download,
Edit2,
Eye,
FileCode,
FilePlus,
FileText,
Folder,
FolderOutput,
FolderPlus,
Home,
Image as ImageIcon,
LayoutGrid,
List,
RefreshCw,
Scissors,
Search,
Trash2,
Upload,
X,
} from 'lucide-react';
import { validateEntryName } from '../schemas/fileSchema';
import { fileService } from '../services/fileService';
import { FileItem, FileSortBy, FileViewMode } from '../types/fileTypes';
function isSupportedArchive(name: string): boolean {
const lower = name.toLowerCase();
return (
lower.endsWith('.zip') ||
lower.endsWith('.tar.gz') ||
lower.endsWith('.tgz') ||
lower.endsWith('.tar')
);
}
function getArchiveStem(name: string): string {
const lower = name.toLowerCase();
if (lower.endsWith('.tar.gz')) return name.slice(0, -7) || 'extracted';
if (lower.endsWith('.tgz')) return name.slice(0, -4) || 'extracted';
if (lower.endsWith('.zip')) return name.slice(0, -4) || 'extracted';
if (lower.endsWith('.tar')) return name.slice(0, -4) || 'extracted';
return `${name}-extracted`;
}
export function FileExplorerView() {
const { activeZone, openFileInEditor } = useWorkspaceStore();
const { pushToast } = useToast();
const [currentPath, setCurrentPath] = useState('');
const [files, setFiles] = useState<FileItem[]>([]);
const [loading, setLoading] = useState(false);
const [search, setSearch] = useState('');
const [sortBy, setSortBy] = useState<FileSortBy>('name');
const [viewMode, setViewMode] = useState<FileViewMode>('list');
const [dragActive, setDragActive] = useState(false);
const [uploading, setUploading] = useState(false);
const [downloadingName, setDownloadingName] = useState<string | null>(null);
// Selection & Clipboard
const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());
const [clipboard, setClipboard] = useState<{
mode: 'copy' | 'move';
paths: string[];
zone: string;
} | null>(null);
const [pasting, setPasting] = useState(false);
// Modals
const [newFileOpen, setNewFileOpen] = useState(false);
const [newFileName, setNewFileName] = useState('');
const [newFolderOpen, setNewFolderOpen] = useState(false);
const [newFolderName, setNewFolderName] = useState('');
const [renameTarget, setRenameTarget] = useState<FileItem | null>(null);
const [renameValue, setRenameValue] = useState('');
const [deleteTarget, setDeleteTarget] = useState<FileItem | null>(null);
const [deleting, setDeleting] = useState(false);
const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
const [bulkDeleting, setBulkDeleting] = useState(false);
// Compress & Extract Modals
const [compressOpen, setCompressOpen] = useState(false);
const [compressName, setCompressName] = useState('archive.zip');
const [compressing, setCompressing] = useState(false);
const [extractTarget, setExtractTarget] = useState<FileItem | null>(null);
const [extractDestDir, setExtractDestDir] = useState('');
const [extracting, setExtracting] = useState(false);
// Quick Preview Modal
const [previewItem, setPreviewItem] = useState<FileItem | null>(null);
const [previewText, setPreviewText] = useState('');
const [previewImageUrl, setPreviewImageUrl] = useState<string | null>(null);
const [previewLoading, setPreviewLoading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const loadFiles = useCallback(
async (targetPath = currentPath) => {
if (!activeZone) return;
setLoading(true);
setSelectedNames(new Set());
try {
const list = await fileService.listFiles(activeZone, targetPath);
setFiles(list || []);
setCurrentPath(targetPath);
} catch (err: unknown) {
pushToast(err instanceof Error ? err.message : 'Không thể tải danh sách tệp', 'error');
} finally {
setLoading(false);
}
},
[activeZone, currentPath, pushToast],
);
useEffect(() => {
if (activeZone) {
setSearch('');
setClipboard((prev) => (prev && prev.zone === activeZone ? prev : null));
void loadFiles('');
}
}, [activeZone]);
useEffect(() => {
return () => {
if (previewImageUrl) URL.revokeObjectURL(previewImageUrl);
};
}, [previewImageUrl]);
const sortedAndFiltered = useMemo(() => {
const q = search.trim().toLowerCase();
const filtered = q ? files.filter((f) => f.name.toLowerCase().includes(q)) : [...files];
filtered.sort((a, b) => {
if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1;
if (sortBy === 'size') return b.size - a.size;
if (sortBy === 'modified') return (b.modified || '').localeCompare(a.modified || '');
return a.name.localeCompare(b.name);
});
return filtered;
}, [files, search, sortBy]);
const allVisibleSelected =
sortedAndFiltered.length > 0 &&
sortedAndFiltered.every((item) => selectedNames.has(item.name));
const toggleSelectItem = (name: string) => {
setSelectedNames((prev) => {
const next = new Set(prev);
if (next.has(name)) next.delete(name);
else next.add(name);
return next;
});
};
const toggleSelectAll = () => {
if (allVisibleSelected) {
setSelectedNames(new Set());
} else {
setSelectedNames(new Set(sortedAndFiltered.map((item) => item.name)));
}
};
const getSelectedRelPaths = (): string[] =>
Array.from(selectedNames).map((name) => joinPath(currentPath, name));
const handleStageClipboard = (mode: 'copy' | 'move') => {
if (!activeZone || selectedNames.size === 0) return;
const paths = getSelectedRelPaths();
setClipboard({ mode, paths, zone: activeZone });
setSelectedNames(new Set());
pushToast(
`Đã lưu ${paths.length} mục vào bộ nhớ tạm (${mode === 'copy' ? 'Sao chép' : 'Di chuyển'}).`,
'info',
);
};
const handlePasteClipboard = async () => {
if (!activeZone || !clipboard || clipboard.zone !== activeZone) return;
setPasting(true);
try {
const res = await fileService.transferFiles(
activeZone,
clipboard.paths,
currentPath,
clipboard.mode,
);
pushToast(
`${clipboard.mode === 'copy' ? 'Đã sao chép' : 'Đã di chuyển'} ${res.processed} mục.`,
'success',
);
if (clipboard.mode === 'move') {
setClipboard(null);
}
await loadFiles(currentPath);
} catch (err: unknown) {
pushToast(err instanceof Error ? err.message : 'Lỗi dán tệp', 'error');
} finally {
setPasting(false);
}
};
const handleOpenCompressModal = () => {
if (selectedNames.size === 0) return;
const first = Array.from(selectedNames)[0];
setCompressName(selectedNames.size === 1 ? `${first}.zip` : 'archive.zip');
setCompressOpen(true);
};
const handleCompressSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!activeZone || selectedNames.size === 0) return;
const paths = getSelectedRelPaths();
setCompressing(true);
try {
const res = await fileService.compressFiles(
activeZone,
paths,
compressName.trim() || 'archive.zip',
currentPath,
);
setCompressOpen(false);
setSelectedNames(new Set());
pushToast(`Đã nén ${res.files_count} tệp thành "${res.path}".`, 'success');
await loadFiles(currentPath);
} catch (err: unknown) {
pushToast(err instanceof Error ? err.message : 'Lỗi nén tệp', 'error');
} finally {
setCompressing(false);
}
};
const handleOpenExtractModal = (item: FileItem) => {
setExtractTarget(item);
setExtractDestDir(currentPath);
};
const handleExtractSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!activeZone || !extractTarget) return;
setExtracting(true);
try {
const res = await fileService.extractArchive(
activeZone,
joinPath(currentPath, extractTarget.name),
extractDestDir.trim(),
);
setExtractTarget(null);
pushToast(
`Đã giải nén ${res.extracted_count} mục vào ${res.dest_dir ? `./${res.dest_dir}` : 'thư mục gốc'}.`,
'success',
);
await loadFiles(currentPath);
} catch (err: unknown) {
pushToast(err instanceof Error ? err.message : 'Lỗi giải nén tệp', 'error');
} finally {
setExtracting(false);
}
};
const handleBulkDeleteConfirm = async () => {
if (!activeZone || selectedNames.size === 0) return;
setBulkDeleting(true);
try {
const res = await fileService.bulkDelete(activeZone, getSelectedRelPaths());
setBulkDeleteOpen(false);
setSelectedNames(new Set());
pushToast(`Đã xoá ${res.deleted} mục.`, 'success');
await loadFiles(currentPath);
} catch (err: unknown) {
pushToast(err instanceof Error ? err.message : 'Lỗi xoá hàng loạt', 'error');
} finally {
setBulkDeleting(false);
}
};
const handleUploadFiles = async (fileList: FileList | File[]) => {
if (!activeZone || fileList.length === 0) return;
setUploading(true);
let okCount = 0;
for (let i = 0; i < fileList.length; i++) {
const f = fileList[i];
try {
await fileService.uploadFile(activeZone, currentPath, f);
okCount++;
} catch (err: unknown) {
pushToast(
`Upload ${f.name} lỗi: ${err instanceof Error ? err.message : 'Thất bại'}`,
'error',
);
}
}
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = '';
if (okCount > 0) {
pushToast(`Đã tải lên ${okCount} tệp.`, 'success');
await loadFiles(currentPath);
}
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setDragActive(false);
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
void handleUploadFiles(e.dataTransfer.files);
}
};
const handleCreateFile = async (e: React.FormEvent) => {
e.preventDefault();
if (!activeZone) return;
const check = validateEntryName(newFileName, 'Tên tệp');
if (!check.ok || !check.data) {
pushToast(check.error || 'Tên tệp không hợp lệ', 'error');
return;
}
const target = joinPath(currentPath, check.data);
try {
await fileService.writeFile(activeZone, target, '');
setNewFileOpen(false);
setNewFileName('');
pushToast(`Đã tạo tệp ${check.data}`, 'success');
await loadFiles(currentPath);
openFileInEditor(target);
} catch (err: unknown) {
pushToast(err instanceof Error ? err.message : 'Lỗi tạo tệp', 'error');
}
};
const handleCreateFolder = async (e: React.FormEvent) => {
e.preventDefault();
if (!activeZone) return;
const check = validateEntryName(newFolderName, 'Tên thư mục');
if (!check.ok || !check.data) {
pushToast(check.error || 'Tên thư mục không hợp lệ', 'error');
return;
}
const target = joinPath(currentPath, check.data);
try {
await fileService.mkdir(activeZone, target);
setNewFolderOpen(false);
setNewFolderName('');
pushToast(`Đã tạo thư mục ${check.data}`, 'success');
await loadFiles(currentPath);
} catch (err: unknown) {
pushToast(err instanceof Error ? err.message : 'Lỗi tạo thư mục', 'error');
}
};
const handleRenameSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!activeZone || !renameTarget) return;
const check = validateEntryName(renameValue, 'Tên mới');
if (!check.ok || !check.data) {
pushToast(check.error || 'Tên mới không hợp lệ', 'error');
return;
}
const oldPath = joinPath(currentPath, renameTarget.name);
try {
await fileService.renameFile(activeZone, oldPath, check.data);
setRenameTarget(null);
setRenameValue('');
pushToast('Đã đổi tên thành công.', 'success');
await loadFiles(currentPath);
} catch (err: unknown) {
pushToast(err instanceof Error ? err.message : 'Lỗi đổi tên', 'error');
}
};
const handleDeleteConfirm = async () => {
if (!activeZone || !deleteTarget) return;
setDeleting(true);
try {
await fileService.deleteFile(activeZone, joinPath(currentPath, deleteTarget.name));
pushToast(`Đã xoá ${deleteTarget.name}`, 'success');
setDeleteTarget(null);
await loadFiles(currentPath);
} catch (err: unknown) {
pushToast(err instanceof Error ? err.message : 'Lỗi xoá tệp', 'error');
} finally {
setDeleting(false);
}
};
const handleDownload = async (item: FileItem) => {
if (!activeZone) return;
setDownloadingName(item.name);
try {
const blob = await fileService.downloadBlob(activeZone, joinPath(currentPath, item.name));
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = item.is_dir ? `${item.name}.zip` : item.name;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
} catch (err: unknown) {
pushToast(err instanceof Error ? err.message : 'Lỗi tải xuống', 'error');
} finally {
setDownloadingName(null);
}
};
const handleCopyPath = async (item: FileItem) => {
const full = joinPath(currentPath, item.name);
try {
await navigator.clipboard.writeText(full);
pushToast(`Đã sao chép: ${full}`, 'info');
} catch {
pushToast('Không thể sao chép vào clipboard', 'error');
}
};
const handleQuickPreview = async (item: FileItem) => {
if (!activeZone || item.is_dir) return;
const cat = getFileCategory(item.name, false);
const fullPath = joinPath(currentPath, item.name);
if (previewImageUrl) {
URL.revokeObjectURL(previewImageUrl);
setPreviewImageUrl(null);
}
setPreviewText('');
setPreviewItem(item);
setPreviewLoading(true);
try {
if (cat === 'image') {
const blob = await fileService.downloadBlob(activeZone, fullPath);
setPreviewImageUrl(URL.createObjectURL(blob));
} else {
const res = await fileService.readFile(activeZone, fullPath);
setPreviewText((res.content || '').slice(0, 12000));
}
} catch (err: unknown) {
setPreviewText(err instanceof Error ? err.message : 'Không thể xem trước tệp này.');
} finally {
setPreviewLoading(false);
}
};
const renderIcon = (item: FileItem) => {
const cat = getFileCategory(item.name, item.is_dir);
if (cat === 'dir') return <Folder className="w-4 h-4 text-amber-500 flex-shrink-0" aria-hidden="true" />;
if (cat === 'image') return <ImageIcon className="w-4 h-4 text-emerald-500 flex-shrink-0" aria-hidden="true" />;
if (cat === 'code') return <FileCode className="w-4 h-4 text-accent flex-shrink-0" aria-hidden="true" />;
if (cat === 'archive') return <Archive className="w-4 h-4 text-sky-500 flex-shrink-0" aria-hidden="true" />;
return <FileText className="w-4 h-4 text-ink-2 flex-shrink-0" aria-hidden="true" />;
};
const handleOpenItem = (item: FileItem) => {
const target = joinPath(currentPath, item.name);
if (item.is_dir) {
void loadFiles(target);
return;
}
const cat = getFileCategory(item.name, false);
if (cat === 'image') void handleQuickPreview(item);
else openFileInEditor(target);
};
const pathSegments = currentPath ? currentPath.split('/').filter(Boolean) : [];
return (
<div
onDragOver={(e) => {
e.preventDefault();
setDragActive(true);
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node)) setDragActive(false);
}}
onDrop={handleDrop}
className="relative flex-1 flex flex-col h-full bg-canvas overflow-hidden"
>
{dragActive && (
<div className="absolute inset-3 z-40 rounded-2xl border-2 border-dashed border-accent bg-accent/10 backdrop-blur-sm flex flex-col items-center justify-center gap-2 pointer-events-none">
<Upload className="w-8 h-8 text-accent" aria-hidden="true" />
<p className="text-sm font-bold text-ink-1">
Thả tệp vào đây để tải lên /{currentPath}
</p>
</div>
)}
{/* Action & Breadcrumb Header */}
<div className="border-b border-line px-4 sm:px-6 py-2.5 bg-surface-1/70 flex flex-col gap-2.5 flex-shrink-0">
<div className="flex flex-wrap items-center justify-between gap-2">
<nav aria-label="Đường dẫn thư mục" className="flex items-center gap-1 text-xs overflow-x-auto">
<button
type="button"
onClick={() => void loadFiles('')}
className={`inline-flex items-center gap-1.5 px-2.5 py-1 min-h-[34px] rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
currentPath === ''
? 'bg-accent/10 text-accent font-semibold'
: 'text-ink-2 hover:bg-surface-2'
}`}
>
<Home className="w-3.5 h-3.5" aria-hidden="true" />
<span className="font-mono">{activeZone}</span>
</button>
{pathSegments.map((seg, idx) => {
const target = pathSegments.slice(0, idx + 1).join('/');
const isLast = idx === pathSegments.length - 1;
return (
<React.Fragment key={target}>
<ChevronRight className="w-3.5 h-3.5 text-ink-3 flex-shrink-0" aria-hidden="true" />
<button
type="button"
onClick={() => void loadFiles(target)}
className={`px-2 py-1 min-h-[34px] rounded-lg font-mono focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
isLast
? 'bg-surface-2 text-ink-1 font-semibold'
: 'text-ink-2 hover:bg-surface-2'
}`}
>
{seg}
</button>
</React.Fragment>
);
})}
</nav>
<div className="flex flex-wrap items-center gap-1.5">
<input
ref={fileInputRef}
type="file"
multiple
onChange={(e) => e.target.files && void handleUploadFiles(e.target.files)}
className="hidden"
aria-label="Chọn tệp để tải lên"
/>
<Button size="sm" variant="secondary" onClick={() => setNewFileOpen(true)}>
<FilePlus className="w-3.5 h-3.5" aria-hidden="true" />
<span className="hidden sm:inline">Tạo File</span>
</Button>
<Button size="sm" variant="secondary" onClick={() => setNewFolderOpen(true)}>
<FolderPlus className="w-3.5 h-3.5" aria-hidden="true" />
<span className="hidden sm:inline">Thư mục</span>
</Button>
<Button
size="sm"
variant="primary"
loading={uploading}
onClick={() => fileInputRef.current?.click()}
>
<Upload className="w-3.5 h-3.5" aria-hidden="true" />
<span>{uploading ? 'Đang tải...' : 'Upload'}</span>
</Button>
<button
type="button"
onClick={() => void loadFiles(currentPath)}
aria-label="Làm mới danh sách tệp"
className="p-2 min-h-[36px] min-w-[36px] flex items-center justify-center rounded-lg border border-line bg-surface-2 hover:bg-surface-3 text-ink-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} aria-hidden="true" />
</button>
</div>
</div>
{/* Search, Sort & View Controls */}
<div className="flex flex-wrap items-center gap-2">
<div className="flex-1 min-w-[180px]">
<Input
aria-label="Lọc tệp trong thư mục"
placeholder="Tìm nhanh theo tên tệp hoặc thư mục..."
value={search}
onChange={(e) => setSearch(e.target.value)}
leftIcon={<Search className="w-3.5 h-3.5" />}
className="min-h-[36px] text-xs"
/>
</div>
<div className="w-36">
<Select
aria-label="Sắp xếp theo"
value={sortBy}
onChange={(e) => setSortBy(e.target.value as FileSortBy)}
className="min-h-[36px] py-1 text-xs"
>
<option value="name">Tên (A → Z)</option>
<option value="size">Kích thước</option>
<option value="modified">Ngày sửa</option>
</Select>
</div>
<div className="flex items-center bg-surface-2 border border-line rounded-lg p-0.5">
<button
type="button"
onClick={() => setViewMode('list')}
aria-label="Chế độ danh sách"
aria-pressed={viewMode === 'list'}
className={`p-1.5 min-h-[32px] min-w-[32px] flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
viewMode === 'list' ? 'bg-accent text-on-accent' : 'text-ink-2 hover:text-ink-1'
}`}
>
<List className="w-3.5 h-3.5" aria-hidden="true" />
</button>
<button
type="button"
onClick={() => setViewMode('grid')}
aria-label="Chế độ lưới"
aria-pressed={viewMode === 'grid'}
className={`p-1.5 min-h-[32px] min-w-[32px] flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
viewMode === 'grid' ? 'bg-accent text-on-accent' : 'text-ink-2 hover:text-ink-1'
}`}
>
<LayoutGrid className="w-3.5 h-3.5" aria-hidden="true" />
</button>
</div>
</div>
{/* Bulk Selection & Clipboard Bar */}
{(selectedNames.size > 0 || (clipboard && clipboard.zone === activeZone)) && (
<div className="flex flex-wrap items-center justify-between gap-2 pt-1 border-t border-line/70">
<div className="flex flex-wrap items-center gap-1.5">
{selectedNames.size > 0 ? (
<>
<span className="text-xs font-mono font-semibold text-accent px-2 py-1 rounded-md bg-accent/10 border border-accent/30">
Đã chọn {selectedNames.size} mục
</span>
<Button
size="sm"
variant="secondary"
onClick={() => handleStageClipboard('copy')}
>
<Copy className="w-3.5 h-3.5" aria-hidden="true" />
<span>Sao chép</span>
</Button>
<Button
size="sm"
variant="secondary"
onClick={() => handleStageClipboard('move')}
>
<Scissors className="w-3.5 h-3.5" aria-hidden="true" />
<span>Di chuyển</span>
</Button>
<Button
size="sm"
variant="secondary"
onClick={handleOpenCompressModal}
>
<Archive className="w-3.5 h-3.5" aria-hidden="true" />
<span>Nén ZIP</span>
</Button>
<Button
size="sm"
variant="danger"
onClick={() => setBulkDeleteOpen(true)}
>
<Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
<span>Xoá ({selectedNames.size})</span>
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => setSelectedNames(new Set())}
>
<X className="w-3.5 h-3.5" aria-hidden="true" />
<span>Bỏ chọn</span>
</Button>
</>
) : (
<button
type="button"
onClick={toggleSelectAll}
className="text-xs font-medium text-ink-2 hover:text-ink-1 px-2 py-1 rounded-lg hover:bg-surface-2"
>
{allVisibleSelected ? 'Bỏ chọn tất cả' : 'Chọn tất cả'}
</button>
)}
</div>
{clipboard && clipboard.zone === activeZone && (
<div className="flex flex-wrap items-center gap-1.5">
<span className="text-xs text-ink-2 font-mono">
Clipboard ({clipboard.mode === 'copy' ? 'Copy' : 'Move'}: {clipboard.paths.length} mục)
</span>
<Button
size="sm"
variant="primary"
loading={pasting}
onClick={() => void handlePasteClipboard()}
>
<ClipboardPaste className="w-3.5 h-3.5" aria-hidden="true" />
<span>Dán vào /{currentPath}</span>
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => setClipboard(null)}
>
<X className="w-3.5 h-3.5" aria-hidden="true" />
<span>Huỷ</span>
</Button>
</div>
)}
</div>
)}
</div>
{/* Directory Content */}
<div className="flex-1 overflow-y-auto p-4 sm:p-6">
{loading ? (
<div className="space-y-2">
<Skeleton className="h-11 w-full" />
<Skeleton className="h-11 w-full" />
<Skeleton className="h-11 w-full" />
<Skeleton className="h-11 w-full" />
</div>
) : sortedAndFiltered.length === 0 ? (
<div className="rounded-2xl border border-dashed border-line bg-surface-1/50 p-12 text-center space-y-2">
<Folder className="w-10 h-10 mx-auto text-ink-3" aria-hidden="true" />
<p className="text-xs sm:text-sm font-medium text-ink-2">
{search ? 'Không tìm thấy tệp phù hợp.' : 'Thư mục trống. Kéo-thả tệp vào đây hoặc bấm Upload.'}
</p>
</div>
) : viewMode === 'grid' ? (
<div className="space-y-3">
<div className="flex items-center justify-between text-xs text-ink-3">
<label className="inline-flex items-center gap-2 cursor-pointer text-ink-2">
<input
type="checkbox"
checked={allVisibleSelected}
onChange={toggleSelectAll}
className="rounded border-line-strong text-accent focus:ring-accent"
/>
<span>Chọn tất cả ({sortedAndFiltered.length})</span>
</label>
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
{sortedAndFiltered.map((item) => {
const selected = selectedNames.has(item.name);
const archiveItem = !item.is_dir && isSupportedArchive(item.name);
return (
<div
key={item.name}
className={`group relative rounded-xl border p-3 flex flex-col justify-between gap-3 transition-colors ${
selected
? 'border-accent bg-accent/10'
: 'border-line bg-surface-1 hover:border-accent/50'
}`}
>
<input
type="checkbox"
checked={selected}
onChange={() => toggleSelectItem(item.name)}
aria-label={`Chọn ${item.name}`}
className="absolute top-2.5 right-2.5 rounded border-line-strong text-accent focus:ring-accent cursor-pointer"
/>
<button
type="button"
onClick={() => handleOpenItem(item)}
className="text-left space-y-2 pr-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent rounded-lg"
>
<div className="w-9 h-9 rounded-lg bg-surface-2 flex items-center justify-center">
{renderIcon(item)}
</div>
<div className="font-mono text-xs font-semibold text-ink-1 truncate">
{item.name}
</div>
<div className="text-[11px] font-mono tabular-nums text-ink-3">
{item.is_dir ? 'Thư mục' : formatBytes(item.size)}
</div>
</button>
<div className="flex items-center justify-end gap-1 pt-1 border-t border-line/60">
{archiveItem && (
<button
type="button"
onClick={() => handleOpenExtractModal(item)}
aria-label={`Giải nén ${item.name}`}
title="Giải nén"
className="p-1.5 min-h-[30px] min-w-[30px] rounded-md text-ink-3 hover:text-sky-500 hover:bg-surface-2"
>
<FolderOutput className="w-3.5 h-3.5" aria-hidden="true" />
</button>
)}
{!item.is_dir && (
<button
type="button"
onClick={() => void handleQuickPreview(item)}
aria-label={`Xem nhanh ${item.name}`}
className="p-1.5 min-h-[30px] min-w-[30px] rounded-md text-ink-3 hover:text-accent hover:bg-surface-2"
>
<Eye className="w-3.5 h-3.5" aria-hidden="true" />
</button>
)}
<button
type="button"
onClick={() => void handleDownload(item)}
aria-label={`Tải ${item.name}`}
className="p-1.5 min-h-[30px] min-w-[30px] rounded-md text-ink-3 hover:text-ink-1 hover:bg-surface-2"
>
<Download className="w-3.5 h-3.5" aria-hidden="true" />
</button>
<button
type="button"
onClick={() => setDeleteTarget(item)}
aria-label={`Xoá ${item.name}`}
className="p-1.5 min-h-[30px] min-w-[30px] rounded-md text-ink-3 hover:text-rose-500 hover:bg-rose-500/10"
>
<Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
</button>
</div>
</div>
);
})}
</div>
</div>
) : (
<div className="rounded-2xl border border-line bg-surface-1 overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="border-b border-line bg-surface-2/60 text-[11px] font-mono uppercase tracking-wider text-ink-3">
<th className="pl-4 pr-2 py-2.5 w-8">
<input
type="checkbox"
checked={allVisibleSelected}
onChange={toggleSelectAll}
aria-label="Chọn tất cả tệp"
className="rounded border-line-strong text-accent focus:ring-accent cursor-pointer"
/>
</th>
<th className="px-3 py-2.5">Tên</th>
<th className="px-4 py-2.5 hidden sm:table-cell">Kích thước</th>
<th className="px-4 py-2.5 hidden md:table-cell">Cập nhật</th>
<th className="px-4 py-2.5 text-right">Thao tác</th>
</tr>
</thead>
<tbody className="divide-y divide-line text-xs">
{sortedAndFiltered.map((item) => {
const selected = selectedNames.has(item.name);
const archiveItem = !item.is_dir && isSupportedArchive(item.name);
return (
<tr
key={item.name}
className={selected ? 'bg-accent/10' : 'hover:bg-surface-2/60'}
>
<td className="pl-4 pr-2 py-2.5">
<input
type="checkbox"
checked={selected}
onChange={() => toggleSelectItem(item.name)}
aria-label={`Chọn ${item.name}`}
className="rounded border-line-strong text-accent focus:ring-accent cursor-pointer"
/>
</td>
<td className="px-3 py-2.5">
<button
type="button"
onClick={() => handleOpenItem(item)}
className="flex items-center gap-2.5 min-h-[34px] text-left font-mono font-medium text-ink-1 hover:text-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent rounded"
>
{renderIcon(item)}
<span className="truncate max-w-[200px] sm:max-w-md">{item.name}</span>
</button>
</td>
<td className="px-4 py-2.5 font-mono tabular-nums text-ink-2 hidden sm:table-cell">
{item.is_dir ? '—' : formatBytes(item.size)}
</td>
<td className="px-4 py-2.5 font-mono tabular-nums text-ink-3 hidden md:table-cell">
{formatDateVi(item.modified)}
</td>
<td className="px-4 py-2.5">
<div className="flex items-center justify-end gap-1">
{archiveItem && (
<button
type="button"
onClick={() => handleOpenExtractModal(item)}
aria-label={`Giải nén ${item.name}`}
title="Giải nén"
className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-sky-500 hover:bg-surface-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<FolderOutput className="w-3.5 h-3.5" aria-hidden="true" />
</button>
)}
{!item.is_dir && (
<button
type="button"
onClick={() => void handleQuickPreview(item)}
aria-label={`Xem nhanh ${item.name}`}
className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-accent hover:bg-surface-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<Eye className="w-3.5 h-3.5" aria-hidden="true" />
</button>
)}
<button
type="button"
onClick={() => void handleCopyPath(item)}
aria-label={`Sao chép đường dẫn ${item.name}`}
className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-ink-1 hover:bg-surface-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<Copy className="w-3.5 h-3.5" aria-hidden="true" />
</button>
<button
type="button"
onClick={() => {
setRenameTarget(item);
setRenameValue(item.name);
}}
aria-label={`Đổi tên ${item.name}`}
className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-ink-1 hover:bg-surface-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<Edit2 className="w-3.5 h-3.5" aria-hidden="true" />
</button>
<button
type="button"
onClick={() => void handleDownload(item)}
disabled={downloadingName === item.name}
aria-label={`Tải xuống ${item.name}`}
className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-ink-1 hover:bg-surface-3 disabled:opacity-40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<Download className="w-3.5 h-3.5" aria-hidden="true" />
</button>
<button
type="button"
onClick={() => setDeleteTarget(item)}
aria-label={`Xoá ${item.name}`}
className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-rose-500 hover:bg-rose-500/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
</button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
{/* Create File Modal */}
<Modal open={newFileOpen} onClose={() => setNewFileOpen(false)} title="Tạo tệp mới">
<form onSubmit={handleCreateFile} className="space-y-4">
<Input
label="Tên tệp"
required
autoFocus
value={newFileName}
onChange={(e) => setNewFileName(e.target.value)}
placeholder="vd: server.js, .env, main.py"
/>
<div className="flex justify-end gap-2">
<Button variant="secondary" size="sm" onClick={() => setNewFileOpen(false)}>
Huỷ
</Button>
<Button type="submit" size="sm">
Tạo & Mở Editor
</Button>
</div>
</form>
</Modal>
{/* Create Folder Modal */}
<Modal open={newFolderOpen} onClose={() => setNewFolderOpen(false)} title="Tạo thư mục mới">
<form onSubmit={handleCreateFolder} className="space-y-4">
<Input
label="Tên thư mục"
required
autoFocus
value={newFolderName}
onChange={(e) => setNewFolderName(e.target.value)}
placeholder="vd: src, config, logs"
/>
<div className="flex justify-end gap-2">
<Button variant="secondary" size="sm" onClick={() => setNewFolderOpen(false)}>
Huỷ
</Button>
<Button type="submit" size="sm">
Tạo thư mục
</Button>
</div>
</form>
</Modal>
{/* Rename Modal */}
<Modal
open={Boolean(renameTarget)}
onClose={() => setRenameTarget(null)}
title={`Đổi tên: ${renameTarget?.name || ''}`}
>
<form onSubmit={handleRenameSubmit} className="space-y-4">
<Input
label="Tên mới"
required
autoFocus
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
/>
<div className="flex justify-end gap-2">
<Button variant="secondary" size="sm" onClick={() => setRenameTarget(null)}>
Huỷ
</Button>
<Button type="submit" size="sm">
Lưu tên mới
</Button>
</div>
</form>
</Modal>
{/* Quick Preview Modal */}
<Modal
open={Boolean(previewItem)}
onClose={() => setPreviewItem(null)}
title={`Xem nhanh: ${previewItem?.name || ''}`}
maxWidthClass="max-w-2xl"
>
{previewLoading ? (
<div className="space-y-2">
<Skeleton className="h-48 w-full" />
</div>
) : previewImageUrl ? (
<div className="flex flex-col items-center gap-3">
<img
src={previewImageUrl}
alt={previewItem?.name || 'Ảnh xem trước'}
className="max-h-[60vh] rounded-xl border border-line object-contain bg-surface-2"
/>
</div>
) : (
<div className="space-y-3">
<pre className="p-4 rounded-xl bg-surface-2 border border-line text-xs font-mono text-ink-1 overflow-auto max-h-[55vh] whitespace-pre-wrap break-words">
{previewText || '(Tệp trống)'}
</pre>
{previewItem && (
<div className="flex justify-end">
<Button
size="sm"
onClick={() => {
const target = joinPath(currentPath, previewItem.name);
setPreviewItem(null);
openFileInEditor(target);
}}
>
Mở trong Editor
</Button>
</div>
)}
</div>
)}
</Modal>
<ConfirmModal
open={Boolean(deleteTarget)}
onClose={() => setDeleteTarget(null)}
onConfirm={handleDeleteConfirm}
title="Xoá mục đã chọn"
description={`Bạn có chắc muốn xoá ${deleteTarget?.is_dir ? 'thư mục' : 'tệp'} "${deleteTarget?.name}"?`}
confirmLabel="Xoá"
danger
loading={deleting}
/>
{/* Compress Modal */}
<Modal
open={compressOpen}
onClose={() => setCompressOpen(false)}
title={`Nén ${selectedNames.size} mục thành ZIP`}
>
<form onSubmit={handleCompressSubmit} className="space-y-4">
<Input
label="Tên file ZIP đầu ra"
required
autoFocus
value={compressName}
onChange={(e) => setCompressName(e.target.value)}
placeholder="archive.zip"
helperText={`Sẽ lưu tại /${currentPath}`}
className="font-mono"
/>
<div className="flex justify-end gap-2">
<Button variant="secondary" size="sm" onClick={() => setCompressOpen(false)}>
Huỷ
</Button>
<Button type="submit" size="sm" loading={compressing}>
Nén ngay
</Button>
</div>
</form>
</Modal>
{/* Extract Archive Modal */}
<Modal
open={Boolean(extractTarget)}
onClose={() => setExtractTarget(null)}
title={`Giải nén: ${extractTarget?.name || ''}`}
>
<form onSubmit={handleExtractSubmit} className="space-y-4">
<Input
label="Thư mục đích trong Zone (để trống = thư mục gốc Zone)"
autoFocus
value={extractDestDir}
onChange={(e) => setExtractDestDir(e.target.value)}
placeholder="vd: dist, app/public"
className="font-mono"
/>
{extractTarget && (
<button
type="button"
onClick={() =>
setExtractDestDir(joinPath(currentPath, getArchiveStem(extractTarget.name)))
}
className="text-xs font-mono text-accent hover:underline"
>
+ Giải nén vào thư mục con ./{joinPath(currentPath, getArchiveStem(extractTarget.name))}
</button>
)}
<div className="flex justify-end gap-2">
<Button variant="secondary" size="sm" onClick={() => setExtractTarget(null)}>
Huỷ
</Button>
<Button type="submit" size="sm" loading={extracting}>
Giải nén ngay
</Button>
</div>
</form>
</Modal>
{/* Bulk Delete Confirmation */}
<ConfirmModal
open={bulkDeleteOpen}
onClose={() => setBulkDeleteOpen(false)}
onConfirm={handleBulkDeleteConfirm}
title="Xoá hàng loạt"
description={`Bạn có chắc muốn xoá vĩnh viễn ${selectedNames.size} mục đang chọn?`}
confirmLabel={`Xoá ${selectedNames.size} mục`}
danger
loading={bulkDeleting}
/>
</div>
);
}
'use client';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
formatBytes,
formatDateVi,
getFileCategory,
joinPath,
} from '@/shared/lib/format';
import { useToast } from '@/shared/hooks/useToast';
import { Button } from '@/shared/components/Button';
import { Skeleton } from '@/shared/components/Card';
import { Input, Select } from '@/shared/components/Input';
import { ConfirmModal, Modal } from '@/shared/components/Modal';
import { useWorkspaceStore } from '@/features/workspace';
import {
Archive,
ChevronRight,
ClipboardPaste,
Copy,
Download,
Edit2,
Eye,
FileCode,
FilePlus,
FileText,
Folder,
FolderOutput,
FolderPlus,
Home,
Image as ImageIcon,
LayoutGrid,
List,
RefreshCw,
Scissors,
Search,
Trash2,
Upload,
X,
} from 'lucide-react';
import { validateEntryName } from '../schemas/fileSchema';
import { fileService } from '../services/fileService';
import { FileItem, FileSortBy, FileViewMode } from '../types/fileTypes';
function isSupportedArchive(name: string): boolean {
const lower = name.toLowerCase();
return (
lower.endsWith('.zip') ||
lower.endsWith('.tar.gz') ||
lower.endsWith('.tgz') ||
lower.endsWith('.tar')
);
}
function getArchiveStem(name: string): string {
const lower = name.toLowerCase();
if (lower.endsWith('.tar.gz')) return name.slice(0, -7) || 'extracted';
if (lower.endsWith('.tgz')) return name.slice(0, -4) || 'extracted';
if (lower.endsWith('.zip')) return name.slice(0, -4) || 'extracted';
if (lower.endsWith('.tar')) return name.slice(0, -4) || 'extracted';
return `${name}-extracted`;
}
export function FileExplorerView() {
const { activeZone, openFileInEditor } = useWorkspaceStore();
const { pushToast } = useToast();
const [currentPath, setCurrentPath] = useState('');
const [files, setFiles] = useState<FileItem[]>([]);
const [loading, setLoading] = useState(false);
const [search, setSearch] = useState('');
const [sortBy, setSortBy] = useState<FileSortBy>('name');
const [viewMode, setViewMode] = useState<FileViewMode>('list');
const [dragActive, setDragActive] = useState(false);
const [uploading, setUploading] = useState(false);
const [downloadingName, setDownloadingName] = useState<string | null>(null);
// Selection & Clipboard
const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());
const [clipboard, setClipboard] = useState<{
mode: 'copy' | 'move';
paths: string[];
zone: string;
} | null>(null);
const [pasting, setPasting] = useState(false);
// Modals
const [newFileOpen, setNewFileOpen] = useState(false);
const [newFileName, setNewFileName] = useState('');
const [newFolderOpen, setNewFolderOpen] = useState(false);
const [newFolderName, setNewFolderName] = useState('');
const [renameTarget, setRenameTarget] = useState<FileItem | null>(null);
const [renameValue, setRenameValue] = useState('');
const [deleteTarget, setDeleteTarget] = useState<FileItem | null>(null);
const [deleting, setDeleting] = useState(false);
const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
const [bulkDeleting, setBulkDeleting] = useState(false);
// Compress & Extract Modals
const [compressOpen, setCompressOpen] = useState(false);