进一步优化 合理拆分文件和优化

This commit is contained in:
Chen committed 2025-12-07 16:08:00 +08:00
1 parent ed76ec5da3
commit fa5bb66d14
30 files changed
+3007 -2363

No files matched your search

@@ -0,0 +1,25 @@
/**
* 拖拽上传提示覆盖层组件
*/
const DragDropOverlay = ({ isVisible }) => {
if (!isVisible) return null;
return (
<div className="absolute inset-0 z-50 bg-blue-500 bg-opacity-20 border-4 border-dashed border-blue-500 flex items-center justify-center pointer-events-none">
<div className="bg-white dark:bg-gray-800 rounded-lg p-8 shadow-2xl">
<div className="text-center">
<div className="text-6xl mb-4">📤</div>
<p className="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">
拖放图片到这里
</p>
<p className="text-sm text-gray-500 dark:text-gray-400">
支持 JPG、PNG、GIF、WebP 等格式
</p>
</div>
</div>
</div>
);
};
export default DragDropOverlay;
+21
View File
@@ -0,0 +1,21 @@
/**
* 空状态提示组件
*/
const EmptyState = ({ isLoading }) => {
return (
<div className="text-center">
{isLoading ? (
<p className="text-lg mb-2">加载中...</p>
) : (
<>
<p className="text-lg mb-2">暂无图片</p>
<p className="text-sm">请添加素材库或调整搜索条件</p>
<p className="text-xs mt-4 text-gray-400">可以直接拖拽文件到这里上传</p>
</>
)}
</div>
);
};
export default EmptyState;
+138
View File
@@ -0,0 +1,138 @@
/**
* 图片单元格组件
*/
import { Play, FileText, Palette, Music, File } from 'lucide-react';
const ImageCell = ({
image,
flatIndex,
isSelected,
renamingImage,
editingFilename,
editInputRef,
getThumbnailUrl,
onImageClick,
onImageDoubleClick,
onContextMenu,
onDragStart,
onEditingChange,
onFinishRename,
onCancelRename,
onStartRename
}) => {
const handleKeyDown = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
onFinishRename();
} else if (e.key === 'Escape') {
e.preventDefault();
onCancelRename();
}
};
const handleDoubleClickFilename = (e) => {
// 始终阻止事件冒泡,避免触发图片放大
e.stopPropagation();
// 只在单选且不在编辑状态时允许双击重命名
if (!renamingImage) {
onStartRename(image);
}
};
return (
<div
className="flex-shrink-0"
style={{ width: `${image.calculatedWidth}px` }}
>
<div
className={`relative group cursor-pointer overflow-hidden rounded-lg transition-all hover:shadow-lg ${
isSelected
? 'border-2 border-blue-400 dark:border-blue-500'
: 'border border-gray-200 dark:border-gray-600'
}`}
style={{
height: `${image.calculatedHeight}px`
}}
onClick={(e) => onImageClick(image, e, flatIndex)}
onDoubleClick={() => onImageDoubleClick(image, flatIndex)}
onContextMenu={(e) => onContextMenu(e, image)}
draggable={true}
onDragStart={(e) => onDragStart(e, image)}
>
<img
src={getThumbnailUrl(image) || 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="200" height="200"%3E%3Crect fill="%23f3f4f6" width="200" height="200"/%3E%3Ctext x="50%25" y="45%25" dominant-baseline="middle" text-anchor="middle" fill="%239ca3af" font-family="sans-serif" font-size="14"%3E需要同步%3C/text%3E%3Ctext x="50%25" y="60%25" dominant-baseline="middle" text-anchor="middle" fill="%23d1d5db" font-family="sans-serif" font-size="12"%3E点击同步按钮%3C/text%3E%3C/svg%3E'}
alt={image.filename}
className="w-full h-full object-cover"
loading="lazy"
onError={(e) => {
e.target.src = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="200" height="200"%3E%3Crect fill="%23fef2f2" width="200" height="200"/%3E%3Ctext x="50%25" y="45%25" dominant-baseline="middle" text-anchor="middle" fill="%23dc2626" font-family="sans-serif" font-size="14"%3E加载失败%3C/text%3E%3Ctext x="50%25" y="60%25" dominant-baseline="middle" text-anchor="middle" fill="%23f87171" font-family="sans-serif" font-size="12"%3E请重新同步%3C/text%3E%3C/svg%3E';
e.target.onerror = null;
}}
/>
{/* 文件类型标识 */}
{image.fileType && image.fileType !== 'image' && (
<div className={`absolute top-2 right-2 rounded-md px-2 py-1 flex items-center gap-1 shadow-lg ${
image.fileType === 'video' ? 'bg-blue-500 bg-opacity-90' :
image.fileType === 'audio' ? 'bg-pink-500 bg-opacity-90' :
image.fileType === 'document' ? 'bg-green-500 bg-opacity-90' :
image.fileType === 'design' ? 'bg-purple-500 bg-opacity-90' :
'bg-gray-500 bg-opacity-90'
}`}>
{image.fileType === 'video' && <Play className="w-4 h-4 text-white fill-white" />}
{image.fileType === 'audio' && <Music className="w-4 h-4 text-white" />}
{image.fileType === 'document' && <FileText className="w-4 h-4 text-white" />}
{image.fileType === 'design' && <Palette className="w-4 h-4 text-white" />}
{image.fileType === 'other' && <File className="w-4 h-4 text-white" />}
<span className="text-white text-xs font-semibold uppercase">
{image.format || image.filename.split('.').pop()}
</span>
</div>
)}
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all pointer-events-none" />
</div>
<div className="mt-1 px-1 h-4 flex items-center">
{renamingImage?.id === image.id ? (
// 编辑模式
<input
ref={editInputRef}
type="text"
value={editingFilename}
onChange={(e) => onEditingChange(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={onFinishRename}
onClick={(e) => e.stopPropagation()}
className="w-full text-xs text-center bg-transparent border-none outline-none focus:outline-none underline decoration-2 decoration-blue-500 underline-offset-2 truncate leading-none"
style={{
color: isSelected ? '#3b82f6' : '#909090',
fontWeight: isSelected ? '600' : '400',
padding: 0,
margin: 0,
height: '1rem'
}}
/>
) : (
// 显示模式
<p
className="text-xs truncate text-center transition-colors cursor-text m-0 leading-none"
style={{
color: isSelected ? '#3b82f6' : '#909090',
fontWeight: isSelected ? '600' : '400',
height: '1rem'
}}
onDoubleClick={handleDoubleClickFilename}
title="双击重命名"
>
{image.filename}
</p>
)}
</div>
</div>
);
};
export default ImageCell;
File diff suppressed because it is too large. Load diff
-6
View File
@@ -6,7 +6,6 @@ import { useScanStore } from '../stores/useScanStore';
import { imageAPI } from '../api';
import { onUserActionStart, onUserActionEnd } from '../services/imageLoadService';
import requestManager, { RequestType } from '../services/requestManager';
import imageCache from '../utils/imageCache';
import domCleanup from '../utils/domCleanup';
import ImageWaterfall from './ImageWaterfall';
import Dashboard from './Dashboard';
@@ -57,11 +56,6 @@ function MainContent() {
return;
}
// 初始加载时重置本地缓存
if (isInitialLoad) {
imageCache.clear(); // 清理缓存
}
// 暂停空闲加载并取消之前的所有请求(关键!)
onUserActionStart();
cancelCurrentRequest();
+54 -45
View File
@@ -8,6 +8,9 @@ import { useClipboardStore } from '../stores/useClipboardStore';
import { imageAPI, fileAPI } from '../api';
import JSZip from 'jszip';
import RatingStars from './RatingStars';
import { createLogger } from '../utils/logger';
const logger = createLogger('RightPanel');
function RightPanel() {
const { currentLibraryId } = useLibraryStore();
@@ -123,7 +126,7 @@ function RightPanel() {
setPathCopied(true);
setTimeout(() => setPathCopied(false), 2000);
} catch (error) {
console.error('复制路径失败:', error);
logger.error('复制路径失败:', error);
alert('复制失败,请重试');
}
};
@@ -171,9 +174,9 @@ function RightPanel() {
filename: actualNewName
});
console.log(`✅ 重命名成功: ${oldFilename} → ${actualNewName}`);
logger.debug(`✅ 重命名成功: ${oldFilename} → ${actualNewName}`);
} catch (error) {
console.error('重命名失败:', error);
logger.error('重命名失败:', error);
alert('重命名失败: ' + (error.message || '未知错误'));
} finally {
setIsEditingFilename(false);
@@ -227,37 +230,42 @@ function RightPanel() {
const result = await fileAPI.rename(currentLibraryId, oldPath, newName);
const newPath = result.newPath;
console.log(`✅ 文件夹重命名成功: ${oldName} → ${newName}, 路径: ${oldPath} → ${newPath}`);
logger.debug(`✅ 文件夹重命名成功: ${oldName} → ${newName}, 路径: ${oldPath} → ${newPath}`);
const { setFolders, setSelectedFolder: setSelectedFolderGlobal, setSelectedFolderItem } = useImageStore.getState();
// 1. 立即更新选中的文件夹项(乐观更新)
setSelectedFolderItem({
...selectedFolderItem,
path: newPath,
name: newName
});
// 2. 如果重命名的是当前选中的文件夹,立即切换到新路径
// 这样可以避免先显示全部图片的闪烁
if (isRenamingCurrentFolder) {
console.log(`📂 重命名当前文件夹: ${oldPath} → ${newPath}`);
logger.debug(`📂 重命名当前文件夹: ${oldPath} → ${newPath}`);
setSelectedFolderGlobal(newPath);
// 重命名当前浏览的文件夹时,立即刷新该文件夹的图片列表,避免数量显示为 0
imageAPI.search(currentLibraryId, { folder: newPath }).then(response => {
const { setImages, setOriginalImages } = useImageStore.getState();
const imgs = response.images || [];
setImages(imgs);
setOriginalImages(imgs);
}).catch(error => {
logger.warn('重命名后刷新文件夹图片失败:', error);
});
}
// 3. 后台刷新文件夹列表(确保数据一致性)
imageAPI.getFolders(currentLibraryId).then(foldersRes => {
console.log('📁 重命名后最新文件夹列表:', foldersRes.folders);
logger.debug('📁 重命名后最新文件夹列表:', foldersRes.folders);
setFolders(foldersRes.folders);
// 用最新数据更新选中的文件夹项
const newFolderItem = foldersRes.folders.find(f => f.path === newPath);
if (newFolderItem) {
setSelectedFolderItem(newFolderItem);
}
});
} catch (error) {
console.error('文件夹重命名失败:', error);
logger.error('文件夹重命名失败:', error);
alert('重命名失败: ' + (error.message || '未知错误'));
} finally {
setIsEditingFolderName(false);
@@ -311,9 +319,9 @@ function RightPanel() {
setSelectedImages(updatedSelectedImages);
}
console.log(`✅ 已更新 ${paths.length} 张图片的评分为 ${newRating} 星`);
logger.debug(`✅ 已更新 ${paths.length} 张图片的评分为 ${newRating} 星`);
} catch (error) {
console.error('更新评分失败:', error);
logger.error('更新评分失败:', error);
alert('更新评分失败: ' + (error.message || '未知错误'));
} finally {
setIsUpdatingRating(false);
@@ -333,7 +341,8 @@ function RightPanel() {
// 判断是否为可以直接显示原图的格式
const canShowOriginal = (format) => {
if (!format) return false;
const supportedFormats = ['jpg', 'jpeg', 'png', 'webp'];
// 添加 gif 支持,以便显示动画效果
const supportedFormats = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
return supportedFormats.includes(format.toLowerCase());
};
@@ -355,7 +364,7 @@ function RightPanel() {
// 对于不支持的格式,只显示缩略图
if (!shouldLoadOriginal) {
setIsLoadingOriginal(false);
console.log(`格式 ${imageFormat} 不支持直接显示原图,使用缩略图`);
logger.debug(`格式 ${imageFormat} 不支持直接显示原图,使用缩略图`);
return;
}
@@ -379,7 +388,7 @@ function RightPanel() {
img.onerror = () => {
// 原图加载失败,保持显示缩略图
console.error('Failed to load original image');
logger.error('Failed to load original image');
setIsLoadingOriginal(false);
};
@@ -409,7 +418,7 @@ function RightPanel() {
// 支持两种字段名
const thumbnailPath = selectedImage?.thumbnailPath || selectedImage?.thumbnail_path;
if (!thumbnailPath) {
console.warn('缩略图路径不存在:', selectedImage);
logger.warn('缩略图路径不存在:', selectedImage);
return '';
}
// Handle both forward and backslash
@@ -461,7 +470,7 @@ function RightPanel() {
try {
success = document.execCommand('copy');
} catch (err) {
console.error('execCommand copy 失败:', err);
logger.error('execCommand copy 失败:', err);
}
// 清理
@@ -541,7 +550,7 @@ function RightPanel() {
try {
success = document.execCommand('copy');
} catch (err) {
console.error('execCommand copy 失败:', err);
logger.error('execCommand copy 失败:', err);
}
// 清理
@@ -550,7 +559,7 @@ function RightPanel() {
resolve(success);
} catch (err) {
console.error('Canvas 复制失败:', err);
logger.error('Canvas 复制失败:', err);
resolve(false);
}
});
@@ -571,7 +580,7 @@ function RightPanel() {
document.execCommand('copy');
return true;
} catch (err) {
console.error('execCommand 复制失败:', err);
logger.error('execCommand 复制失败:', err);
return false;
} finally {
document.body.removeChild(textArea);
@@ -584,7 +593,7 @@ function RightPanel() {
// 1. 先写入应用内剪贴板(同步,用于应用内粘贴)
const itemsToCopy = [{ type: 'file', path: selectedImage.path, data: selectedImage }];
copyToClipboard(itemsToCopy, 'copy');
console.log(`📋 已复制 1 个文件到应用内剪贴板`);
logger.debug(`📋 已复制 1 个文件到应用内剪贴板`);
// 2. 获取原图URL,写入系统剪贴板
const imageUrl = imageAPI.getOriginalUrl(currentLibraryId, selectedImage.path);
@@ -631,12 +640,12 @@ function RightPanel() {
setTimeout(() => setImageCopied(false), 2000);
return;
} catch (err) {
console.warn('Clipboard API 失败,尝试备用方案:', err);
logger.warn('Clipboard API 失败,尝试备用方案:', err);
}
}
// 方案2:使用 canvas + contenteditable + execCommand(非 HTTPS 环境)
console.log('尝试 Canvas + execCommand 方案...');
logger.debug('尝试 Canvas + execCommand 方案...');
const canvasSuccess = await fallbackCopyImageViaCanvas(imageUrl);
if (canvasSuccess) {
setImageCopied(true);
@@ -645,7 +654,7 @@ function RightPanel() {
}
// 方案3:直接使用图片 URL + contenteditable
console.log('尝试直接图片 URL 方案...');
logger.debug('尝试直接图片 URL 方案...');
const directSuccess = await fallbackCopyImage(imageUrl);
if (directSuccess) {
setImageCopied(true);
@@ -654,7 +663,7 @@ function RightPanel() {
}
// 方案4:最后降级为复制链接
console.warn('所有图片复制方案失败,降级为复制链接');
logger.warn('所有图片复制方案失败,降级为复制链接');
const textSuccess = fallbackCopyText(imageUrl);
if (textSuccess) {
setImageCopied(true);
@@ -716,7 +725,7 @@ function RightPanel() {
copyImg.style.marginBottom = '10px';
container.appendChild(copyImg);
} catch (err) {
console.error(`加载图片失败: ${filename}`, err);
logger.error(`加载图片失败: ${filename}`, err);
}
}
@@ -734,7 +743,7 @@ function RightPanel() {
try {
success = document.execCommand('copy');
} catch (err) {
console.error('execCommand copy 失败:', err);
logger.error('execCommand copy 失败:', err);
}
// 清理
@@ -743,7 +752,7 @@ function RightPanel() {
resolve(success);
} catch (err) {
console.error('批量复制图片失败:', err);
logger.error('批量复制图片失败:', err);
resolve(false);
}
});
@@ -769,7 +778,7 @@ function RightPanel() {
// 1. 先写入应用内剪贴板(同步,用于应用内粘贴)
const itemsToCopy = imagesToCopy.map(img => ({ type: 'file', path: img.path, data: img }));
copyToClipboard(itemsToCopy, 'copy');
console.log(`📋 已复制 ${itemsToCopy.length} 个文件到应用内剪贴板`);
logger.debug(`📋 已复制 ${itemsToCopy.length} 个文件到应用内剪贴板`);
if (imagesToCopy.length === 1) {
// 单张图片:直接复制
@@ -823,12 +832,12 @@ function RightPanel() {
setTimeout(() => setImageCopied(false), 2000);
return;
} catch (err) {
console.warn('Clipboard API 失败,尝试备用方案:', err);
logger.warn('Clipboard API 失败,尝试备用方案:', err);
}
}
// 方案2:使用 contenteditable + execCommand
console.log('尝试 contenteditable 批量复制方案...');
logger.debug('尝试 contenteditable 批量复制方案...');
const success = await fallbackCopyMultipleImages(imageUrls);
if (success) {
setImageCopied(true);
@@ -837,7 +846,7 @@ function RightPanel() {
}
// 方案3:降级为复制文件名列表
console.warn('批量图片复制失败,降级为复制文件名');
logger.warn('批量图片复制失败,降级为复制文件名');
const textSuccess = fallbackCopyText(textContent);
if (textSuccess) {
setImageCopied(true);
@@ -892,15 +901,15 @@ function RightPanel() {
const progress = Math.round(((i + 1) / imagesToExport.length) * 90); // 90% 用于下载
setExportProgress(progress);
console.log(`已添加: ${img.filename} (${i + 1}/${imagesToExport.length})`);
logger.debug(`已添加: ${img.filename} (${i + 1}/${imagesToExport.length})`);
} catch (error) {
console.error(`下载失败: ${img.filename}`, error);
logger.error(`下载失败: ${img.filename}`, error);
}
}
// 生成 ZIP 文件
setExportProgress(95);
console.log('正在生成 ZIP 文件...');
logger.debug('正在生成 ZIP 文件...');
const zipBlob = await zip.generateAsync({
type: 'blob',
compression: 'DEFLATE',
@@ -917,10 +926,10 @@ function RightPanel() {
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
console.log('导出完成!');
logger.debug('导出完成!');
}
} catch (error) {
console.error('导出失败:', error);
logger.error('导出失败:', error);
alert('导出失败,请重试');
} finally {
setIsExporting(false);
@@ -973,15 +982,15 @@ function RightPanel() {
const progress = Math.round(((i + 1) / folderImages.length) * 90);
setFolderExportProgress(progress);
console.log(`已添加: ${filePath} (${i + 1}/${folderImages.length})`);
logger.debug(`已添加: ${filePath} (${i + 1}/${folderImages.length})`);
} catch (error) {
console.error(`下载失败: ${img.filename}`, error);
logger.error(`下载失败: ${img.filename}`, error);
}
}
// 生成 ZIP 文件
setFolderExportProgress(95);
console.log('正在生成 ZIP 文件...');
logger.debug('正在生成 ZIP 文件...');
const zipBlob = await zip.generateAsync({
type: 'blob',
compression: 'DEFLATE',
@@ -998,9 +1007,9 @@ function RightPanel() {
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
console.log('文件夹导出完成!');
logger.debug('文件夹导出完成!');
} catch (error) {
console.error('导出文件夹失败:', error);
logger.error('导出文件夹失败:', error);
alert('导出文件夹失败,请重试');
} finally {
setIsExportingFolder(false);
@@ -1312,7 +1321,7 @@ function RightPanel() {
isLoadingOriginal ? 'opacity-75' : 'opacity-100'
}`}
onError={(e) => {
console.error('图片加载失败:', imageUrl);
logger.error('图片加载失败:', imageUrl);
e.target.style.display = 'none';
}}
/>
+323 -98
View File
@@ -10,6 +10,10 @@ import LibraryMissingModal from './LibraryMissingModal';
import ContextMenu, { menuItems } from './ContextMenu';
import UndoToast from './UndoToast';
import FolderSelector from './FolderSelector';
import ConflictDialog from './ConflictDialog';
import { createLogger } from '../utils/logger';
const logger = createLogger('Sidebar');
// 检查素材库扫描状态
const checkScanStatus = async (libraryId) => {
@@ -56,6 +60,8 @@ function Sidebar() {
const [editingFolderName, setEditingFolderName] = useState(''); // 编辑中的文件夹名
const [creatingFolder, setCreatingFolder] = useState(null); // 正在创建的文件夹 { type: 'sibling' | 'child', parentPath: string }
const [newFolderName, setNewFolderName] = useState(''); // 新建文件夹名称
const [conflictDialog, setConflictDialog] = useState({ isOpen: false, conflicts: [], pendingMove: null }); // 冲突对话框
const [dragMoveHistory, setDragMoveHistory] = useState([]); // 拖拽移动历史栈
const folderSearchDebounceRef = useRef(null);
const librarySelectorRef = useRef(null);
const folderNameInputRef = useRef(null);
@@ -187,7 +193,7 @@ function Sidebar() {
return parentPath || null;
}, []);
// 监听快捷键(Del删除、F2重命名、Ctrl+Z撤销)
// 监听快捷键(Del删除、F2重命名、Ctrl+Z撤销文件夹)
useEffect(() => {
const handleKeyDown = async (e) => {
// 忽略输入框中的快捷键
@@ -237,20 +243,31 @@ function Sidebar() {
}
}
// Ctrl+Z → 撤销(文件夹或图片)
// Ctrl+Z → 撤销文件夹相关操作(拖拽移动 / 删除)
if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
// 如果有文件夹撤销历史,撤销文件夹
const { selectedImages, selectedImage } = useImageStore.getState();
// 有图片撤销栈时,让 ImageWaterfall 处理图片撤销
if (selectedImages.length > 0 || selectedImage) return;
// 1. 优先撤销拖拽移动
if (dragMoveHistory.length > 0) {
e.preventDefault();
await handleUndoDragMove();
return;
}
// 2. 没有拖拽记录时,再撤销文件夹删除
if (undoHistory.length > 0) {
e.preventDefault();
await handleUndoFolderDelete();
return;
}
// 否则让 ImageWaterfall 处理图片撤销
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [selectedFolder, undoHistory, folders, findNextFolderAfterDelete]);
}, [selectedFolder, undoHistory, dragMoveHistory, folders, findNextFolderAfterDelete]);
// 文件夹删除功能(乐观更新,立即响应)
const handleDeleteFolder = async (folderPath) => {
@@ -287,7 +304,7 @@ function Sidebar() {
]).then(([deleteResult, foldersRes]) => {
const { setFolders } = useImageStore.getState();
if (deleteResult.failed.length > 0) {
console.warn(`⚠️ 删除失败:`, deleteResult.failed);
logger.warn(`⚠️ 删除失败:`, deleteResult.failed);
// 失败时回滚
setUndoHistory(undoHistory);
setUndoToast({ isVisible: false, message: '', count: 0 });
@@ -298,7 +315,7 @@ function Sidebar() {
setFolders(foldersRes.folders);
}
}).catch(error => {
console.error('删除文件夹失败:', error);
logger.error('删除文件夹失败:', error);
// 失败时回滚
setUndoHistory(undoHistory);
setUndoToast({ isVisible: false, message: '', count: 0 });
@@ -342,7 +359,7 @@ function Sidebar() {
// 4. 立即跳转到恢复的文件夹
setSelectedFolder(lastDeleted.folderPath);
console.log(`📂 跳转到文件夹: ${lastDeleted.folderPath}`);
logger.debug(`📂 跳转到文件夹: ${lastDeleted.folderPath}`);
// 5. 后台执行API调用(不阻塞UI)
Promise.all([
@@ -352,7 +369,7 @@ function Sidebar() {
const { setFolders } = useImageStore.getState();
// 检查恢复结果
if (restoreResult.failed.length > 0) {
console.warn(`⚠️ 恢复失败: ${restoreResult.failed.length} 个文件`);
logger.warn(`⚠️ 恢复失败: ${restoreResult.failed.length} 个文件`);
const errorMsg = restoreResult.failed[0].error || '未知错误';
// 失败时回滚
@@ -364,7 +381,7 @@ function Sidebar() {
setFolders(foldersRes.folders);
}
}).catch(error => {
console.error('撤销失败:', error);
logger.error('撤销失败:', error);
// 失败时回滚
setUndoHistory(undoHistory);
imageAPI.getFolders(currentLibraryId).then(foldersRes => {
@@ -375,6 +392,123 @@ function Sidebar() {
});
};
// 检查拖拽移动冲突
const checkDragMoveConflicts = async (items, targetFolderPath) => {
if (!currentLibraryId) return [];
try {
// 获取目标文件夹的文件列表
const response = await imageAPI.search(currentLibraryId, { folder: targetFolderPath });
const targetFolderImages = response.images || [];
const conflicts = [];
for (const item of items) {
const fileName = item.path.split('/').pop();
const itemFolder = item.path.substring(0, item.path.lastIndexOf('/'));
// 检查是否存在同名文件
const exists = targetFolderImages.some(img => img.filename === fileName);
if (exists) {
conflicts.push({
path: item.path,
name: fileName,
isSameLocation: itemFolder === targetFolderPath
});
}
}
return conflicts;
} catch (error) {
logger.error('检查拖拽移动冲突失败:', error);
return [];
}
};
// 执行拖拽移动(带冲突操作)
const executeDragMove = async (items, targetFolderPath, conflictAction = 'rename') => {
if (!currentLibraryId) return;
try {
// 检查是否包含文件夹
const hasFolders = items.some(item => item.type === 'folder');
// 保存移动前的信息(用于撤销)
const { images, clearSelection } = useImageStore.getState();
const sourceFolders = new Map();
const movedImages = [];
if (!hasFolders) {
items.forEach(item => {
const img = images.find(i => i.path === item.path);
if (img) {
sourceFolders.set(item.path, img.folder);
movedImages.push(img);
}
});
}
// 1. 如果是移动文件,立即从UI中移除(乐观更新)并清空选中状态
if (!hasFolders) {
const { setImages } = useImageStore.getState();
const movedPaths = new Set(items.map(item => item.path));
const remainingImages = images.filter(img => !movedPaths.has(img.path));
setImages(remainingImages);
// 关键:拖拽移动后清空图片选中,避免 Ctrl+Z 时仍被视为“有图片选中”而拦截文件夹级撤销
clearSelection();
}
// 2. 执行移动(带冲突操作)
const result = await fileAPI.move(currentLibraryId, items, targetFolderPath, conflictAction);
if (result.failed && result.failed.length > 0) {
alert(`移动失败: ${result.failed[0].error}`);
} else {
const successCount = result.success?.length || 0;
// 移动成功,保存到历史栈(用于撤销)
if (successCount > 0 && !hasFolders) {
const newHistory = [...dragMoveHistory, {
items,
targetFolder: targetFolderPath,
sourceFolders: Array.from(sourceFolders.entries()),
images: movedImages
}];
setDragMoveHistory(newHistory);
// 显示撤销提示
setUndoToast({
isVisible: true,
message: `已移动 ${successCount} 个文件`,
count: successCount
});
// 3秒后自动隐藏
setTimeout(() => {
setUndoToast({ isVisible: false, message: '', count: 0 });
}, 3000);
}
logger.debug(`✅ 已移动 ${items.length} 个${hasFolders ? '文件夹' : '文件'}到: ${targetFolderPath}`);
}
// 3. 刷新文件夹列表
const foldersRes = await imageAPI.getFolders(currentLibraryId);
const { setFolders, setImages } = useImageStore.getState();
setFolders(foldersRes.folders);
// 4. 刷新当前文件夹的图片列表(无论是源还是目标)
if (selectedFolder) {
const params = { folder: selectedFolder };
const response = await imageAPI.search(currentLibraryId, params);
setImages(response.images);
}
} catch (error) {
logger.error('拖拽移动失败:', error);
alert('移动失败: ' + (error.message || '未知错误'));
}
};
// 处理拖拽到文件夹
const handleDrop = async (e, targetFolder) => {
e.preventDefault();
@@ -389,34 +523,22 @@ function Sidebar() {
if (!items || items.length === 0) return;
// 检查是否包含文件夹
const hasFolders = items.some(item => item.type === 'folder');
// 检查冲突
const conflicts = await checkDragMoveConflicts(items, targetFolder.path);
// 1. 如果是移动文件,立即从UI中移除(乐观更新)
if (!hasFolders) {
const { images, setImages } = useImageStore.getState();
const movedPaths = new Set(items.map(item => item.path));
const remainingImages = images.filter(img => !movedPaths.has(img.path));
setImages(remainingImages);
}
// 2. 执行移动和刷新(并行)
const [result, foldersRes] = await Promise.all([
fileAPI.move(currentLibraryId, items, targetFolder.path),
imageAPI.getFolders(currentLibraryId)
]);
if (result.failed && result.failed.length > 0) {
alert(`移动失败: ${result.failed[0].error}`);
if (conflicts.length > 0) {
// 有冲突,显示对话框
setConflictDialog({
isOpen: true,
conflicts,
pendingMove: { items, targetFolder: targetFolder.path }
});
} else {
console.log(`✅ 已移动 ${items.length} 个${hasFolders ? '文件夹' : '文件'}到: ${targetFolder.path}`);
// 无冲突,直接执行移动
await executeDragMove(items, targetFolder.path, 'rename');
}
// 3. 刷新文件夹列表
const { setFolders } = useImageStore.getState();
setFolders(foldersRes.folders);
} catch (error) {
console.error('拖拽移动失败:', error);
logger.error('拖拽移动失败:', error);
}
};
@@ -432,6 +554,117 @@ function Sidebar() {
setDragOverFolder(null);
};
// 处理冲突解决
const handleConflictResolve = async (action) => {
const { pendingMove } = conflictDialog;
// 关闭对话框
setConflictDialog({ isOpen: false, conflicts: [], pendingMove: null });
if (pendingMove) {
// 执行移动操作
await executeDragMove(pendingMove.items, pendingMove.targetFolder, action);
}
};
// 取消冲突对话框
const handleConflictCancel = () => {
setConflictDialog({ isOpen: false, conflicts: [], pendingMove: null });
};
// 撤销拖拽移动
const handleUndoDragMove = async () => {
if (dragMoveHistory.length === 0) return;
// 从历史栈中取出最近的移动记录
const lastMove = dragMoveHistory[dragMoveHistory.length - 1];
const remainingHistory = dragMoveHistory.slice(0, -1);
// 立即关闭Toast
setUndoToast({ isVisible: false, message: '', count: 0 });
// 立即更新历史栈
setDragMoveHistory(remainingHistory);
// 构造撤销移动项
const undoItems = [];
const sourceMap = new Map(lastMove.sourceFolders);
for (const item of lastMove.items) {
const sourceFolder = sourceMap.get(item.path);
if (sourceFolder !== undefined) {
undoItems.push({
...item,
sourceFolder
});
}
}
if (undoItems.length === 0) return;
// 按原文件夹分组
const groupedBySource = new Map();
for (const item of undoItems) {
const source = item.sourceFolder;
if (!groupedBySource.has(source)) {
groupedBySource.set(source, []);
}
groupedBySource.get(source).push({
type: item.type,
path: item.path.split('/').pop()
});
}
// 获取主要的源文件夹(大多数文件的源文件夹)
let primarySourceFolder = null;
if (groupedBySource.size > 0) {
let maxCount = 0;
for (const [folder, items] of groupedBySource.entries()) {
if (items.length > maxCount) {
maxCount = items.length;
primarySourceFolder = folder;
}
}
}
// 自动切换到主要源文件夹
if (primarySourceFolder && selectedFolder !== primarySourceFolder) {
setSelectedFolder(primarySourceFolder);
}
// 后台执行撤销移动
try {
await Promise.all(
Array.from(groupedBySource.entries()).map(([sourceFolder, items]) => {
const fullPathItems = items.map(item => ({
type: item.type,
path: `${lastMove.targetFolder}/${item.path}`
}));
return fileAPI.move(currentLibraryId, fullPathItems, sourceFolder, 'rename');
})
);
// 刷新文件夹列表
const foldersRes = await imageAPI.getFolders(currentLibraryId);
const { setFolders, setImages } = useImageStore.getState();
setFolders(foldersRes.folders);
// 刷新当前文件夹的图片列表(现在应该是源文件夹之一)
if (selectedFolder) {
const params = { folder: selectedFolder };
const response = await imageAPI.search(currentLibraryId, params);
setImages(response.images);
}
logger.debug(`✅ 撤销拖拽移动完成`);
} catch (error) {
logger.error('撤销拖拽移动失败:', error);
// 失败时回滚
setDragMoveHistory(dragMoveHistory);
alert('撤销移动失败: ' + (error.message || '未知错误'));
}
};
// 打开文件夹移动选择器
const handleMoveFolderClick = (folderPath) => {
setMoveFolderPath(folderPath);
@@ -463,14 +696,14 @@ function Sidebar() {
} else {
// 2. 移动成功,选中新位置
setSelectedFolder(newPath);
console.log(`✅ 已移动文件夹: ${moveFolderPath} -> ${newPath}`);
logger.debug(`✅ 已移动文件夹: ${moveFolderPath} -> ${newPath}`);
}
// 3. 刷新文件夹列表
const { setFolders } = useImageStore.getState();
setFolders(foldersRes.folders);
} catch (error) {
console.error('移动文件夹失败:', error);
logger.error('移动文件夹失败:', error);
alert('移动失败: ' + (error.message || '未知错误'));
// 失败时重新加载文件夹列表
@@ -525,24 +758,40 @@ function Sidebar() {
const result = await fileAPI.rename(currentLibraryId, oldPath, newName);
const newPath = result.newPath;
console.log(`✅ 文件夹重命名成功: ${oldName} → ${newName}, 路径: ${oldPath} → ${newPath}`);
logger.debug(`✅ 文件夹重命名成功: ${oldName} → ${newName}, 路径: ${oldPath} → ${newPath}`);
const { setFolders, setSelectedFolder: setSelectedFolderGlobal } = useImageStore.getState();
const { setFolders, setSelectedFolder: setSelectedFolderGlobal, setSelectedFolderItem } = useImageStore.getState();
// 1. 如果重命名的是当前选中的文件夹,立即切换到新路径
// 这样可以避免先显示全部图片的闪烁
if (isRenamingCurrentFolder) {
console.log(`📂 重命名当前文件夹: ${oldPath} → ${newPath}`);
logger.debug(`📂 重命名当前文件夹: ${oldPath} → ${newPath}`);
setSelectedFolderGlobal(newPath);
// 重命名当前浏览的文件夹时,立即刷新该文件夹的图片列表,避免连续重命名导致数量显示为 0
imageAPI.search(currentLibraryId, { folder: newPath }).then(response => {
const { setImages, setOriginalImages } = useImageStore.getState();
const imgs = response.images || [];
setImages(imgs);
setOriginalImages(imgs);
}).catch(error => {
logger.warn('重命名后刷新文件夹图片失败:', error);
});
}
// 2. 后台刷新文件夹列表(不阻塞UI)
imageAPI.getFolders(currentLibraryId).then(foldersRes => {
console.log('📁 重命名后最新文件夹列表:', foldersRes.folders);
logger.debug('📁 重命名后最新文件夹列表:', foldersRes.folders);
setFolders(foldersRes.folders);
// 3. 用最新数据更新 selectedFolderItem,让右侧详情面板立即显示新名称
const newFolderItem = foldersRes.folders.find(f => f.path === newPath);
if (newFolderItem) {
setSelectedFolderItem(newFolderItem);
}
});
} catch (error) {
console.error('文件夹重命名失败:', error);
logger.error('文件夹重命名失败:', error);
alert('重命名失败: ' + (error.message || '未知错误'));
} finally {
setRenamingFolder(null);
@@ -560,14 +809,14 @@ function Sidebar() {
const handleStartCreateFolder = (type, basePath) => {
// type: 'sibling' 同级 | 'child' 子级
// basePath: 基准文件夹路径
const parentPath = type === 'sibling'
const parentPath = type === 'sibling'
? (basePath.includes('/') ? basePath.substring(0, basePath.lastIndexOf('/')) : '')
: basePath;
setCreatingFolder({ type, parentPath, basePath });
setNewFolderName('新建文件夹');
setContextMenu({ isOpen: false, position: null, folder: null });
// 延迟聚焦
setTimeout(() => {
if (newFolderInputRef.current) {
@@ -577,48 +826,6 @@ function Sidebar() {
}, 50);
};
// 完成创建文件夹
const handleFinishCreateFolder = async () => {
if (!creatingFolder || !newFolderName.trim()) {
setCreatingFolder(null);
setNewFolderName('');
return;
}
const folderName = newFolderName.trim();
const { parentPath } = creatingFolder;
const newFolderPath = parentPath ? `${parentPath}/${folderName}` : folderName;
try {
// 调用后端 API 创建文件夹
await fileAPI.createFolder(currentLibraryId, newFolderPath);
console.log(`✅ 文件夹创建成功: ${newFolderPath}`);
// 刷新文件夹列表
const foldersRes = await imageAPI.getFolders(currentLibraryId);
const { setFolders } = useImageStore.getState();
setFolders(foldersRes.folders);
// 展开父文件夹
if (parentPath) {
setExpandedFolders(prev => new Set([...prev, parentPath]));
}
} catch (error) {
console.error('创建文件夹失败:', error);
alert('创建文件夹失败: ' + (error.message || '未知错误'));
} finally {
setCreatingFolder(null);
setNewFolderName('');
}
};
// 取消创建文件夹
const handleCancelCreateFolder = () => {
setCreatingFolder(null);
setNewFolderName('');
};
const handleAddLibrary = async () => {
// 扫描期间禁止添加素材库
if (isScanning()) {
@@ -640,7 +847,7 @@ function Sidebar() {
try {
// 1. 添加素材库
console.log('📝 添加素材库...');
logger.debug('📝 添加素材库...');
const response = await libraryAPI.add(newLibraryName.trim(), newLibraryPath.trim());
const newLibId = response.id;
const hasExistingIndex = response.hasExistingIndex;
@@ -658,7 +865,7 @@ function Sidebar() {
setIsAdding(false); // 立即释放按钮
// 3. 切换到新素材库
console.log('🔄 切换到新素材库...');
logger.debug('🔄 切换到新素材库...');
await libraryAPI.setCurrent(newLibId);
setCurrentLibrary(newLibId);
setSelectedFolder(null);
@@ -680,7 +887,7 @@ function Sidebar() {
// 6. 如果有已有索引,先快速加载数据库中的数据
if (hasExistingIndex) {
console.log('检测到已有索引,先加载现有数据...');
logger.debug('检测到已有索引,先加载现有数据...');
try {
const [foldersRes, countRes] = await Promise.all([
imageAPI.getFolders(newLibId),
@@ -688,27 +895,27 @@ function Sidebar() {
]);
useImageStore.getState().setFolders(foldersRes.folders);
useImageStore.getState().setTotalImageCount(countRes.count);
console.log('✅ 已加载现有数据');
logger.debug('✅ 已加载现有数据');
} catch (err) {
console.warn('⚠️ 加载现有数据失败:', err);
logger.warn('⚠️ 加载现有数据失败:', err);
}
}
// 7. 开始异步扫描(不等待,Socket.IO 会推送进度)
console.log('🔍 开始异步扫描...');
logger.debug('🔍 开始异步扫描...');
if (hasExistingIndex) {
console.log('执行增量同步,检测变化...');
logger.debug('执行增量同步,检测变化...');
scanAPI.sync(newLibId, false); // wait=false,异步执行
} else {
console.log('首次添加,执行全量扫描...');
logger.debug('首次添加,执行全量扫描...');
scanAPI.fullScan(newLibId, false); // wait=false,异步执行
}
// 扫描在后台进行,Socket.IO 会推送进度和完成事件
// App.jsx 中的 scanComplete 监听器会自动刷新数据
console.log('✅ 扫描已启动,请等待进度显示...');
logger.debug('✅ 扫描已启动,请等待进度显示...');
} catch (error) {
console.error('❌ Error adding library:', error);
logger.error('❌ Error adding library:', error);
// 提取错误信息
let errorMessage = error.message || '未知错误';
@@ -801,7 +1008,7 @@ function Sidebar() {
}
}).catch(() => { });
} catch (error) {
console.error('Error setting current library:', error);
logger.error('Error setting current library:', error);
alert('切换素材库失败: ' + error.message);
useImageStore.getState().setImageLoadingState({ isLoading: false });
} finally {
@@ -1449,7 +1656,7 @@ function Sidebar() {
{/* 撤销删除提示 */}
<UndoToast
isVisible={undoToast.isVisible}
isVisible={undoToast.isVisible && dragMoveHistory.length === 0}
message={undoToast.message}
onUndo={handleUndoFolderDelete}
onClose={() => {
@@ -1458,6 +1665,16 @@ function Sidebar() {
}}
/>
{/* 撤销拖拽移动提示 */}
<UndoToast
isVisible={undoToast.isVisible && dragMoveHistory.length > 0}
message={undoToast.message}
onUndo={handleUndoDragMove}
onClose={() => {
setUndoToast({ isVisible: false, message: '', count: 0 });
}}
/>
{/* 文件夹选择器 */}
{showFolderSelector && (
<FolderSelector
@@ -1470,6 +1687,14 @@ function Sidebar() {
}}
/>
)}
{/* 冲突处理对话框 */}
<ConflictDialog
isOpen={conflictDialog.isOpen}
conflicts={conflictDialog.conflicts}
onResolve={handleConflictResolve}
onCancel={handleConflictCancel}
/>
</div>
);
}
@@ -0,0 +1,33 @@
/**
* 上传进度提示组件
*/
const UploadProgress = ({ progress }) => {
const { isUploading, percent, total } = progress;
if (!isUploading) return null;
return (
<div className="absolute top-4 right-4 z-40 bg-white dark:bg-gray-800 rounded-lg shadow-xl p-4 min-w-[300px]">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
正在上传...
</span>
<span className="text-sm text-gray-500 dark:text-gray-400">
{percent}%
</span>
</div>
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
<div
className="bg-blue-500 h-2 rounded-full transition-all duration-300"
style={{ width: `${percent}%` }}
/>
</div>
<div className="mt-2 text-xs text-gray-500 dark:text-gray-400 text-right">
共 {total} 个文件
</div>
</div>
);
};
export default UploadProgress;