diff --git a/backend/database/db.js b/backend/database/db.js
index f347071..caffb0d 100644
--- a/backend/database/db.js
+++ b/backend/database/db.js
@@ -1,6 +1,7 @@
const Database = require('better-sqlite3');
const path = require('path');
const fs = require('fs');
+const { constants } = require('../src/config');
class LibraryDatabase {
constructor(libraryPath) {
@@ -28,14 +29,15 @@ class LibraryDatabase {
this.initTables();
- // 启动 WAL 定期 checkpoint(每 5 分钟)
+ // 启动 WAL 定期 checkpoint(使用配置的间隔)
+ const checkpointInterval = constants.MEMORY.WAL_CHECKPOINT_INTERVAL_MS || 600000;
this.walCheckpointInterval = setInterval(() => {
try {
this.db.pragma('wal_checkpoint(PASSIVE)');
} catch (e) {
console.warn('[DB] WAL checkpoint warning:', e.message);
}
- }, 300000); // 5 分钟
+ }, checkpointInterval); // 10分钟(降低I/O开销,不影响性能)
}
initTables() {
diff --git a/backend/src/config/constants.js b/backend/src/config/constants.js
index 1325a97..7ea584d 100644
--- a/backend/src/config/constants.js
+++ b/backend/src/config/constants.js
@@ -42,7 +42,8 @@ module.exports = {
CACHE_SIZE_KB: 4096,
CLEANUP_INTERVAL_MS: 60000, // 清理间隔:1分钟
DB_IDLE_TIMEOUT_MS: 60000, // 数据库空闲超时:60秒
- DB_CLEANUP_CHECK_INTERVAL: 10000 // 数据库清理检查间隔:10秒
+ DB_CLEANUP_CHECK_INTERVAL: 10000, // 数据库清理检查间隔:10秒(已优化)
+ WAL_CHECKPOINT_INTERVAL_MS: 600000 // WAL checkpoint间隔:10分钟(降低I/O开销)
},
// 数据库配置
diff --git a/backend/src/routes/file.js b/backend/src/routes/file.js
index ee6e3cb..0f9e1d3 100644
--- a/backend/src/routes/file.js
+++ b/backend/src/routes/file.js
@@ -66,10 +66,10 @@ router.patch('/rename', asyncHandler(async (req, res) => {
/**
* 移动文件或文件夹
* POST /api/file/move
- * Body: { libraryId, items: [{type, path}], targetFolder }
+ * Body: { libraryId, items: [{type, path}], targetFolder, conflictAction?: 'skip'|'replace'|'rename' }
*/
router.post('/move', asyncHandler(async (req, res) => {
- const { libraryId, items, targetFolder } = req.body;
+ const { libraryId, items, targetFolder, conflictAction } = req.body;
if (!libraryId || !items || !Array.isArray(items) || targetFolder === undefined) {
return res.status(400).json({
@@ -78,7 +78,7 @@ router.post('/move', asyncHandler(async (req, res) => {
});
}
- const results = await fileService.moveItems(libraryId, items, targetFolder);
+ const results = await fileService.moveItems(libraryId, items, targetFolder, conflictAction);
res.json({
success: true,
diff --git a/backend/src/services/FileService.js b/backend/src/services/FileService.js
index 5984f49..d039780 100644
--- a/backend/src/services/FileService.js
+++ b/backend/src/services/FileService.js
@@ -556,11 +556,12 @@ class FileService {
* @param {string} libraryId - 素材库ID
* @param {Array} items - 待移动项
* @param {string} targetFolder - 目标文件夹(相对路径)
+ * @param {string} conflictAction - 冲突处理方式: 'skip'|'replace'|'rename'
*/
- async moveItems(libraryId, items, targetFolder) {
+ async moveItems(libraryId, items, targetFolder, conflictAction = 'rename') {
const db = this._getDatabase(libraryId);
const libraryPath = db.libraryPath;
- const results = { success: [], failed: [] };
+ const results = { success: [], failed: [], conflicts: [] };
for (const item of items) {
try {
@@ -570,12 +571,12 @@ class FileService {
const normalizedTarget = targetFolder ? targetFolder.replace(/\\/g, '/') : '';
// 目标文件夹相对路径
- const newRelativeFolder = normalizedTarget
+ let newRelativeFolder = normalizedTarget
? `${normalizedTarget}/${fileName}`
: fileName;
const oldFullPath = path.join(libraryPath, oldPath);
- const newFullPath = path.join(libraryPath, newRelativeFolder);
+ let newFullPath = path.join(libraryPath, newRelativeFolder);
// 检查源路径是否存在
if (!fs.existsSync(oldFullPath)) {
@@ -591,10 +592,53 @@ class FileService {
fs.mkdirSync(targetFullPath, { recursive: true });
}
- // 检查目标是否已存在同名文件/文件夹
+ // 处理冲突
+ const isDirectory = item.type === 'folder';
+
if (fs.existsSync(newFullPath)) {
- results.failed.push({ path: oldPath, error: '目标位置已存在同名文件' });
- continue;
+ // 目标位置已存在同名文件/文件夹
+ results.conflicts.push({ path: oldPath, name: fileName });
+
+ if (conflictAction === 'skip') {
+ // 跳过冲突文件
+ console.log(`⏭️ 跳过冲突: ${fileName}`);
+ continue;
+ } else if (conflictAction === 'replace') {
+ // 覆盖:先删除目标文件/文件夹
+ console.log(`🔄 覆盖: ${fileName}`);
+ if (fs.statSync(newFullPath).isDirectory()) {
+ // 删除目标物理目录
+ fs.rmSync(newFullPath, { recursive: true, force: true });
+ // 同时删除数据库中目标路径下的记录,避免后续路径更新时触发 UNIQUE(path) 冲突
+ const normalizedTargetFolder = newRelativeFolder.replace(/\\/g, '/');
+ db.deleteImagesByFolderPrefix(normalizedTargetFolder);
+ db.deleteFoldersByPrefix(normalizedTargetFolder);
+ } else {
+ // 删除目标物理文件
+ fs.unlinkSync(newFullPath);
+ // 删除数据库中该文件的记录,避免 _updatePathInDatabase 更新到已存在路径时报 UNIQUE 约束错误
+ const normalizedTargetPath = newRelativeFolder.replace(/\\/g, '/');
+ db.deleteImage(normalizedTargetPath);
+ }
+ // 继续执行移动
+ } else if (conflictAction === 'rename') {
+ // 重命名:自动编号
+ const ext = isDirectory ? '' : path.extname(fileName);
+ const basename = isDirectory ? fileName : path.basename(fileName, ext);
+ let counter = 1;
+
+ while (fs.existsSync(newFullPath)) {
+ const numberedName = isDirectory
+ ? `${basename} (${counter})`
+ : `${basename} (${counter})${ext}`;
+ newRelativeFolder = normalizedTarget
+ ? `${normalizedTarget}/${numberedName}`
+ : numberedName;
+ newFullPath = path.join(libraryPath, newRelativeFolder);
+ counter++;
+ }
+ console.log(`✏️ 重命名为: ${path.basename(newFullPath)}`);
+ }
}
if (item.type === 'folder') {
diff --git a/backend/utils/memoryDiagnostics.js b/backend/utils/memoryDiagnostics.js
deleted file mode 100644
index b6b7280..0000000
--- a/backend/utils/memoryDiagnostics.js
+++ /dev/null
@@ -1,176 +0,0 @@
-/**
- * Memory Diagnostics Tool
- * 诊断内存泄漏和高内存使用
- */
-
-const v8 = require('v8');
-const fs = require('fs');
-const path = require('path');
-
-/**
- * 生成堆快照
- */
-function takeHeapSnapshot(filename) {
- const snapshotPath = path.join(__dirname, '..', 'logs', filename);
-
- // 确保目录存在
- const dir = path.dirname(snapshotPath);
- if (!fs.existsSync(dir)) {
- fs.mkdirSync(dir, { recursive: true });
- }
-
- const snapshot = v8.writeHeapSnapshot(snapshotPath);
- console.log(`[MemoryDiagnostics] Heap snapshot saved: ${snapshot}`);
- return snapshot;
-}
-
-/**
- * 获取堆统计信息
- */
-function getHeapStatistics() {
- const stats = v8.getHeapStatistics();
- return {
- totalHeapSize: (stats.total_heap_size / 1024 / 1024).toFixed(2) + ' MB',
- totalHeapSizeExecutable: (stats.total_heap_size_executable / 1024 / 1024).toFixed(2) + ' MB',
- totalPhysicalSize: (stats.total_physical_size / 1024 / 1024).toFixed(2) + ' MB',
- totalAvailableSize: (stats.total_available_size / 1024 / 1024).toFixed(2) + ' MB',
- usedHeapSize: (stats.used_heap_size / 1024 / 1024).toFixed(2) + ' MB',
- heapSizeLimit: (stats.heap_size_limit / 1024 / 1024).toFixed(2) + ' MB',
- mallocedMemory: (stats.malloced_memory / 1024 / 1024).toFixed(2) + ' MB',
- peakMallocedMemory: (stats.peak_malloced_memory / 1024 / 1024).toFixed(2) + ' MB',
- doesZapGarbage: stats.does_zap_garbage
- };
-}
-
-/**
- * 打印堆统计信息
- */
-function logHeapStatistics() {
- const stats = getHeapStatistics();
- console.log('\n[MemoryDiagnostics] Heap Statistics:');
- Object.entries(stats).forEach(([key, value]) => {
- console.log(` ${key}: ${value}`);
- });
-}
-
-/**
- * 强制垃圾回收并报告
- */
-function forceGCAndReport() {
- if (!global.gc) {
- console.warn('[MemoryDiagnostics] GC not available. Run with --expose-gc');
- return null;
- }
-
- const before = process.memoryUsage();
- const beforeRSS = before.rss / 1024 / 1024;
- const beforeHeap = before.heapUsed / 1024 / 1024;
-
- console.log(`[MemoryDiagnostics] Before GC: RSS=${beforeRSS.toFixed(0)}MB, Heap=${beforeHeap.toFixed(0)}MB`);
-
- // 执行多次 GC
- for (let i = 0; i < 5; i++) {
- global.gc();
- }
-
- const after = process.memoryUsage();
- const afterRSS = after.rss / 1024 / 1024;
- const afterHeap = after.heapUsed / 1024 / 1024;
-
- const rssReclaimed = beforeRSS - afterRSS;
- const heapReclaimed = beforeHeap - afterHeap;
-
- console.log(`[MemoryDiagnostics] After GC: RSS=${afterRSS.toFixed(0)}MB, Heap=${afterHeap.toFixed(0)}MB`);
- console.log(`[MemoryDiagnostics] Reclaimed: RSS=${rssReclaimed.toFixed(0)}MB, Heap=${heapReclaimed.toFixed(0)}MB`);
-
- return {
- before: { rss: beforeRSS, heap: beforeHeap },
- after: { rss: afterRSS, heap: afterHeap },
- reclaimed: { rss: rssReclaimed, heap: heapReclaimed }
- };
-}
-
-/**
- * 检测可能的内存泄漏
- */
-function detectMemoryLeak() {
- const usage = process.memoryUsage();
- const rss = usage.rss / 1024 / 1024;
- const heap = usage.heapUsed / 1024 / 1024;
- const external = usage.external / 1024 / 1024;
-
- const issues = [];
-
- // RSS 过高
- if (rss > 500) {
- issues.push({
- type: 'HIGH_RSS',
- severity: 'critical',
- message: `RSS is very high: ${rss.toFixed(0)}MB`,
- suggestion: 'Check for native memory leaks, large buffers, or file handles'
- });
- }
-
- // Heap 过高
- if (heap > 200) {
- issues.push({
- type: 'HIGH_HEAP',
- severity: 'warning',
- message: `Heap usage is high: ${heap.toFixed(0)}MB`,
- suggestion: 'Check for object retention, closures, or large data structures'
- });
- }
-
- // External 过高
- if (external > 100) {
- issues.push({
- type: 'HIGH_EXTERNAL',
- severity: 'warning',
- message: `External memory is high: ${external.toFixed(0)}MB`,
- suggestion: 'Check for Buffer allocations, native addons, or C++ objects'
- });
- }
-
- // RSS 远大于 Heap(可能是 native 内存泄漏)
- if (rss > heap * 3) {
- issues.push({
- type: 'RSS_HEAP_MISMATCH',
- severity: 'critical',
- message: `RSS (${rss.toFixed(0)}MB) is much larger than Heap (${heap.toFixed(0)}MB)`,
- suggestion: 'Likely native memory leak. Check SQLite, Sharp, or other native modules'
- });
- }
-
- return issues;
-}
-
-/**
- * 打印内存泄漏诊断
- */
-function diagnoseMemoryLeak() {
- console.log('\n[MemoryDiagnostics] Running memory leak detection...\n');
-
- const issues = detectMemoryLeak();
-
- if (issues.length === 0) {
- console.log('✅ No obvious memory issues detected');
- } else {
- console.log(`⚠️ Found ${issues.length} potential issues:\n`);
- issues.forEach((issue, index) => {
- console.log(`${index + 1}. [${issue.severity.toUpperCase()}] ${issue.type}`);
- console.log(` ${issue.message}`);
- console.log(` 💡 ${issue.suggestion}\n`);
- });
- }
-
- return issues;
-}
-
-module.exports = {
- takeHeapSnapshot,
- getHeapStatistics,
- logHeapStatistics,
- forceGCAndReport,
- detectMemoryLeak,
- diagnoseMemoryLeak
-};
diff --git a/backend/utils/memoryStats.js b/backend/utils/memoryStats.js
deleted file mode 100644
index 9806815..0000000
--- a/backend/utils/memoryStats.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * Memory Statistics Utility
- * 显示详细的内存使用统计
- */
-
-function formatBytes(bytes) {
- return (bytes / 1024 / 1024).toFixed(2) + ' MB';
-}
-
-function getMemoryStats() {
- const usage = process.memoryUsage();
-
- return {
- heapUsed: usage.heapUsed,
- heapTotal: usage.heapTotal,
- rss: usage.rss,
- external: usage.external,
- arrayBuffers: usage.arrayBuffers,
- heapUsedMB: formatBytes(usage.heapUsed),
- heapTotalMB: formatBytes(usage.heapTotal),
- rssMB: formatBytes(usage.rss),
- externalMB: formatBytes(usage.external),
- arrayBuffersMB: formatBytes(usage.arrayBuffers)
- };
-}
-
-function logMemoryStats(label = 'Memory') {
- const stats = getMemoryStats();
- console.log(`\n[${label}] Memory Statistics:`);
- console.log(` RSS (总内存): ${stats.rssMB}`);
- console.log(` Heap Used (堆使用): ${stats.heapUsedMB}`);
- console.log(` Heap Total (堆总量):${stats.heapTotalMB}`);
- console.log(` External (外部): ${stats.externalMB}`);
- console.log(` Array Buffers: ${stats.arrayBuffersMB}`);
-}
-
-function getMemoryPressure() {
- const usage = process.memoryUsage();
- const heapUsedMB = usage.heapUsed / 1024 / 1024;
- const rssMB = usage.rss / 1024 / 1024;
-
- let pressure = 'low';
- if (heapUsedMB > 200 || rssMB > 500) {
- pressure = 'critical';
- } else if (heapUsedMB > 100 || rssMB > 300) {
- pressure = 'high';
- } else if (heapUsedMB > 50 || rssMB > 150) {
- pressure = 'medium';
- }
-
- return {
- level: pressure,
- heapUsedMB,
- rssMB
- };
-}
-
-module.exports = {
- getMemoryStats,
- logMemoryStats,
- getMemoryPressure,
- formatBytes
-};
diff --git a/backend/utils/migrateThumbnails.js b/backend/utils/migrateThumbnails.js
deleted file mode 100644
index bde2671..0000000
--- a/backend/utils/migrateThumbnails.js
+++ /dev/null
@@ -1,148 +0,0 @@
-/**
- * 缩略图迁移工具
- * 将旧结构的缩略图迁移到新的分片结构
- *
- * 旧结构:.flypic/thumbnails/hash.webp
- * 新结构:.flypic/thumbnails/ab/hash.webp (分片存储)
- */
-
-const fs = require('fs');
-const path = require('path');
-
-/**
- * 迁移单个素材库的缩略图
- * @param {string} libraryPath - 素材库路径
- * @returns {Object} 迁移结果统计
- */
-async function migrateThumbnails(libraryPath) {
- const thumbnailsDir = path.join(libraryPath, '.flypic', 'thumbnails');
-
- // 检查目录是否存在
- if (!fs.existsSync(thumbnailsDir)) {
- return { migrated: 0, skipped: 0, errors: 0, message: 'Thumbnails directory not found' };
- }
-
- const stats = {
- migrated: 0,
- skipped: 0,
- errors: 0
- };
-
- try {
- const entries = fs.readdirSync(thumbnailsDir, { withFileTypes: true });
-
- for (const entry of entries) {
- // 跳过已经是目录的(已经是新结构)
- if (entry.isDirectory()) {
- continue;
- }
-
- // 只处理 .webp 文件
- if (!entry.name.endsWith('.webp')) {
- continue;
- }
-
- try {
- const oldPath = path.join(thumbnailsDir, entry.name);
-
- // 提取 hash(去掉扩展名)
- const hash = entry.name.replace('.webp', '');
-
- // 计算分片目录(使用前2个字符)
- const shard = hash.slice(0, 2);
- const shardDir = path.join(thumbnailsDir, shard);
- const newPath = path.join(shardDir, entry.name);
-
- // 如果新路径已存在,跳过
- if (fs.existsSync(newPath)) {
- stats.skipped++;
- continue;
- }
-
- // 创建分片目录
- if (!fs.existsSync(shardDir)) {
- fs.mkdirSync(shardDir, { recursive: true });
- }
-
- // 移动文件
- fs.renameSync(oldPath, newPath);
- stats.migrated++;
-
- console.log(`[Migrate] Moved: ${entry.name} -> ${shard}/${entry.name}`);
- } catch (error) {
- console.error(`[Migrate] Error migrating ${entry.name}:`, error.message);
- stats.errors++;
- }
- }
-
- console.log(`[Migrate] Complete for ${libraryPath}:`, stats);
- return stats;
- } catch (error) {
- console.error(`[Migrate] Error reading thumbnails directory:`, error);
- return { ...stats, message: error.message };
- }
-}
-
-/**
- * 检查是否需要迁移
- * @param {string} libraryPath - 素材库路径
- * @returns {boolean} 是否需要迁移
- */
-function needsMigration(libraryPath) {
- const thumbnailsDir = path.join(libraryPath, '.flypic', 'thumbnails');
-
- if (!fs.existsSync(thumbnailsDir)) {
- return false;
- }
-
- try {
- const entries = fs.readdirSync(thumbnailsDir, { withFileTypes: true });
-
- // 检查是否有直接在 thumbnails 目录下的 .webp 文件
- for (const entry of entries) {
- if (entry.isFile() && entry.name.endsWith('.webp')) {
- return true;
- }
- }
-
- return false;
- } catch (error) {
- console.error(`[Migrate] Error checking migration need:`, error);
- return false;
- }
-}
-
-/**
- * 批量迁移多个素材库
- * @param {Array} libraries - 素材库列表
- * @returns {Object} 总体迁移统计
- */
-async function migrateAllLibraries(libraries) {
- const totalStats = {
- migrated: 0,
- skipped: 0,
- errors: 0,
- librariesProcessed: 0
- };
-
- for (const library of libraries) {
- if (needsMigration(library.path)) {
- console.log(`[Migrate] Processing library: ${library.name}`);
- const stats = await migrateThumbnails(library.path);
-
- totalStats.migrated += stats.migrated;
- totalStats.skipped += stats.skipped;
- totalStats.errors += stats.errors;
- totalStats.librariesProcessed++;
- }
- }
-
- console.log(`[Migrate] Total stats:`, totalStats);
- return totalStats;
-}
-
-module.exports = {
- migrateThumbnails,
- needsMigration,
- migrateAllLibraries
-};
diff --git a/frontend/src/api/file.js b/frontend/src/api/file.js
index 3f5e190..e54361b 100644
--- a/frontend/src/api/file.js
+++ b/frontend/src/api/file.js
@@ -36,12 +36,14 @@ export const fileAPI = {
* @param {string} libraryId - 素材库ID
* @param {Array} items - 待移动项
* @param {string} targetFolder - 目标文件夹路径
+ * @param {string} conflictAction - 冲突处理方式: 'skip'|'replace'|'rename'
*/
- async move(libraryId, items, targetFolder) {
+ async move(libraryId, items, targetFolder, conflictAction = 'rename') {
return api.post('/file/move', {
libraryId,
items,
- targetFolder
+ targetFolder,
+ conflictAction
});
},
diff --git a/frontend/src/components/DragDropOverlay.jsx b/frontend/src/components/DragDropOverlay.jsx
new file mode 100644
index 0000000..8f53b0e
--- /dev/null
+++ b/frontend/src/components/DragDropOverlay.jsx
@@ -0,0 +1,25 @@
+/**
+ * 拖拽上传提示覆盖层组件
+ */
+
+const DragDropOverlay = ({ isVisible }) => {
+ if (!isVisible) return null;
+
+ return (
+
+
+
+
📤
+
+ 拖放图片到这里
+
+
+ 支持 JPG、PNG、GIF、WebP 等格式
+
+
+
+
+ );
+};
+
+export default DragDropOverlay;
diff --git a/frontend/src/components/EmptyState.jsx b/frontend/src/components/EmptyState.jsx
new file mode 100644
index 0000000..6292953
--- /dev/null
+++ b/frontend/src/components/EmptyState.jsx
@@ -0,0 +1,21 @@
+/**
+ * 空状态提示组件
+ */
+
+const EmptyState = ({ isLoading }) => {
+ return (
+
+ {isLoading ? (
+
加载中...
+ ) : (
+ <>
+
暂无图片
+
请添加素材库或调整搜索条件
+
可以直接拖拽文件到这里上传
+ >
+ )}
+
+ );
+};
+
+export default EmptyState;
diff --git a/frontend/src/components/ImageCell.jsx b/frontend/src/components/ImageCell.jsx
new file mode 100644
index 0000000..5d9cfb1
--- /dev/null
+++ b/frontend/src/components/ImageCell.jsx
@@ -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 (
+
+
onImageClick(image, e, flatIndex)}
+ onDoubleClick={() => onImageDoubleClick(image, flatIndex)}
+ onContextMenu={(e) => onContextMenu(e, image)}
+ draggable={true}
+ onDragStart={(e) => onDragStart(e, image)}
+ >
+
)
{
+ 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' && (
+
+ {image.fileType === 'video' &&
}
+ {image.fileType === 'audio' &&
}
+ {image.fileType === 'document' &&
}
+ {image.fileType === 'design' &&
}
+ {image.fileType === 'other' &&
}
+
+ {image.format || image.filename.split('.').pop()}
+
+
+ )}
+
+
+
+
+
+ {renamingImage?.id === image.id ? (
+ // 编辑模式
+
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'
+ }}
+ />
+ ) : (
+ // 显示模式
+
+ {image.filename}
+
+ )}
+
+
+ );
+};
+
+export default ImageCell;
diff --git a/frontend/src/components/ImageWaterfall.jsx b/frontend/src/components/ImageWaterfall.jsx
index ea515dc..66a7bdf 100644
--- a/frontend/src/components/ImageWaterfall.jsx
+++ b/frontend/src/components/ImageWaterfall.jsx
@@ -1,15 +1,38 @@
-import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
+/**
+ * 图片瀑布流组件 - 重构版
+ * 从 1880 行精简到 ~300 行,通过提取 hooks 和组件实现
+ */
+
+import { useState, useMemo, useCallback, useRef } from 'react';
import { PhotoProvider } from 'react-photo-view';
import 'react-photo-view/dist/react-photo-view.css';
import { VariableSizeList as List } from 'react-window';
-import { Play, FileText, Palette, Music, File } from 'lucide-react';
+
+// Stores
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
-import { useUIStore } from '../stores/useUIStore';
-import { useScanStore } from '../stores/useScanStore';
-import { useClipboardStore } from '../stores/useClipboardStore';
-import { imageAPI, fileAPI } from '../api';
-import requestManager, { RequestType } from '../services/requestManager';
+
+// Custom Hooks
+import { useWaterfallLayout } from '../hooks/useWaterfallLayout';
+import { useImageDelete } from '../hooks/useImageDelete';
+import { useConflictHandler } from '../hooks/useConflictHandler';
+import { useImageClipboard } from '../hooks/useImageClipboard';
+import { useImageMove } from '../hooks/useImageMove';
+import { useImageRename } from '../hooks/useImageRename';
+import { useImageRating } from '../hooks/useImageRating';
+import { useImageUpload } from '../hooks/useImageUpload';
+import { useImageKeyboard } from '../hooks/useImageKeyboard';
+import { useInfiniteScroll } from '../hooks/useInfiniteScroll';
+
+// Utils
+import { filterImages } from '../utils/imageFilters';
+import { imageAPI } from '../api';
+
+// Components
+import ImageCell from './ImageCell';
+import DragDropOverlay from './DragDropOverlay';
+import UploadProgress from './UploadProgress';
+import EmptyState from './EmptyState';
import FileViewer from './FileViewer';
import ContextMenu, { menuItems } from './ContextMenu';
import UndoToast from './UndoToast';
@@ -17,774 +40,245 @@ import RatingToast from './RatingToast';
import FolderSelector from './FolderSelector';
import ConflictDialog from './ConflictDialog';
-// 虚拟滚动阈值:超过此数量启用虚拟滚动
-const VIRTUAL_SCROLL_THRESHOLD = 100;
-
-// 解析大小字符串为 KB
-const parseSizeToKB = (sizeStr) => {
- const match = sizeStr.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB)$/);
- if (!match) return 0;
- const value = parseFloat(match[1]);
- const unit = match[2];
- switch (unit) {
- case 'B': return value / 1024;
- case 'KB': return value;
- case 'MB': return value * 1024;
- case 'GB': return value * 1024 * 1024;
- default: return 0;
- }
-};
-
-// 匹配大小范围
-const matchSizeRange = (sizeKB, range) => {
- if (range.startsWith('>')) {
- const minStr = range.substring(1).trim();
- const minKB = parseSizeToKB(minStr);
- return sizeKB >= minKB;
- } else if (range.includes(' - ')) {
- const [minStr, maxStr] = range.split(' - ').map(s => s.trim());
- const minKB = parseSizeToKB(minStr);
- const maxKB = parseSizeToKB(maxStr);
- return sizeKB >= minKB && sizeKB < maxKB;
- }
- return false;
-};
+// 虚拟滚动阈值
+const VIRTUAL_SCROLL_THRESHOLD = 50;
// 加载配置
const LOAD_CONFIG = {
- pageSize: 100, // 每次加载 100 张(更轻量)
- preloadThreshold: 300, // 距离边界 300px 时预加载
- overscanCount: 4, // 预渲染 4 行(减少内存)
+ overscanCount: 4, // 预渲染 4 行
};
function ImageWaterfall() {
const { currentLibraryId } = useLibraryStore();
const {
images, selectedImage, setSelectedImage, selectedImages, setSelectedImages,
- toggleImageSelection, clearSelection, imageLoadingState, selectedFolder, setSelectedFolder,
- searchKeywords, filters, appendImages, setImageLoadingState, setImages, folders, setFolders,
- renamingImage, setRenamingImage, updateImage, setSelectedFolderItem
+ toggleImageSelection, clearSelection, imageLoadingState, selectedFolder,
+ searchKeywords, filters, folders, setSelectedFolderItem
} = useImageStore();
-
- const { thumbnailHeight, isResizingPanels } = useUIStore();
-
- // 前端筛选逻辑:基于 filters 过滤图片
- const filteredImages = useMemo(() => {
- const { formats, sizes, orientations, ratings } = filters;
-
- // 如果没有任何筛选条件,直接返回原始图片
- if ((!formats || formats.length === 0) &&
- (!sizes || sizes.length === 0) &&
- (!orientations || orientations.length === 0) &&
- (!ratings || ratings.length === 0)) {
- return images;
- }
- return images.filter(img => {
- // 格式筛选
- if (formats && formats.length > 0) {
- if (!formats.includes(img.format?.toLowerCase())) {
- return false;
- }
- }
-
- // 文件大小筛选
- if (sizes && sizes.length > 0) {
- const sizeKB = img.size / 1024;
- let matchesSize = false;
-
- for (const range of sizes) {
- if (matchSizeRange(sizeKB, range)) {
- matchesSize = true;
- break;
- }
- }
-
- if (!matchesSize) return false;
- }
-
- // 方向筛选(多选)
- if (orientations && orientations.length > 0) {
- const aspectRatio = img.width / img.height;
- let matchesOrientation = false;
-
- for (const orientation of orientations) {
- if (orientation === 'horizontal' && aspectRatio > 1.05) {
- matchesOrientation = true;
- break;
- } else if (orientation === 'vertical' && aspectRatio < 0.95) {
- matchesOrientation = true;
- break;
- } else if (orientation === 'square' && aspectRatio >= 0.95 && aspectRatio <= 1.05) {
- matchesOrientation = true;
- break;
- }
- }
-
- if (!matchesOrientation) return false;
- }
-
- // 评分筛选(多选)
- if (ratings && ratings.length > 0) {
- const imgRating = img.rating || 0;
- if (!ratings.includes(imgRating)) return false;
- }
-
- return true;
- });
- }, [images, filters]);
- const containerRef = useRef(null);
- const listRef = useRef(null);
- const [containerWidth, setContainerWidth] = useState(0);
- const [containerHeight, setContainerHeight] = useState(0);
+ // 状态
const [photoIndex, setPhotoIndex] = useState(-1);
const [lastSelectedIndex, setLastSelectedIndex] = useState(null);
const [viewerFile, setViewerFile] = useState(null);
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, image: null });
- const [undoToast, setUndoToast] = useState({ isVisible: false, message: '', count: 0 });
- const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈,支持多次撤销
- const [ratingToast, setRatingToast] = useState({ isVisible: false, rating: 0, count: 0 }); // 评分提醒
- const [showFolderSelector, setShowFolderSelector] = useState(false); // 显示文件夹选择器
- const [moveItems, setMoveItems] = useState([]); // 待移动的项
- const [editingFilename, setEditingFilename] = useState(''); // 编辑中的文件名
- const editInputRef = useRef(null); // 编辑输入框引用
- const [conflictDialog, setConflictDialog] = useState({ isOpen: false, conflicts: [], pendingPaste: null, pendingUpload: null }); // 冲突对话框
- const [isDraggingOver, setIsDraggingOver] = useState(false); // 拖拽悬停状态
- const [uploadProgress, setUploadProgress] = useState({ isUploading: false, percent: 0, current: 0, total: 0 }); // 上传进度
-
- // 剪贴板状态
- const { copyToClipboard, getClipboard, hasClipboard } = useClipboardStore();
+ // 统一图片移动/删除撤销顺序的栈:按操作时间顺序记录 'move' | 'delete'
+ const [undoStack, setUndoStack] = useState([]);
+ const listRef = useRef(null);
+ const prevRowCountRef = useRef(0);
- // 监听文件夹切换,切换时关闭Toast
- useEffect(() => {
- // 文件夹切换时立即关闭Toast,避免重新计时
- setUndoToast({ isVisible: false, message: '', count: 0 });
- }, [selectedFolder]);
+ // 前端筛选
+ const filteredImages = useMemo(() => {
+ return filterImages(images, filters);
+ }, [images, filters]);
- // 全局阻止浏览器默认的拖放行为(防止浏览器打开文件)
- useEffect(() => {
- const preventDefaults = (e) => {
- e.preventDefault();
- e.stopPropagation();
- };
+ // 瀑布流布局
+ const { rows, flatImages, containerRef, containerWidth, containerHeight, getRowHeight } =
+ useWaterfallLayout(filteredImages);
- // 阻止整个文档的默认拖放行为
- document.addEventListener('dragover', preventDefaults);
- document.addEventListener('drop', preventDefaults);
+ // 删除和撤销
+ const { undoHistory, undoToast, setUndoToast, handleQuickDelete, handleUndo } =
+ useImageDelete();
- return () => {
- document.removeEventListener('dragover', preventDefaults);
- document.removeEventListener('drop', preventDefaults);
- };
- }, []);
+ // 统一冲突处理
+ const { conflictDialog, showConflictDialog, hideConflictDialog, resolveConflict } =
+ useConflictHandler();
- // 全局快捷键监听 - Del 键删除, Ctrl+Z 撤销, F2/Enter 重命名, Ctrl+C 复制, Ctrl+V 粘贴
- useEffect(() => {
- const handleGlobalKeyDown = async (e) => {
- // 忽略输入框中的快捷键
- if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
-
- // Ctrl+C → 复制
- if ((e.ctrlKey || e.metaKey) && e.key === 'c') {
- if (selectedImages.length > 0 || selectedImage) {
- e.preventDefault();
- handleCopy();
- }
- return;
- }
-
- // Ctrl+V → 粘贴
- if ((e.ctrlKey || e.metaKey) && e.key === 'v') {
- if (hasClipboard() && selectedFolder) {
- e.preventDefault();
- await handlePaste();
- }
- return;
- }
-
- // Ctrl+Z → 撤销
- if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
- e.preventDefault();
- if (undoHistory.length > 0) {
- await handleUndo();
- }
- return;
- }
-
- // F2 或 Enter → 重命名(仅单选时)
- if ((e.key === 'F2' || e.key === 'Enter') && selectedImage && selectedImages.length === 0) {
- e.preventDefault();
- handleStartRename(selectedImage);
- return;
- }
-
- // Del 键 → 直接移入回收站
- if (e.key === 'Delete') {
- if (selectedImages.length > 0 || selectedImage) {
- e.preventDefault();
- await handleQuickDelete();
- }
- return;
- }
-
- // 数字键 1-5 → 快速评分
- if (['1', '2', '3', '4', '5'].includes(e.key)) {
- if (selectedImages.length > 0 || selectedImage) {
- e.preventDefault();
- const rating = parseInt(e.key);
- await handleQuickRating(rating);
- }
- return;
- }
-
- // 数字键 0 → 取消评分
- if (e.key === '0') {
- if (selectedImages.length > 0 || selectedImage) {
- e.preventDefault();
- await handleQuickRating(0);
- }
- return;
- }
- };
+ // 剪贴板操作
+ const { handleCopy, handlePaste, executePaste } =
+ useImageClipboard(showConflictDialog);
- window.addEventListener('keydown', handleGlobalKeyDown);
- return () => window.removeEventListener('keydown', handleGlobalKeyDown);
- }, [selectedImages, selectedImage, images, currentLibraryId, undoHistory, selectedFolder, hasClipboard]);
+ // 移动功能
+ const {
+ showFolderSelector, moveItems, handleMoveClick, handleMove, handleCancelMove, executeMove,
+ undoHistory: moveUndoHistory, undoToast: moveUndoToast, setUndoToast: setMoveUndoToast, handleUndoMove
+ } = useImageMove(showConflictDialog);
- // 简单的向下无限滚动加载
- const loadMoreImages = useCallback(async () => {
- if (!currentLibraryId || !imageLoadingState.hasMore || imageLoadingState.isLoading) {
- return;
- }
+ // 重命名
+ const {
+ renamingImage,
+ editingFilename,
+ editInputRef,
+ setEditingFilename,
+ handleStartRename,
+ handleFinishRename,
+ handleCancelRename
+ } = useImageRename();
- const requestContext = requestManager.createRequest(RequestType.IMAGES);
- setImageLoadingState({ isLoading: true });
+ // 评分
+ const { ratingToast, setRatingToast, handleQuickRating } = useImageRating();
- try {
- const params = {
- offset: images.length,
- limit: LOAD_CONFIG.pageSize
- };
- if (selectedFolder) params.folder = selectedFolder;
- if (searchKeywords) params.keywords = searchKeywords;
- if (filters.formats?.length > 0) params.formats = filters.formats.join(',');
+ // 上传
+ const {
+ isDraggingOver,
+ uploadProgress,
+ handleDragEnter,
+ handleDragOver,
+ handleDragLeave,
+ handleDrop: baseHandleDrop,
+ uploadWithConflictAction
+ } = useImageUpload();
- const response = await imageAPI.search(currentLibraryId, params, {
- signal: requestContext.signal
+ // 无限滚动
+ const { loadMoreImages, preloadThreshold } = useInfiniteScroll();
+
+ // 带撤销栈的删除
+ const handleQuickDeleteWithUndoStack = useCallback(async () => {
+ await handleQuickDelete();
+ setUndoStack(prev => [...prev, 'delete']);
+ }, [handleQuickDelete]);
+
+ // 带撤销栈的移动(通过文件夹选择器触发)
+ const handleMoveWithUndoStack = useCallback(async (targetFolder) => {
+ await handleMove(targetFolder);
+ setUndoStack(prev => [...prev, 'move']);
+ }, [handleMove]);
+
+ // 键盘快捷键(Ctrl+Z 按照 undoStack 顺序一步步撤销)
+ useImageKeyboard({
+ onDelete: handleQuickDeleteWithUndoStack,
+ onUndo: async () => {
+ console.log('🔍 撤销前状态:', {
+ undoStack: [...undoStack],
+ moveUndoHistory: moveUndoHistory.length,
+ deleteUndoHistory: undoHistory.length
});
-
- if (!requestManager.isValid(requestContext.id)) {
- return;
- }
-
- const { images: newImages, total, hasMore } = response;
- requestManager.complete(requestContext.id);
-
- appendImages(newImages);
- setImageLoadingState({
- isLoading: false,
- loadedCount: images.length + newImages.length,
- totalCount: total,
- hasMore: hasMore || false,
- });
- } catch (error) {
- if (error.name === 'CanceledError' || error.name === 'AbortError') {
- return;
- }
- console.error('Error loading more images:', error);
- requestManager.error(requestContext.id);
- setImageLoadingState({ isLoading: false });
- }
- }, [currentLibraryId, imageLoadingState, images.length, selectedFolder, searchKeywords, filters, appendImages, setImageLoadingState]);
-
- // 监听容器宽度变化(使用 ResizeObserver + 去抖/阈值抑制)
- useEffect(() => {
- let resizeObserver = null;
- let retryCount = 0;
- const maxRetries = 10;
-
- // 使用 ref 记录上次宽度,避免频繁 setState
- const lastWidthRef = { current: 0 };
- let debounceTimer = null;
-
- const emitSize = (width, height) => {
- // 仅当差异超过阈值时更新,减少重算次数
- const threshold = 12; // px
- if (Math.abs(width - lastWidthRef.current) < threshold) return true;
-
- lastWidthRef.current = width;
-
- // 去抖:在一小段静止后再更新(拖动时降低重算频率)
- if (debounceTimer) clearTimeout(debounceTimer);
- debounceTimer = setTimeout(() => {
- setContainerWidth(width);
- setContainerHeight(height);
- }, 50);
- return true;
- };
-
- const measureAndEmit = () => {
- if (containerRef.current) {
- // 预留 padding:与现有布局保持一致
- const width = containerRef.current.offsetWidth - 32;
- const height = containerRef.current.offsetHeight;
- if (width > 0) {
- return emitSize(width, height);
- }
- }
- return false;
- };
-
- const tryInit = () => {
- if (measureAndEmit()) {
- // 成功获取宽度,设置 ResizeObserver
- if (containerRef.current) {
- resizeObserver = new ResizeObserver(() => {
- // 拖动时跳过更新,避免频繁重算布局
- if (useUIStore.getState().isResizingPanels) return;
- measureAndEmit();
- });
- resizeObserver.observe(containerRef.current);
- }
- } else if (retryCount < maxRetries) {
- // 重试
- retryCount++;
- requestAnimationFrame(tryInit);
- }
- };
-
- // 使用 requestAnimationFrame 确保 DOM 已渲染
- requestAnimationFrame(tryInit);
-
- return () => {
- if (resizeObserver) {
- resizeObserver.disconnect();
- }
- if (debounceTimer) {
- clearTimeout(debounceTimer);
- }
- };
- }, []);
-
- // 拖动结束时(isResizingPanels 从 true -> false)立即测量一次
- useEffect(() => {
- if (isResizingPanels) return;
- if (!containerRef.current) return;
- const width = containerRef.current.offsetWidth - 32;
- const height = containerRef.current.offsetHeight;
- if (width > 0) {
- setContainerWidth(width);
- setContainerHeight(height);
- // 重置虚拟列表缓存
- if (listRef.current) {
- listRef.current.resetAfterIndex(0);
- }
- }
- }, [isResizingPanels]);
-
- // 布局计算(始终在主线程同步执行)
- const rows = useMemo(() => {
- if (!filteredImages.length || !containerWidth) {
- return [];
- }
-
- const gap = 16;
- const targetHeight = thumbnailHeight;
- const calculatedRows = [];
- let currentRow = [];
- let currentRowWidthSum = 0;
-
- filteredImages.forEach((image, index) => {
- const aspectRatio = image.width / image.height;
- const imageWidth = targetHeight * aspectRatio;
- currentRow.push({
- ...image,
- originalWidth: imageWidth,
- aspectRatio: aspectRatio
- });
- currentRowWidthSum += imageWidth;
-
- const currentGaps = (currentRow.length - 1) * gap;
- const totalWidth = currentRowWidthSum + currentGaps;
- const isLastImage = index === filteredImages.length - 1;
-
- let shouldFinishRow = false;
-
- if (isLastImage) {
- shouldFinishRow = true;
- } else if (totalWidth >= containerWidth * 0.95) {
- // Row is almost full (95% or more) - finish it
- shouldFinishRow = true;
- } else {
- // Check if adding next image would overflow too much
- const nextImage = filteredImages[index + 1];
- if (nextImage) {
- const nextAspectRatio = nextImage.width / nextImage.height;
- const nextImageWidth = targetHeight * nextAspectRatio;
- const nextTotalWidth = currentRowWidthSum + nextImageWidth + (currentRow.length * gap);
-
- // If adding next image would exceed 120% of container width, finish current row
- if (nextTotalWidth > containerWidth * 1.2) {
- shouldFinishRow = true;
- }
- }
+ if (undoStack.length === 0) return;
+ const last = undoStack[undoStack.length - 1];
+ setUndoStack(prev => prev.slice(0, -1));
+
+ console.log(`🎯 准备撤销: ${last}`);
+
+ if (last === 'move' && moveUndoHistory.length > 0) {
+ console.log('↩️ 执行移动撤销');
+ await handleUndoMove();
+ } else if (last === 'delete' && undoHistory.length > 0) {
+ console.log('↩️ 执行删除撤销');
+ await handleUndo();
}
- if (shouldFinishRow) {
- const totalGaps = (currentRow.length - 1) * gap;
- const availableWidth = containerWidth - totalGaps;
-
- // For last row with few images, limit the scale to avoid over-stretching
- let scale = availableWidth / currentRowWidthSum;
-
- if (isLastImage && currentRow.length < 3) {
- // Last row with 1-2 images: don't stretch too much
- scale = Math.min(scale, 1.2);
- }
-
- const rowHeight = targetHeight * scale;
-
- currentRow = currentRow.map(img => ({
- ...img,
- calculatedWidth: img.originalWidth * scale,
- calculatedHeight: rowHeight
- }));
-
- calculatedRows.push(currentRow);
-
- // Reset for next row
- currentRow = [];
- currentRowWidthSum = 0;
+ console.log('✅ 撤销完成');
+ },
+ onCopy: () => {
+ const result = handleCopy();
+ if (result.success) {
+ setUndoToast({
+ isVisible: true,
+ message: `已复制 ${result.count} 个文件`,
+ count: result.count
+ });
+ setTimeout(() => setUndoToast({ isVisible: false, message: '', count: 0 }), 2000);
}
+ },
+ onPaste: handlePaste,
+ onRename: handleStartRename,
+ onRating: handleQuickRating,
+ canUndo: undoStack.length > 0,
+ canPaste: selectedFolder !== null
+ });
+
+ // 包装上传处理以集成冲突对话框
+ const handleDrop = useCallback(async (e) => {
+ await baseHandleDrop(e, (conflicts, files, targetFolder) => {
+ showConflictDialog(conflicts, 'upload', { files, targetFolder });
});
+ }, [baseHandleDrop, showConflictDialog]);
- return calculatedRows;
- }, [filteredImages, thumbnailHeight, containerWidth]);
-
- const getThumbnailUrl = (image) => {
- // 后端已统一转换为 camelCase
- const thumbnailPath = image.thumbnailPath;
-
- if (!currentLibraryId || !thumbnailPath) {
- return '';
- }
- // 提取文件名(兼容反斜杠)
- const filename = thumbnailPath.replace(/\\/g, '/').split('/').pop();
- // 使用分片结构,不再需要 size 参数
+ // 缩略图和原图 URL
+ const getThumbnailUrl = useCallback((image) => {
+ if (!currentLibraryId || !image.thumbnailPath) return '';
+ const filename = image.thumbnailPath.replace(/\\/g, '/').split('/').pop();
return imageAPI.getThumbnailUrl(currentLibraryId, filename);
- };
+ }, [currentLibraryId]);
- const getOriginalUrl = (image) => {
+ const getOriginalUrl = useCallback((image) => {
if (!currentLibraryId) return '';
return imageAPI.getOriginalUrl(currentLibraryId, image.path);
- };
+ }, [currentLibraryId]);
- // PhotoProvider 使用与布局无关的列表,避免随 containerWidth 变化重建
+ // PhotoProvider 图片列表
const providerImages = useMemo(() => {
return filteredImages.map(img => ({ src: getOriginalUrl(img), key: img.id }));
- }, [filteredImages, currentLibraryId]);
+ }, [filteredImages, getOriginalUrl]);
- // 是否启用虚拟滚动
- const useVirtualScroll = filteredImages.length > VIRTUAL_SCROLL_THRESHOLD;
-
- // 获取行高(用于虚拟滚动)
- const getRowHeight = useCallback((index) => {
- if (!rows || !rows[index] || rows[index].length === 0) {
- return thumbnailHeight + 40;
- }
- // 行高 = 图片高度 + 文件名区域 + 行间距
- const firstImage = rows[index][0];
- return (firstImage?.calculatedHeight || thumbnailHeight) + 28 + 32;
- }, [rows, thumbnailHeight]);
-
- // 跟踪上次的行数,用于增量更新虚拟列表
- const prevRowCountRef = useRef(0);
-
- // 当行数据变化时,智能更新虚拟列表缓存
- useEffect(() => {
- if (listRef.current && useVirtualScroll) {
- const prevRowCount = prevRowCountRef.current;
- const currRowCount = rows.length;
-
- if (currRowCount > prevRowCount && prevRowCount > 0) {
- // 增量更新:只重置新增的行,保持滚动位置
- const resetIndex = Math.max(0, prevRowCount - 1);
- listRef.current.resetAfterIndex(resetIndex);
-
- // 不需要手动恢复滚动位置,react-window 会自动保持
- } else if (currRowCount !== prevRowCount) {
- // 完全重置(只在行数减少或首次加载时)
- listRef.current.resetAfterIndex(0);
- }
-
- prevRowCountRef.current = currRowCount;
- }
- }, [rows, useVirtualScroll]);
-
- // 扁平化的图片列表(用于 Shift 多选)
- const flatImages = useMemo(() => {
- if (!rows || rows.length === 0) return [];
- return rows.flat();
- }, [rows]);
-
- // 处理图片点击(支持 Ctrl/Shift 多选)
+ // 图片点击处理
const handleImageClick = useCallback((image, event, imageIndex) => {
- // 关键修复:点击图片时清空文件夹选中状态
setSelectedFolderItem(null);
if (event.ctrlKey || event.metaKey) {
- // Ctrl/Cmd 点击:切换选中状态
event.preventDefault();
toggleImageSelection(image);
setLastSelectedIndex(imageIndex);
} else if (event.shiftKey && lastSelectedIndex !== null) {
- // Shift 点击:范围选择
event.preventDefault();
const start = Math.min(lastSelectedIndex, imageIndex);
const end = Math.max(lastSelectedIndex, imageIndex);
const rangeImages = flatImages.slice(start, end + 1);
setSelectedImages(rangeImages);
} else {
- // 普通点击:单选
clearSelection();
setSelectedImage(image);
setLastSelectedIndex(imageIndex);
}
}, [flatImages, lastSelectedIndex, toggleImageSelection, setSelectedImages, clearSelection, setSelectedImage, setSelectedFolderItem]);
- // 处理右键菜单
+ // 图片双击处理
+ const handleImageDoubleClick = useCallback((image, flatIndex) => {
+ const fileType = image.fileType || 'image';
+ if (fileType === 'image') {
+ setPhotoIndex(flatIndex);
+ } else {
+ setViewerFile(image);
+ }
+ }, []);
+
+ // 文件名双击处理(重命名)
+ const handleFilenameDoubleClick = useCallback((e, image) => {
+ // 始终阻止事件冒泡,避免触发图片放大
+ e.stopPropagation();
+
+ // 只在单选时允许双击重命名
+ if (selectedImages.length === 0) {
+ handleStartRename(image);
+ }
+ }, [selectedImages, handleStartRename]);
+
+ // 右键菜单
const handleContextMenu = useCallback((e, image) => {
e.preventDefault();
+
+ // 右键时,如果当前图片不在选区中,则将其设为新的选中项
+ if (selectedImages.length === 0) {
+ if (!selectedImage || selectedImage.id !== image.id) {
+ clearSelection();
+ setSelectedImage(image);
+ }
+ } else if (!selectedImages.some(img => img.id === image.id)) {
+ // 已经有多选,但右键点在选区外,则重置为单选
+ clearSelection();
+ setSelectedImage(image);
+ }
+
setContextMenu({
isOpen: true,
position: { x: e.clientX, y: e.clientY },
image
});
- }, []);
+ }, [selectedImages, selectedImage, clearSelection, setSelectedImage]);
- // 撤销删除 - 乐观更新,立即响应
- const handleUndo = async () => {
- if (undoHistory.length === 0) return;
-
- // 从历史栈中取出最近的删除记录
- const lastDeleted = undoHistory[undoHistory.length - 1];
- const remainingHistory = undoHistory.slice(0, -1);
-
- // 1. 立即关闭Toast
- setUndoToast({ isVisible: false, message: '', count: 0 });
-
- // 2. 立即更新历史栈
- setUndoHistory(remainingHistory);
-
- // 3. 获取被恢复文件的文件夹路径
- const restoredFolder = lastDeleted.images[0]?.folder || null;
-
- // 4. 立即更新文件夹计数(乐观更新)
- const { folders, setFolders } = useImageStore.getState();
- if (folders && folders.length > 0) {
- const updatedFolders = folders.map(folder => {
- // 计算该文件夹下恢复的图片数量
- const restoredInFolder = lastDeleted.images.filter(img =>
- img.folder === folder.path || img.folder?.startsWith(folder.path + '/')
- ).length;
-
- if (restoredInFolder > 0) {
- return {
- ...folder,
- count: (folder.count || 0) + restoredInFolder
- };
- }
- return folder;
- });
- setFolders(updatedFolders);
- }
-
- // 5. 立即恢复图片到UI(乐观更新)
- if (restoredFolder && restoredFolder !== selectedFolder) {
- // 跨文件夹:先跳转,让文件夹加载自然显示图片
- setSelectedFolder(restoredFolder);
- console.log(`📂 跳转到文件夹: ${restoredFolder}`);
- } else {
- // 同文件夹:立即添加到列表
- const restoredImages = [...images, ...lastDeleted.images];
- setImages(restoredImages);
- }
-
- // 6. 后台执行API调用(不阻塞UI)
- Promise.all([
- fileAPI.restore(currentLibraryId, lastDeleted.items),
- imageAPI.getFolders(currentLibraryId)
- ]).then(([restoreResult, foldersRes]) => {
- // 检查恢复结果
- if (restoreResult.failed.length > 0) {
- console.warn(`⚠️ 恢复失败: ${restoreResult.failed.length} 个文件`);
- const errorMsg = restoreResult.failed[0].error || '未知错误';
-
- // 失败时回滚UI
- setUndoHistory(undoHistory);
- if (restoredFolder === selectedFolder) {
- setImages(images);
- }
- setFolders(foldersRes.folders);
- alert(`恢复失败: ${errorMsg}\n\n提示:超过5分钟的文件已移入系统回收站,请手动从回收站恢复。`);
- } else {
- // 成功时刷新文件夹列表以确保同步
- setFolders(foldersRes.folders);
- }
- }).catch(error => {
- console.error('恢复失败:', error);
- // 失败时回滚
- setUndoHistory(undoHistory);
- if (restoredFolder === selectedFolder) {
- setImages(images);
- }
- imageAPI.getFolders(currentLibraryId).then(foldersRes => {
- setFolders(foldersRes.folders);
- });
- alert('恢复失败: ' + (error.message || '未知错误'));
- });
- };
-
- // 快速评分(数字键 0-5)
- const handleQuickRating = async (rating) => {
- const imagesToRate = selectedImages.length > 0
+ // 拖拽开始
+ const handleDragStart = useCallback((e, image) => {
+ const draggedImages = selectedImages.length > 0 && selectedImages.some(img => img.id === image.id)
? selectedImages
- : selectedImage
- ? [selectedImage]
- : [];
+ : [image];
- if (imagesToRate.length === 0) return;
-
- try {
- const paths = imagesToRate.map(img => img.path);
- await imageAPI.updateRating(currentLibraryId, paths, rating);
-
- // 更新本地状态
- const updatedImages = images.map(img => {
- if (paths.includes(img.path)) {
- return { ...img, rating };
- }
- return img;
- });
- setImages(updatedImages);
-
- // 更新选中状态
- if (selectedImage && paths.includes(selectedImage.path)) {
- useImageStore.getState().setSelectedImage({ ...selectedImage, rating });
- }
- if (selectedImages.length > 0) {
- const updatedSelected = selectedImages.map(img => {
- if (paths.includes(img.path)) {
- return { ...img, rating };
- }
- return img;
- });
- useImageStore.getState().setSelectedImages(updatedSelected);
- }
-
- // 显示评分提醒
- setRatingToast({
- isVisible: true,
- rating,
- count: imagesToRate.length
- });
-
- console.log(`⭐ 已将 ${imagesToRate.length} 张图片评为 ${rating} 星`);
- } catch (error) {
- console.error('评分失败:', error);
- alert('评分失败: ' + (error.message || '未知错误'));
- }
- };
+ const items = draggedImages.map(img => ({ type: 'file', path: img.path }));
+ e.dataTransfer.setData('application/json', JSON.stringify({ items }));
+ e.dataTransfer.effectAllowed = 'move';
+ }, [selectedImages]);
- // 快速删除(乐观更新,立即响应)
- const handleQuickDelete = async () => {
- const items = selectedImages.length > 0
- ? selectedImages.map(img => ({ type: 'file', path: img.path }))
- : selectedImage
- ? [{ type: 'file', path: selectedImage.path }]
- : [];
-
- if (items.length === 0) return;
-
- // 保存被删除的图片信息(乐观更新)
- const deletingPaths = new Set(items.map(item => item.path));
- const deletedImagesList = images.filter(img => deletingPaths.has(img.path));
-
- // 1. 立即更新UI(乐观更新)- 最快的响应
- const remainingImages = images.filter(img => !deletingPaths.has(img.path));
- setImages(remainingImages);
- clearSelection();
-
- // 2. 立即更新文件夹计数(乐观更新)
- const { folders, setFolders } = useImageStore.getState();
- if (folders && folders.length > 0) {
- const updatedFolders = folders.map(folder => {
- // 计算该文件夹下被删除的图片数量
- const deletedInFolder = deletedImagesList.filter(img =>
- img.folder === folder.path || img.folder?.startsWith(folder.path + '/')
- ).length;
-
- if (deletedInFolder > 0) {
- return {
- ...folder,
- count: Math.max(0, (folder.count || 0) - deletedInFolder)
- };
- }
- return folder;
- });
- setFolders(updatedFolders);
- }
-
- // 3. 推入历史栈
- const newHistory = [...undoHistory, {
- images: deletedImagesList,
- paths: Array.from(deletingPaths),
- items: items
- }];
- setUndoHistory(newHistory);
-
- // 5. 显示Toast(立即显示)
- setUndoToast({
- isVisible: true,
- message: `已将 ${items.length} 个文件移入临时文件夹(Ctrl+Z撤销 · ${newHistory.length}次)`,
- count: items.length
- });
-
- // 6. 后台执行API调用(不阻塞UI)
- Promise.all([
- fileAPI.delete(currentLibraryId, items),
- imageAPI.getFolders(currentLibraryId)
- ]).then(([deleteResult, foldersRes]) => {
- // 检查是否有失败的项
- if (deleteResult.failed.length > 0) {
- console.warn(`⚠️ 删除失败: ${deleteResult.failed.length} 个文件`, deleteResult.failed);
- // 如果有失败,回滚UI
- setImages(images);
- setUndoHistory(undoHistory);
- setUndoToast({ isVisible: false, message: '', count: 0 });
- setFolders(foldersRes.folders);
- alert('删除失败: 部分文件无法删除');
- } else {
- // 成功时刷新文件夹列表(但已经被乐观更新了,这里主要是确保同步)
- setFolders(foldersRes.folders);
- }
- }).catch(error => {
- console.error('删除失败:', error);
- // 失败时回滚UI
- setImages(images);
- setUndoHistory(undoHistory);
- setUndoToast({ isVisible: false, message: '', count: 0 });
- imageAPI.getFolders(currentLibraryId).then(foldersRes => {
- setFolders(foldersRes.folders);
- });
- alert('删除失败: ' + (error.message || '未知错误'));
- });
- };
-
- // 打开移动文件夹选择器
- const handleMoveClick = useCallback(() => {
- // 准备待移动的项
+ // 准备移动文件(用于右键菜单)
+ const handlePrepareMove = useCallback(() => {
const itemsToMove = selectedImages.length > 0
? selectedImages.map(img => ({ type: 'file', path: img.path }))
: selectedImage
@@ -792,622 +286,61 @@ function ImageWaterfall() {
: [];
if (itemsToMove.length === 0) return;
-
- setMoveItems(itemsToMove);
- setShowFolderSelector(true);
+
setContextMenu({ isOpen: false, position: null, image: null });
- }, [selectedImages, selectedImage]);
+ handleMoveClick(itemsToMove);
+ }, [selectedImages, selectedImage, handleMoveClick]);
- // 执行移动
- const handleMove = useCallback(async (targetFolder) => {
- if (!currentLibraryId || moveItems.length === 0) return;
-
- setShowFolderSelector(false);
-
- // 1. 立即从当前列表中移除这些图片(乐观更新)
- const movedPaths = new Set(moveItems.map(item => item.path));
- const remainingImages = images.filter(img => !movedPaths.has(img.path));
- setImages(remainingImages);
- clearSelection();
-
- try {
- // 2. 后台执行移动和刷新(并行)
- const [result, foldersRes] = await Promise.all([
- fileAPI.move(currentLibraryId, moveItems, targetFolder),
- imageAPI.getFolders(currentLibraryId)
- ]);
-
- if (result.failed && result.failed.length > 0) {
- alert(`移动失败: ${result.failed[0].error}`);
- // 失败时恢复图片列表
- setImages(images);
- } else {
- console.log(`✅ 已移动 ${moveItems.length} 个文件到: ${targetFolder || '根目录'}`);
- }
-
- // 3. 刷新文件夹列表
- setFolders(foldersRes.folders);
- } catch (error) {
- console.error('移动失败:', error);
- alert('移动失败: ' + (error.message || '未知错误'));
- // 失败时恢复图片列表
- setImages(images);
- } finally {
- setMoveItems([]);
- }
- }, [currentLibraryId, moveItems, images, setImages, clearSelection, setFolders]);
-
- // 复制图片到系统剪贴板(支持多图,使用 HTML 格式)
- const copyImagesToSystemClipboard = async (images) => {
- try {
- // 检查 Clipboard API 是否可用
- if (typeof ClipboardItem === 'undefined' || !navigator.clipboard || typeof navigator.clipboard.write !== 'function') {
- console.warn('系统剪贴板 API 不可用');
- return false;
- }
-
- if (images.length === 0) return false;
-
- // 单张图片:直接复制为 PNG
- if (images.length === 1) {
- try {
- const img = images[0];
- const imageUrl = `/api/image/original/${currentLibraryId}/${img.path}`;
- const response = await fetch(imageUrl);
- const blob = await response.blob();
-
- // 转换为 PNG
- const canvas = document.createElement('canvas');
- const image = new Image();
-
- await new Promise((resolve, reject) => {
- image.onload = resolve;
- image.onerror = reject;
- image.src = URL.createObjectURL(blob);
- });
-
- canvas.width = image.width;
- canvas.height = image.height;
- const ctx = canvas.getContext('2d');
- ctx.drawImage(image, 0, 0);
-
- URL.revokeObjectURL(image.src);
-
- const pngBlob = await new Promise((resolve) => {
- canvas.toBlob(resolve, 'image/png');
- });
-
- await navigator.clipboard.write([
- new ClipboardItem({
- 'image/png': pngBlob
- })
- ]);
-
- return true;
- } catch (error) {
- console.warn('单图复制失败:', error);
- return false;
- }
- }
-
- // 多张图片:使用 HTML 格式(包含所有图片的 base64)
+ // 处理冲突解决(统一处理粘贴、移动、上传)
+ const handleConflictResolveAll = useCallback(async (action) => {
+ await resolveConflict(action, async (resolvedAction, operation) => {
+ const { type, pendingOperation } = conflictDialog;
+
try {
- const imageDataList = await Promise.all(
- images.map(async (img) => {
- const imageUrl = `/api/image/original/${currentLibraryId}/${img.path}`;
- const response = await fetch(imageUrl);
- const blob = await response.blob();
-
- return new Promise((resolve) => {
- const reader = new FileReader();
- reader.onloadend = () => {
- resolve({
- dataUrl: reader.result,
- filename: img.filename
- });
- };
- reader.readAsDataURL(blob);
+ if (type === 'paste') {
+ await executePaste(pendingOperation.items, pendingOperation.targetFolder, resolvedAction);
+ } else if (type === 'move') {
+ await executeMove(pendingOperation.items, pendingOperation.targetFolder, resolvedAction);
+ // 注意:不在这里推入 undoStack,由外层的 handleMoveWithUndoStack 统一管理
+ } else if (type === 'upload') {
+ const result = await uploadWithConflictAction(
+ pendingOperation.files,
+ pendingOperation.targetFolder,
+ resolvedAction
+ );
+ if (result.success && !result.skipped) {
+ setUndoToast({
+ isVisible: true,
+ message: `上传完成: 成功 ${result.successCount} 个${result.failedCount > 0 ? `, 失败 ${result.failedCount} 个` : ''}`,
+ count: result.successCount
});
- })
- );
-
- // 创建 HTML 格式(使用 span 包裹每张图片,消除间距)
- const htmlContent = imageDataList.map(({ dataUrl, filename }) => `
`).join('');
-
- // 创建纯文本格式(文件名列表)
- const textContent = images.map(img => img.filename).join('\n');
-
- await navigator.clipboard.write([
- new ClipboardItem({
- 'text/html': new Blob([htmlContent], { type: 'text/html' }),
- 'text/plain': new Blob([textContent], { type: 'text/plain' })
- })
- ]);
-
- return true;
- } catch (error) {
- console.warn('多图复制失败:', error);
- return false;
- }
- } catch (error) {
- console.warn('写入系统剪贴板失败:', error);
- return false;
- }
- };
-
- // 复制到剪贴板(立即更新应用内剪贴板,异步写入系统剪贴板)
- const handleCopy = useCallback(() => {
- const imagesToCopy = selectedImages.length > 0
- ? selectedImages
- : selectedImage
- ? [selectedImage]
- : [];
-
- if (imagesToCopy.length === 0) return;
-
- // 1. 立即写入应用内剪贴板(用于应用内粘贴,同步操作)
- const itemsToCopy = imagesToCopy.map(img => ({ type: 'file', path: img.path, data: img }));
- copyToClipboard(itemsToCopy, 'copy');
- console.log(`📋 已复制 ${itemsToCopy.length} 个文件到应用内剪贴板`);
-
- // 2. 立即显示Toast
- setUndoToast({
- isVisible: true,
- message: `已复制 ${itemsToCopy.length} 个文件`,
- count: itemsToCopy.length
- });
-
- // 3秒后自动隐藏
- setTimeout(() => {
- setUndoToast({ isVisible: false, message: '', count: 0 });
- }, 3000);
-
- // 3. 异步写入系统剪贴板(用于跨应用粘贴,不阻塞)
- copyImagesToSystemClipboard(imagesToCopy).then(success => {
- if (success) {
- console.log(`✅ 已写入系统剪贴板,可粘贴到外部应用`);
- }
- });
- }, [selectedImages, selectedImage, copyToClipboard, currentLibraryId]);
-
- // 粘贴(先检查冲突)
- const handlePaste = useCallback(async () => {
- if (!currentLibraryId || !selectedFolder) return;
-
- const { items } = getClipboard();
- if (!items || items.length === 0) return;
-
- // 检查目标文件夹中是否存在同名文件(包括源文件本身)
- const targetFolderImages = images.filter(img => img.folder === selectedFolder);
- 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 === selectedFolder // 标记是否在同一位置
- });
- }
- }
-
- // 如果有冲突,显示对话框
- if (conflicts.length > 0) {
- setConflictDialog({
- isOpen: true,
- conflicts,
- pendingPaste: { items, targetFolder: selectedFolder }
- });
- } else {
- // 没有冲突,直接执行粘贴
- await executePaste(items, selectedFolder, 'rename');
- }
- }, [currentLibraryId, selectedFolder, getClipboard, images]);
-
- // 执行粘贴操作
- const executePaste = useCallback(async (items, targetFolder, conflictAction) => {
- if (!currentLibraryId) return;
-
- console.log(`📋 开始粘贴 ${items.length} 个文件到: ${targetFolder}`);
-
- // 1. 立即更新文件夹计数(乐观更新)
- const { folders, setFolders } = useImageStore.getState();
- const originalFolders = folders; // 保存用于回滚
-
- if (folders && folders.length > 0) {
- const updatedFolders = folders.map(folder => {
- // 更新目标文件夹及其所有父文件夹的计数
- if (folder.path === targetFolder || targetFolder.startsWith(folder.path + '/')) {
- return {
- ...folder,
- count: (folder.count || 0) + items.length
- };
- }
- return folder;
- });
- setFolders(updatedFolders);
- }
-
- // 2. 立即显示Toast
- setUndoToast({
- isVisible: true,
- message: `已粘贴 ${items.length} 个文件`,
- count: items.length
- });
-
- // 3秒后自动隐藏
- setTimeout(() => {
- setUndoToast({ isVisible: false, message: '', count: 0 });
- }, 3000);
-
- // 3. 后台执行API调用(串行,确保文件夹数据是最新的)
- (async () => {
- try {
- // 先执行复制
- const result = await fileAPI.copy(currentLibraryId, items, targetFolder, conflictAction);
-
- // 处理结果
- const successCount = result.success?.length || 0;
- const failedCount = result.failed?.length || 0;
-
- if (failedCount > 0) {
- // 有失败的项,更新Toast提示
- setUndoToast({
- isVisible: true,
- message: successCount > 0
- ? `已粘贴 ${successCount} 个文件,${failedCount} 个失败`
- : `粘贴失败: ${result.failed[0].error}`,
- count: successCount
- });
-
- setTimeout(() => {
- setUndoToast({ isVisible: false, message: '', count: 0 });
- }, 3000);
- }
-
- // 刷新当前文件夹的图片列表
- if (selectedFolder === targetFolder) {
- const params = { folder: selectedFolder };
- const response = await imageAPI.search(currentLibraryId, params);
- setImages(response.images);
- }
-
- // 复制完成后再刷新文件夹列表(确保拿到最新数据)
- const foldersRes = await imageAPI.getFolders(currentLibraryId);
- setFolders(foldersRes.folders);
- } catch (error) {
- console.error('粘贴失败:', error);
- // 失败时回滚文件夹计数
- setFolders(originalFolders);
- setUndoToast({ isVisible: false, message: '', count: 0 });
- alert('粘贴失败: ' + (error.message || '未知错误'));
- }
- })();
- }, [currentLibraryId, selectedFolder, setImages]);
-
- // 处理冲突对话框的选择
- const handleConflictResolve = useCallback(async (action) => {
- const { pendingPaste, pendingUpload } = conflictDialog;
-
- // 关闭对话框
- setConflictDialog({ isOpen: false, conflicts: [], pendingPaste: null, pendingUpload: null });
-
- if (pendingPaste) {
- // 粘贴冲突
- await executePaste(pendingPaste.items, pendingPaste.targetFolder, action);
- } else if (pendingUpload) {
- // 上传冲突 - 重新上传并带上 conflictAction 参数
- console.log(`处理上传冲突: ${action}`);
-
- if (action === 'skip') {
- // 跳过:不再上传
- console.log('用户选择跳过上传');
- return;
- }
-
- // 开始上传
- setUploadProgress({ isUploading: true, percent: 0, current: 0, total: pendingUpload.files.length });
-
- try {
- const result = await fileAPI.upload(
- currentLibraryId,
- pendingUpload.targetFolder,
- pendingUpload.files,
- (progressEvent) => {
- const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
- setUploadProgress(prev => ({ ...prev, percent }));
- },
- action // 传递 conflictAction
- );
-
- // 上传完成
- setUploadProgress({ isUploading: false, percent: 100, current: result.success.length, total: pendingUpload.files.length });
-
- // 显示结果提示
- const successCount = result.success?.length || 0;
- const failedCount = result.failed?.length || 0;
-
- let message = `上传完成: 成功 ${successCount} 个`;
- if (failedCount > 0) message += `, 失败 ${failedCount} 个`;
-
- setUndoToast({
- isVisible: true,
- message: message,
- count: successCount
- });
-
- setTimeout(() => {
- setUndoToast({ isVisible: false, message: '', count: 0 });
- setUploadProgress({ isUploading: false, percent: 0, current: 0, total: 0 });
- }, 3000);
-
- // 立即刷新当前文件夹的图片列表
- if (successCount > 0) {
- const params = { folder: selectedFolder || '' };
- const response = await imageAPI.search(currentLibraryId, params);
- setImages(response.images);
-
- // 刷新文件夹列表
- const foldersRes = await imageAPI.getFolders(currentLibraryId);
- setFolders(foldersRes.folders);
-
- // 2秒后再刷新一次,确保缩略图已生成
- setTimeout(async () => {
- try {
- const response2 = await imageAPI.search(currentLibraryId, params);
- setImages(response2.images);
- console.log('✅ 缩略图刷新完成');
- } catch (err) {
- console.error('刷新缩略图失败:', err);
- }
- }, 2000);
- }
- } catch (error) {
- console.error('上传失败:', error);
- setUploadProgress({ isUploading: false, percent: 0, current: 0, total: 0 });
- alert('上传失败: ' + (error.response?.data?.error || error.message || '未知错误'));
- }
- }
- }, [conflictDialog, executePaste, currentLibraryId, selectedFolder, setImages, setFolders]);
-
- // 取消冲突对话框
- const handleConflictCancel = useCallback(() => {
- setConflictDialog({ isOpen: false, conflicts: [], pendingPaste: null, pendingUpload: null });
- }, []);
-
- // 拖放事件处理 - 拖拽进入
- const handleDragEnter = useCallback((e) => {
- e.preventDefault();
- e.stopPropagation();
-
- // 关键修复:只检测外部文件拖入,排除应用内部拖动
- const types = e.dataTransfer.types;
- // 外部文件拖入的特征:包含 Files 且不包含 application/json
- const hasFiles = types.includes('Files');
- const hasJson = types.includes('application/json');
-
- if (hasFiles && !hasJson) {
- setIsDraggingOver(true);
- }
- }, []);
-
- // 拖放事件处理 - 拖拽悬停
- const handleDragOver = useCallback((e) => {
- e.preventDefault();
- e.stopPropagation();
-
- // 检查是否为外部文件
- const types = e.dataTransfer.types;
- const hasFiles = types.includes('Files');
- const hasJson = types.includes('application/json');
-
- if (hasFiles && !hasJson) {
- e.dataTransfer.dropEffect = 'copy';
- } else {
- e.dataTransfer.dropEffect = 'none';
- }
- }, []);
-
- // 拖放事件处理 - 拖拽离开(立即取消提示)
- const handleDragLeave = useCallback((e) => {
- e.preventDefault();
- e.stopPropagation();
-
- // 关键修复:离开容器区域立即取消提示
- const rect = containerRef.current?.getBoundingClientRect();
- if (rect) {
- const x = e.clientX;
- const y = e.clientY;
- // 检查鼠标是否离开容器区域
- if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
- setIsDraggingOver(false);
- }
- }
- }, []);
-
- // 拖放事件处理 - 文件放下
- const handleDrop = useCallback(async (e) => {
- e.preventDefault();
- e.stopPropagation();
- setIsDraggingOver(false);
-
- if (!currentLibraryId) {
- alert('请先选择素材库');
- return;
- }
-
- const files = Array.from(e.dataTransfer.files);
- if (files.length === 0) return;
-
- console.log(`📤 准备上传 ${files.length} 个文件到: ${selectedFolder || '根目录'}`);
-
- // 开始上传(不过滤格式,让后端处理)
- setUploadProgress({ isUploading: true, percent: 0, current: 0, total: files.length });
-
- try {
- const result = await fileAPI.upload(
- currentLibraryId,
- selectedFolder || '',
- files,
- (progressEvent) => {
- const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
- setUploadProgress(prev => ({ ...prev, percent }));
- }
- );
-
- // 上传完成
- setUploadProgress({ isUploading: false, percent: 100, current: result.success.length, total: files.length });
-
- // 检查是否有冲突
- const conflicts = result.conflicts || [];
- if (conflicts.length > 0) {
- // 有冲突,显示冲突对话框
- console.log(`⚠️ 检测到 ${conflicts.length} 个文件冲突`);
- setConflictDialog({
- isOpen: true,
- conflicts: conflicts,
- pendingUpload: {
- files: files.filter(f => {
- const filename = f.name;
- return conflicts.some(c => c.name === filename);
- }),
- targetFolder: selectedFolder || ''
+ setTimeout(() => setUndoToast({ isVisible: false, message: '', count: 0 }), 3000);
}
- });
- setUploadProgress({ isUploading: false, percent: 0, current: 0, total: 0 });
- return;
+ }
+ } catch (error) {
+ alert(`操作失败: ${error.message || '未知错误'}`);
}
+ });
+ }, [conflictDialog, resolveConflict, executePaste, executeMove, uploadWithConflictAction, setUndoToast]);
- // 显示结果提示
- const successCount = result.success?.length || 0;
- const failedCount = result.failed?.length || 0;
-
- let message = `上传完成: 成功 ${successCount} 个`;
- if (failedCount > 0) message += `, 失败 ${failedCount} 个`;
-
- setUndoToast({
- isVisible: true,
- message: message,
- count: successCount
- });
-
- setTimeout(() => {
- setUndoToast({ isVisible: false, message: '', count: 0 });
- setUploadProgress({ isUploading: false, percent: 0, current: 0, total: 0 });
- }, 3000);
-
- // 立即刷新当前文件夹的图片列表(不等待后台处理)
- if (successCount > 0) {
- // 立即刷新,让用户看到文件(缩略图可能还在生成中)
- const params = { folder: selectedFolder || '' };
- const response = await imageAPI.search(currentLibraryId, params);
- setImages(response.images);
-
- // 刷新文件夹列表
- const foldersRes = await imageAPI.getFolders(currentLibraryId);
- setFolders(foldersRes.folders);
-
- // 2秒后再刷新一次,确保缩略图已生成
- setTimeout(async () => {
- try {
- const response2 = await imageAPI.search(currentLibraryId, params);
- setImages(response2.images);
- console.log('✅ 缩略图刷新完成');
- } catch (err) {
- console.error('刷新缩略图失败:', err);
- }
- }, 2000);
- }
- } catch (error) {
- console.error('上传失败:', error);
- setUploadProgress({ isUploading: false, percent: 0, current: 0, total: 0 });
- alert('上传失败: ' + (error.response?.data?.error || error.message || '未知错误'));
- }
- }, [currentLibraryId, selectedFolder, setImages, setFolders]);
-
- // 开始重命名
- const handleStartRename = useCallback((image) => {
- if (!image) return;
- setRenamingImage(image);
- // 获取不带扩展名的文件名
- const nameWithoutExt = image.filename.substring(0, image.filename.lastIndexOf('.')) || image.filename;
- setEditingFilename(nameWithoutExt);
- // 延迟聚焦,确保输入框已渲染
- setTimeout(() => {
- if (editInputRef.current) {
- editInputRef.current.focus();
- editInputRef.current.select();
- }
- }, 50);
- }, [setRenamingImage]);
-
- // 完成重命名
- const handleFinishRename = useCallback(async () => {
- if (!renamingImage || !editingFilename.trim()) {
- setRenamingImage(null);
- setEditingFilename('');
- return;
- }
-
- const oldFilename = renamingImage.filename;
- const ext = oldFilename.substring(oldFilename.lastIndexOf('.'));
- const newFilename = editingFilename.trim() + ext;
-
- // 如果文件名没有改变,直接退出
- if (newFilename === oldFilename) {
- setRenamingImage(null);
- setEditingFilename('');
- return;
- }
-
- try {
- // 调用重命名API
- const result = await fileAPI.rename(currentLibraryId, renamingImage.path, newFilename);
-
- // 更新图片信息
- const newPath = result.newPath;
- const actualNewName = result.newName;
- updateImage(renamingImage.path, {
- path: newPath,
- filename: actualNewName
- });
-
- console.log(`✅ 重命名成功: ${oldFilename} → ${actualNewName}`);
- } catch (error) {
- console.error('重命名失败:', error);
- alert('重命名失败: ' + (error.message || '未知错误'));
- } finally {
- setRenamingImage(null);
- setEditingFilename('');
- }
- }, [renamingImage, editingFilename, currentLibraryId, updateImage]);
-
- // 取消重命名
- const handleCancelRename = useCallback(() => {
- setRenamingImage(null);
- setEditingFilename('');
- }, []);
-
- // 准备右键菜单选项
+ // 右键菜单选项
const getContextMenuOptions = useCallback((image) => {
const isMultiSelection = selectedImages.length > 0;
- const menuOptions = [];
-
- // 复制选项放在第一位
- menuOptions.push(
+ const menuOptions = [
menuItems.copy(() => {
setContextMenu({ isOpen: false, position: null, image: null });
- handleCopy();
+ const result = handleCopy();
+ if (result.success) {
+ setUndoToast({
+ isVisible: true,
+ message: `已复制 ${result.count} 个文件`,
+ count: result.count
+ });
+ setTimeout(() => setUndoToast({ isVisible: false, message: '', count: 0 }), 3000);
+ }
})
- );
+ ];
- // 只在单选时显示重命名选项
if (!isMultiSelection) {
menuOptions.push(
menuItems.rename(() => {
@@ -1418,7 +351,7 @@ function ImageWaterfall() {
}
menuOptions.push(
- menuItems.move(handleMoveClick),
+ menuItems.move(handlePrepareMove),
menuItems.delete(async () => {
setContextMenu({ isOpen: false, position: null, image: null });
await handleQuickDelete();
@@ -1426,150 +359,13 @@ function ImageWaterfall() {
);
return menuOptions;
- }, [selectedImages, selectedImage, handleMoveClick, handleStartRename, handleCopy]);
+ }, [selectedImages, handlePrepareMove, handleStartRename, handleCopy, handleQuickDelete, setUndoToast]);
- // 渲染单个图片单元格
- const renderImageCell = (image, flatIndex) => {
- const isSingleSelected = selectedImage?.id === image.id;
- const isMultiSelected = selectedImages.some(img => img.id === image.id);
- const isSelected = isSingleSelected || isMultiSelected;
-
- return (
-
-
handleImageClick(image, e, flatIndex)}
- onDoubleClick={() => {
- const fileType = image.fileType || 'image';
- if (fileType === 'image') {
- setPhotoIndex(flatIndex);
- } else {
- setViewerFile(image);
- }
- }}
- onContextMenu={(e) => handleContextMenu(e, image)}
- draggable={true}
- onDragStart={(e) => {
- // 准备拖拽的图片列表
- const draggedImages = selectedImages.length > 0 && selectedImages.some(img => img.id === image.id)
- ? selectedImages
- : [image];
-
- // 转换为 items 格式(type + path)
- const items = draggedImages.map(img => ({
- type: 'file',
- path: img.path
- }));
-
- e.dataTransfer.setData('application/json', JSON.stringify({ items }));
- e.dataTransfer.effectAllowed = 'move';
- }}
- >
-
)
{
- // 缩略图加载失败时显示占位符
- 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' && (
-
- {image.fileType === 'video' &&
}
- {image.fileType === 'audio' &&
}
- {image.fileType === 'document' &&
}
- {image.fileType === 'design' &&
}
- {image.fileType === 'other' &&
}
-
- {image.format || image.filename.split('.').pop()}
-
-
- )}
-
-
-
-
- {renamingImage?.id === image.id ? (
- // 编辑模式 - 保持与显示模式相同的样式,只添加下划线提示
-
setEditingFilename(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- handleFinishRename();
- } else if (e.key === 'Escape') {
- e.preventDefault();
- handleCancelRename();
- }
- }}
- onBlur={handleFinishRename}
- 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'
- }}
- />
- ) : (
- // 显示模式
-
{
- // 只在单选时允许双击重命名
- if (selectedImages.length === 0) {
- e.stopPropagation();
- handleStartRename(image);
- }
- }}
- title={selectedImages.length === 0 ? "双击重命名" : ""}
- >
- {image.filename}
-
- )}
-
-
- );
- };
-
- // 渲染一行(用于虚拟滚动)
- const renderRow = ({ index, style }) => {
+ // 渲染单行
+ const renderRow = useCallback(({ index, style }) => {
const row = rows[index];
if (!row) return null;
- // 计算该行之前的所有图片数量
let flatIndexBase = 0;
for (let i = 0; i < index; i++) {
flatIndexBase += rows[i]?.length || 0;
@@ -1577,66 +373,72 @@ function ImageWaterfall() {
return (
- {row.map((image, imageIndex) => renderImageCell(image, flatIndexBase + imageIndex))}
+ {row.map((image, imageIndex) => {
+ const flatIndex = flatIndexBase + imageIndex;
+ const isSingleSelected = selectedImage?.id === image.id;
+ const isMultiSelected = selectedImages.some(img => img.id === image.id);
+ const isSelected = isSingleSelected || isMultiSelected;
+
+ return (
+
+ );
+ })}
);
- };
+ }, [
+ rows,
+ selectedImage,
+ selectedImages,
+ renamingImage,
+ editingFilename,
+ getThumbnailUrl,
+ handleImageClick,
+ handleImageDoubleClick,
+ handleContextMenu,
+ handleDragStart,
+ handleStartRename,
+ handleFinishRename,
+ handleCancelRename
+ ]);
- // 加载中时显示空容器,避免闪烁"暂无图片"
- if (!filteredImages.length && imageLoadingState.isLoading) {
- return (
-
- {/* 拖拽提示覆盖层 */}
- {isDraggingOver && (
-
-
-
-
📤
-
- 拖放图片到这里
-
-
- 支持 JPG、PNG、GIF、WebP 等格式
-
-
-
-
- )}
-
- {/* 上传进度提示 */}
- {uploadProgress.isUploading && (
-
-
-
- 正在上传...
-
-
- {uploadProgress.percent}%
-
-
-
-
- 共 {uploadProgress.total} 个文件
-
-
- )}
-
- );
- }
+ // 虚拟列表更新
+ useRef(() => {
+ if (listRef.current && filteredImages.length > VIRTUAL_SCROLL_THRESHOLD) {
+ const prevRowCount = prevRowCountRef.current;
+ const currRowCount = rows.length;
+
+ if (currRowCount > prevRowCount && prevRowCount > 0) {
+ const resetIndex = Math.max(0, prevRowCount - 1);
+ listRef.current.resetAfterIndex(resetIndex);
+ } else if (currRowCount !== prevRowCount) {
+ listRef.current.resetAfterIndex(0);
+ }
+
+ prevRowCountRef.current = currRowCount;
+ }
+ }, [rows, filteredImages.length]);
- // 真正没有图片时才显示提示
+ // 是否启用虚拟滚动
+ const useVirtualScroll = filteredImages.length > VIRTUAL_SCROLL_THRESHOLD;
+
+ // 空状态
if (!filteredImages.length) {
return (
- {/* 拖拽提示覆盖层 */}
- {isDraggingOver && (
-
-
-
-
📤
-
- 拖放图片到这里
-
-
- 支持 JPG、PNG、GIF、WebP 等格式
-
-
-
-
- )}
-
- {/* 上传进度提示 */}
- {uploadProgress.isUploading && (
-
-
-
- 正在上传...
-
-
- {uploadProgress.percent}%
-
-
-
-
- 共 {uploadProgress.total} 个文件
-
-
- )}
-
-
-
暂无图片
-
请添加素材库或调整搜索条件
-
可以直接拖拽文件到这里上传
-
+
+
+
);
}
// 等待容器宽度初始化
if (!containerWidth && filteredImages.length > 0) {
- return (
-
- );
+ return ;
}
return (
@@ -1712,45 +470,8 @@ function ImageWaterfall() {
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
- {/* 拖拽提示覆盖层 */}
- {isDraggingOver && (
-
-
-
-
📤
-
- 拖放图片到这里
-
-
- 支持 JPG、PNG、GIF、WebP 等格式
-
-
-
-
- )}
-
- {/* 上传进度提示 */}
- {uploadProgress.isUploading && (
-
-
-
- 正在上传...
-
-
- {uploadProgress.percent}%
-
-
-
-
- 共 {uploadProgress.total} 个文件
-
-
- )}
+
+
{useVirtualScroll ? (
- /* 虚拟滚动模式 */
{
- // 向下滚动:接近底部时加载更多
if (scrollDirection === 'forward' && imageLoadingState.hasMore && !imageLoadingState.isLoading) {
const totalHeight = rows.reduce((sum, _, i) => sum + getRowHeight(i), 0);
const scrollBottom = scrollOffset + (containerHeight || 600);
- if (totalHeight - scrollBottom < LOAD_CONFIG.preloadThreshold) {
+ if (totalHeight - scrollBottom < preloadThreshold) {
loadMoreImages();
}
}
@@ -1783,14 +502,12 @@ function ImageWaterfall() {
{renderRow}
) : (
- /* 普通渲染模式(≤500张图片) */
{
- // 向下滚动:接近底部时加载更多
if (imageLoadingState.hasMore && !imageLoadingState.isLoading) {
const { scrollTop, scrollHeight, clientHeight } = e.target;
- if (scrollHeight - scrollTop - clientHeight < LOAD_CONFIG.preloadThreshold) {
+ if (scrollHeight - scrollTop - clientHeight < preloadThreshold) {
loadMoreImages();
}
}
@@ -1804,7 +521,33 @@ function ImageWaterfall() {
}
return (
- {row.map((image, imageIndex) => renderImageCell(image, flatIndexBase + imageIndex))}
+ {row.map((image, imageIndex) => {
+ const flatIndex = flatIndexBase + imageIndex;
+ const isSingleSelected = selectedImage?.id === image.id;
+ const isMultiSelected = selectedImages.some(img => img.id === image.id);
+ const isSelected = isSingleSelected || isMultiSelected;
+
+ return (
+
+ );
+ })}
);
})}
@@ -1835,10 +578,15 @@ function ImageWaterfall() {
isVisible={undoToast.isVisible}
message={undoToast.message}
onUndo={handleUndo}
- onClose={() => {
- setUndoToast({ isVisible: false, message: '', count: 0 });
- // 不清空历史栈,允许Toast消失后仍可Ctrl+Z
- }}
+ onClose={() => setUndoToast({ isVisible: false, message: '', count: 0 })}
+ />
+
+ {/* 撤销移动提示 */}
+
setMoveUndoToast({ isVisible: false, message: '', count: 0 })}
/>
{/* 评分提醒 */}
@@ -1854,11 +602,8 @@ function ImageWaterfall() {
{
- setShowFolderSelector(false);
- setMoveItems([]);
- }}
+ onSelect={handleMoveWithUndoStack}
+ onClose={handleCancelMove}
/>
)}
@@ -1866,8 +611,8 @@ function ImageWaterfall() {
);
diff --git a/frontend/src/components/MainContent.jsx b/frontend/src/components/MainContent.jsx
index 4e0f41e..2787fd9 100644
--- a/frontend/src/components/MainContent.jsx
+++ b/frontend/src/components/MainContent.jsx
@@ -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();
diff --git a/frontend/src/components/RightPanel.jsx b/frontend/src/components/RightPanel.jsx
index 94f6a28..d86934e 100644
--- a/frontend/src/components/RightPanel.jsx
+++ b/frontend/src/components/RightPanel.jsx
@@ -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';
}}
/>
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 00f3372..464b5fd 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -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() {
{/* 撤销删除提示 */}
{
@@ -1458,6 +1665,16 @@ function Sidebar() {
}}
/>
+ {/* 撤销拖拽移动提示 */}
+ 0}
+ message={undoToast.message}
+ onUndo={handleUndoDragMove}
+ onClose={() => {
+ setUndoToast({ isVisible: false, message: '', count: 0 });
+ }}
+ />
+
{/* 文件夹选择器 */}
{showFolderSelector && (
)}
+
+ {/* 冲突处理对话框 */}
+
);
}
diff --git a/frontend/src/components/UploadProgress.jsx b/frontend/src/components/UploadProgress.jsx
new file mode 100644
index 0000000..5622b02
--- /dev/null
+++ b/frontend/src/components/UploadProgress.jsx
@@ -0,0 +1,33 @@
+/**
+ * 上传进度提示组件
+ */
+
+const UploadProgress = ({ progress }) => {
+ const { isUploading, percent, total } = progress;
+
+ if (!isUploading) return null;
+
+ return (
+
+
+
+ 正在上传...
+
+
+ {percent}%
+
+
+
+
+ 共 {total} 个文件
+
+
+ );
+};
+
+export default UploadProgress;
diff --git a/frontend/src/hooks/useConflictHandler.js b/frontend/src/hooks/useConflictHandler.js
new file mode 100644
index 0000000..95f097a
--- /dev/null
+++ b/frontend/src/hooks/useConflictHandler.js
@@ -0,0 +1,79 @@
+/**
+ * 统一的冲突处理 Hook
+ * 用于复制、粘贴、移动、上传等操作的冲突处理
+ */
+
+import { useState, useCallback } from 'react';
+
+/**
+ * 冲突类型
+ */
+export const ConflictType = {
+ PASTE: 'paste', // 粘贴冲突
+ MOVE: 'move', // 移动冲突
+ UPLOAD: 'upload', // 上传冲突
+};
+
+/**
+ * 冲突处理 Hook
+ * @returns {Object} 冲突处理相关的状态和方法
+ */
+export const useConflictHandler = () => {
+ const [conflictDialog, setConflictDialog] = useState({
+ isOpen: false,
+ conflicts: [],
+ type: null, // 冲突类型: 'paste' | 'move' | 'upload'
+ pendingOperation: null // 待执行的操作数据
+ });
+
+ /**
+ * 显示冲突对话框
+ * @param {Array} conflicts - 冲突列表 [{path, name, isSameLocation}]
+ * @param {string} type - 冲突类型
+ * @param {Object} operationData - 操作数据
+ */
+ const showConflictDialog = useCallback((conflicts, type, operationData) => {
+ setConflictDialog({
+ isOpen: true,
+ conflicts,
+ type,
+ pendingOperation: operationData
+ });
+ }, []);
+
+ /**
+ * 隐藏冲突对话框
+ */
+ const hideConflictDialog = useCallback(() => {
+ setConflictDialog({
+ isOpen: false,
+ conflicts: [],
+ type: null,
+ pendingOperation: null
+ });
+ }, []);
+
+ /**
+ * 处理冲突解决
+ * @param {string} action - 解决方式: 'skip' | 'replace' | 'rename'
+ * @param {Function} onResolve - 解决后的回调函数
+ */
+ const resolveConflict = useCallback(async (action, onResolve) => {
+ const { pendingOperation } = conflictDialog;
+
+ // 关闭对话框
+ hideConflictDialog();
+
+ // 执行回调
+ if (onResolve && pendingOperation) {
+ await onResolve(action, pendingOperation);
+ }
+ }, [conflictDialog, hideConflictDialog]);
+
+ return {
+ conflictDialog,
+ showConflictDialog,
+ hideConflictDialog,
+ resolveConflict
+ };
+};
diff --git a/frontend/src/hooks/useImageClipboard.js b/frontend/src/hooks/useImageClipboard.js
new file mode 100644
index 0000000..54f450c
--- /dev/null
+++ b/frontend/src/hooks/useImageClipboard.js
@@ -0,0 +1,261 @@
+/**
+ * 图片剪贴板操作 Hook(重构版 - 使用统一冲突处理)
+ */
+
+import { useCallback } from 'react';
+import { useImageStore } from '../stores/useImageStore';
+import { useLibraryStore } from '../stores/useLibraryStore';
+import { useClipboardStore } from '../stores/useClipboardStore';
+import { fileAPI, imageAPI } from '../api';
+import { createLogger } from '../utils/logger';
+
+const logger = createLogger('useImageClipboard');
+
+/**
+ * 图片剪贴板功能(复制粘贴)
+ * @param {Function} showConflictDialog - 显示冲突对话框的回调
+ * @returns {Object} 剪贴板相关的状态和方法
+ */
+export const useImageClipboard = (showConflictDialog) => {
+ const { currentLibraryId } = useLibraryStore();
+ const {
+ selectedImage, selectedImages, images, setImages,
+ selectedFolder, folders, setFolders
+ } = useImageStore();
+ const { copyToClipboard, getClipboard } = useClipboardStore();
+
+ /**
+ * 复制图片到系统剪贴板(支持多图,使用 HTML 格式)
+ */
+ const copyImagesToSystemClipboard = useCallback(async (images) => {
+ try {
+ // 检查 Clipboard API 是否可用
+ if (typeof ClipboardItem === 'undefined' || !navigator.clipboard || typeof navigator.clipboard.write !== 'function') {
+ logger.warn('系统剪贴板 API 不可用');
+ return false;
+ }
+
+ if (images.length === 0) return false;
+
+ // 单张图片:直接复制为 PNG
+ if (images.length === 1) {
+ try {
+ const img = images[0];
+ const imageUrl = `/api/image/original/${currentLibraryId}/${img.path}`;
+ const response = await fetch(imageUrl);
+ const blob = await response.blob();
+
+ // 转换为 PNG
+ const canvas = document.createElement('canvas');
+ const image = new Image();
+
+ await new Promise((resolve, reject) => {
+ image.onload = resolve;
+ image.onerror = reject;
+ image.src = URL.createObjectURL(blob);
+ });
+
+ canvas.width = image.width;
+ canvas.height = image.height;
+ const ctx = canvas.getContext('2d');
+ ctx.drawImage(image, 0, 0);
+
+ URL.revokeObjectURL(image.src);
+
+ const pngBlob = await new Promise((resolve) => {
+ canvas.toBlob(resolve, 'image/png');
+ });
+
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ 'image/png': pngBlob
+ })
+ ]);
+
+ return true;
+ } catch (error) {
+ logger.warn('单图复制失败:', error);
+ return false;
+ }
+ }
+
+ // 多张图片:使用 HTML 格式(包含所有图片的 base64)
+ try {
+ const imageDataList = await Promise.all(
+ images.map(async (img) => {
+ const imageUrl = `/api/image/original/${currentLibraryId}/${img.path}`;
+ const response = await fetch(imageUrl);
+ const blob = await response.blob();
+
+ return new Promise((resolve) => {
+ const reader = new FileReader();
+ reader.onloadend = () => {
+ resolve({
+ dataUrl: reader.result,
+ filename: img.filename
+ });
+ };
+ reader.readAsDataURL(blob);
+ });
+ })
+ );
+
+ // 创建 HTML 格式(使用 span 包裹每张图片,消除间距)
+ const htmlContent = imageDataList.map(({ dataUrl, filename }) =>
+ `
`
+ ).join('');
+
+ // 创建纯文本格式(文件名列表)
+ const textContent = images.map(img => img.filename).join('\n');
+
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ 'text/html': new Blob([htmlContent], { type: 'text/html' }),
+ 'text/plain': new Blob([textContent], { type: 'text/plain' })
+ })
+ ]);
+
+ return true;
+ } catch (error) {
+ logger.warn('多图复制失败:', error);
+ return false;
+ }
+ } catch (error) {
+ logger.warn('写入系统剪贴板失败:', error);
+ return false;
+ }
+ }, [currentLibraryId]);
+
+ /**
+ * 复制到剪贴板(立即更新应用内剪贴板,异步写入系统剪贴板)
+ */
+ const handleCopy = useCallback(() => {
+ const imagesToCopy = selectedImages.length > 0
+ ? selectedImages
+ : selectedImage
+ ? [selectedImage]
+ : [];
+
+ if (imagesToCopy.length === 0) return;
+
+ // 1. 立即写入应用内剪贴板(用于应用内粘贴,同步操作)
+ const itemsToCopy = imagesToCopy.map(img => ({ type: 'file', path: img.path, data: img }));
+ copyToClipboard(itemsToCopy, 'copy');
+ logger.debug(`📋 已复制 ${itemsToCopy.length} 个文件到应用内剪贴板`);
+
+ // 2. 异步写入系统剪贴板(用于跨应用粘贴,不阻塞)
+ copyImagesToSystemClipboard(imagesToCopy).then(success => {
+ if (success) {
+ logger.debug(`✅ 已写入系统剪贴板,可粘贴到外部应用`);
+ }
+ });
+
+ return { success: true, count: itemsToCopy.length };
+ }, [selectedImages, selectedImage, copyToClipboard, copyImagesToSystemClipboard]);
+
+ /**
+ * 检查粘贴冲突
+ */
+ const checkPasteConflicts = useCallback((items, targetFolder) => {
+ const targetFolderImages = images.filter(img => img.folder === targetFolder);
+ 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 === targetFolder
+ });
+ }
+ }
+
+ return conflicts;
+ }, [images]);
+
+ /**
+ * 执行粘贴操作
+ */
+ const executePaste = useCallback(async (items, targetFolder, conflictAction) => {
+ if (!currentLibraryId) return;
+
+ logger.debug(`📋 开始粘贴 ${items.length} 个文件到: ${targetFolder}`);
+
+ // 1. 立即更新文件夹计数(乐观更新)
+ const originalFolders = folders;
+
+ if (folders && folders.length > 0) {
+ const updatedFolders = folders.map(folder => {
+ if (folder.path === targetFolder || targetFolder.startsWith(folder.path + '/')) {
+ return {
+ ...folder,
+ count: (folder.count || 0) + items.length
+ };
+ }
+ return folder;
+ });
+ setFolders(updatedFolders);
+ }
+
+ // 2. 后台执行API调用
+ try {
+ const result = await fileAPI.copy(currentLibraryId, items, targetFolder, conflictAction);
+
+ const successCount = result.success?.length || 0;
+ const failedCount = result.failed?.length || 0;
+
+ // 刷新当前文件夹的图片列表
+ if (selectedFolder === targetFolder) {
+ const params = { folder: selectedFolder };
+ const response = await imageAPI.search(currentLibraryId, params);
+ setImages(response.images);
+ }
+
+ // 刷新文件夹列表
+ const foldersRes = await imageAPI.getFolders(currentLibraryId);
+ setFolders(foldersRes.folders);
+
+ return { success: true, successCount, failedCount };
+ } catch (error) {
+ logger.error('粘贴失败:', error);
+ // 失败时回滚文件夹计数
+ setFolders(originalFolders);
+ throw error;
+ }
+ }, [currentLibraryId, selectedFolder, folders, setImages, setFolders]);
+
+ /**
+ * 粘贴(先检查冲突)
+ */
+ const handlePaste = useCallback(async () => {
+ if (!currentLibraryId || !selectedFolder) return;
+
+ const { items } = getClipboard();
+ if (!items || items.length === 0) return;
+
+ // 检查冲突
+ const conflicts = checkPasteConflicts(items, selectedFolder);
+
+ if (conflicts.length > 0 && showConflictDialog) {
+ // 有冲突,显示对话框
+ showConflictDialog(conflicts, 'paste', {
+ items,
+ targetFolder: selectedFolder
+ });
+ } else {
+ // 没有冲突,直接执行粘贴
+ await executePaste(items, selectedFolder, 'rename');
+ }
+ }, [currentLibraryId, selectedFolder, getClipboard, checkPasteConflicts, showConflictDialog, executePaste]);
+
+ return {
+ handleCopy,
+ handlePaste,
+ executePaste
+ };
+};
diff --git a/frontend/src/hooks/useImageDelete.js b/frontend/src/hooks/useImageDelete.js
new file mode 100644
index 0000000..9132655
--- /dev/null
+++ b/frontend/src/hooks/useImageDelete.js
@@ -0,0 +1,204 @@
+/**
+ * 图片删除和撤销 Hook
+ */
+
+import { useState, useCallback } from 'react';
+import { useImageStore } from '../stores/useImageStore';
+import { useLibraryStore } from '../stores/useLibraryStore';
+import { fileAPI, imageAPI } from '../api';
+import { createLogger } from '../utils/logger';
+
+const logger = createLogger('useImageDelete');
+
+/**
+ * 图片删除和撤销功能
+ * @returns {Object} 删除相关的状态和方法
+ */
+export const useImageDelete = () => {
+ const { currentLibraryId } = useLibraryStore();
+ const {
+ images, setImages, selectedImage, selectedImages,
+ clearSelection, folders, setFolders, selectedFolder
+ } = useImageStore();
+
+ const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈,支持多次撤销
+ const [undoToast, setUndoToast] = useState({ isVisible: false, message: '', count: 0 });
+
+ /**
+ * 快速删除(乐观更新,立即响应)
+ */
+ const handleQuickDelete = useCallback(async () => {
+ const items = selectedImages.length > 0
+ ? selectedImages.map(img => ({ type: 'file', path: img.path }))
+ : selectedImage
+ ? [{ type: 'file', path: selectedImage.path }]
+ : [];
+
+ if (items.length === 0) return;
+
+ // 保存被删除的图片信息(乐观更新)
+ const deletingPaths = new Set(items.map(item => item.path));
+ const deletedImagesList = images.filter(img => deletingPaths.has(img.path));
+
+ // 1. 立即更新UI(乐观更新)- 最快的响应
+ const remainingImages = images.filter(img => !deletingPaths.has(img.path));
+ setImages(remainingImages);
+ clearSelection();
+
+ // 2. 立即更新文件夹计数(乐观更新)
+ if (folders && folders.length > 0) {
+ const updatedFolders = folders.map(folder => {
+ // 计算该文件夹下被删除的图片数量
+ const deletedInFolder = deletedImagesList.filter(img =>
+ img.folder === folder.path || img.folder?.startsWith(folder.path + '/')
+ ).length;
+
+ if (deletedInFolder > 0) {
+ return {
+ ...folder,
+ count: Math.max(0, (folder.count || 0) - deletedInFolder)
+ };
+ }
+ return folder;
+ });
+ setFolders(updatedFolders);
+ }
+
+ // 3. 推入历史栈
+ const newHistory = [...undoHistory, {
+ images: deletedImagesList,
+ paths: Array.from(deletingPaths),
+ items: items
+ }];
+ setUndoHistory(newHistory);
+
+ // 4. 显示Toast(立即显示)
+ setUndoToast({
+ isVisible: true,
+ message: `已将 ${items.length} 个文件移入临时文件夹(Ctrl+Z撤销 · ${newHistory.length}次)`,
+ count: items.length
+ });
+
+ // 5. 后台执行API调用(不阻塞UI)
+ Promise.all([
+ fileAPI.delete(currentLibraryId, items),
+ imageAPI.getFolders(currentLibraryId)
+ ]).then(([deleteResult, foldersRes]) => {
+ // 检查是否有失败的项
+ if (deleteResult.failed.length > 0) {
+ logger.warn(`⚠️ 删除失败: ${deleteResult.failed.length} 个文件`, deleteResult.failed);
+ // 如果有失败,回滚UI
+ setImages(images);
+ setUndoHistory(undoHistory);
+ setUndoToast({ isVisible: false, message: '', count: 0 });
+ setFolders(foldersRes.folders);
+ alert('删除失败: 部分文件无法删除');
+ } else {
+ // 成功时刷新文件夹列表(但已经被乐观更新了,这里主要是确保同步)
+ setFolders(foldersRes.folders);
+ }
+ }).catch(error => {
+ logger.error('删除失败:', error);
+ // 失败时回滚UI
+ setImages(images);
+ setUndoHistory(undoHistory);
+ setUndoToast({ isVisible: false, message: '', count: 0 });
+ imageAPI.getFolders(currentLibraryId).then(foldersRes => {
+ setFolders(foldersRes.folders);
+ });
+ alert('删除失败: ' + (error.message || '未知错误'));
+ });
+ }, [selectedImages, selectedImage, images, currentLibraryId, undoHistory, folders, setImages, clearSelection, setFolders]);
+
+ /**
+ * 撤销删除 - 乐观更新,立即响应
+ */
+ const handleUndo = useCallback(async () => {
+ if (undoHistory.length === 0) return;
+
+ // 从历史栈中取出最近的删除记录
+ const lastDeleted = undoHistory[undoHistory.length - 1];
+ const remainingHistory = undoHistory.slice(0, -1);
+
+ // 1. 立即关闭Toast
+ setUndoToast({ isVisible: false, message: '', count: 0 });
+
+ // 2. 立即更新历史栈
+ setUndoHistory(remainingHistory);
+
+ // 3. 获取被恢复文件的文件夹路径
+ const restoredFolder = lastDeleted.images[0]?.folder || null;
+
+ // 4. 立即更新文件夹计数(乐观更新)
+ if (folders && folders.length > 0) {
+ const updatedFolders = folders.map(folder => {
+ // 计算该文件夹下恢复的图片数量
+ const restoredInFolder = lastDeleted.images.filter(img =>
+ img.folder === folder.path || img.folder?.startsWith(folder.path + '/')
+ ).length;
+
+ if (restoredInFolder > 0) {
+ return {
+ ...folder,
+ count: (folder.count || 0) + restoredInFolder
+ };
+ }
+ return folder;
+ });
+ setFolders(updatedFolders);
+ }
+
+ // 5. 立即恢复图片到UI(乐观更新)
+ if (restoredFolder && restoredFolder !== selectedFolder) {
+ // 跨文件夹:先跳转,让文件夹加载自然显示图片
+ useImageStore.getState().setSelectedFolder(restoredFolder);
+ logger.debug(`📂 跳转到文件夹: ${restoredFolder}`);
+ } else {
+ // 同文件夹:立即添加到列表
+ const restoredImages = [...images, ...lastDeleted.images];
+ setImages(restoredImages);
+ }
+
+ // 6. 后台执行API调用(不阻塞UI)
+ Promise.all([
+ fileAPI.restore(currentLibraryId, lastDeleted.items),
+ imageAPI.getFolders(currentLibraryId)
+ ]).then(([restoreResult, foldersRes]) => {
+ // 检查恢复结果
+ if (restoreResult.failed.length > 0) {
+ logger.warn(`⚠️ 恢复失败: ${restoreResult.failed.length} 个文件`);
+ const errorMsg = restoreResult.failed[0].error || '未知错误';
+
+ // 失败时回滚UI
+ setUndoHistory(undoHistory);
+ if (restoredFolder === selectedFolder) {
+ setImages(images);
+ }
+ setFolders(foldersRes.folders);
+ alert(`恢复失败: ${errorMsg}\n\n提示:超过5分钟的文件已移入系统回收站,请手动从回收站恢复。`);
+ } else {
+ // 成功时刷新文件夹列表以确保同步
+ setFolders(foldersRes.folders);
+ }
+ }).catch(error => {
+ logger.error('恢复失败:', error);
+ // 失败时回滚
+ setUndoHistory(undoHistory);
+ if (restoredFolder === selectedFolder) {
+ setImages(images);
+ }
+ imageAPI.getFolders(currentLibraryId).then(foldersRes => {
+ setFolders(foldersRes.folders);
+ });
+ alert('恢复失败: ' + (error.message || '未知错误'));
+ });
+ }, [undoHistory, currentLibraryId, images, selectedFolder, folders, setImages, setFolders]);
+
+ return {
+ undoHistory,
+ undoToast,
+ setUndoToast,
+ handleQuickDelete,
+ handleUndo
+ };
+};
diff --git a/frontend/src/hooks/useImageKeyboard.js b/frontend/src/hooks/useImageKeyboard.js
new file mode 100644
index 0000000..b33efb5
--- /dev/null
+++ b/frontend/src/hooks/useImageKeyboard.js
@@ -0,0 +1,121 @@
+/**
+ * 图片键盘快捷键 Hook
+ */
+
+import { useEffect } from 'react';
+import { useImageStore } from '../stores/useImageStore';
+import { useClipboardStore } from '../stores/useClipboardStore';
+
+/**
+ * 键盘快捷键处理
+ * @param {Object} handlers - 快捷键处理函数
+ * @returns {void}
+ */
+export const useImageKeyboard = (handlers) => {
+ const { selectedImage, selectedImages } = useImageStore();
+ const { hasClipboard } = useClipboardStore();
+
+ const {
+ onDelete,
+ onUndo,
+ onCopy,
+ onPaste,
+ onRename,
+ onRating,
+ canUndo = false,
+ canPaste = false
+ } = handlers;
+
+ useEffect(() => {
+ const handleGlobalKeyDown = async (e) => {
+ // 忽略输入框中的快捷键
+ if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
+
+ // Ctrl+C → 复制
+ if ((e.ctrlKey || e.metaKey) && e.key === 'c') {
+ if (selectedImages.length > 0 || selectedImage) {
+ e.preventDefault();
+ onCopy?.();
+ }
+ return;
+ }
+
+ // Ctrl+V → 粘贴
+ if ((e.ctrlKey || e.metaKey) && e.key === 'v') {
+ if (hasClipboard() && canPaste) {
+ e.preventDefault();
+ await onPaste?.();
+ }
+ return;
+ }
+
+ // Ctrl+Z → 撤销
+ // 只有在有可撤销的【图片】操作时,才拦截并阻止事件继续传播,避免 Sidebar 的全局监听同一按键再次处理
+ // 当没有图片撤销时,保持事件传播,让 Sidebar 处理文件夹删除/拖拽移动等撤销
+ if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
+ if (canUndo) {
+ e.preventDefault();
+ // 阻止后续监听器(例如 Sidebar 的 window.keydown)处理本次 Ctrl+Z
+ if (typeof e.stopImmediatePropagation === 'function') {
+ e.stopImmediatePropagation();
+ } else if (typeof e.stopPropagation === 'function') {
+ e.stopPropagation();
+ }
+ await onUndo?.();
+ }
+ // 如果没有可撤销的图片操作,则不拦截,让其他监听器处理
+ return;
+ }
+
+ // F2 或 Enter → 重命名(仅单选时)
+ if ((e.key === 'F2' || e.key === 'Enter') && selectedImage && selectedImages.length === 0) {
+ e.preventDefault();
+ onRename?.(selectedImage);
+ return;
+ }
+
+ // Del 键 → 删除
+ if (e.key === 'Delete') {
+ if (selectedImages.length > 0 || selectedImage) {
+ e.preventDefault();
+ await onDelete?.();
+ }
+ return;
+ }
+
+ // 数字键 1-5 → 快速评分
+ if (['1', '2', '3', '4', '5'].includes(e.key)) {
+ if (selectedImages.length > 0 || selectedImage) {
+ e.preventDefault();
+ const rating = parseInt(e.key);
+ await onRating?.(rating);
+ }
+ return;
+ }
+
+ // 数字键 0 → 取消评分
+ if (e.key === '0') {
+ if (selectedImages.length > 0 || selectedImage) {
+ e.preventDefault();
+ await onRating?.(0);
+ }
+ return;
+ }
+ };
+
+ window.addEventListener('keydown', handleGlobalKeyDown);
+ return () => window.removeEventListener('keydown', handleGlobalKeyDown);
+ }, [
+ selectedImages,
+ selectedImage,
+ hasClipboard,
+ canUndo,
+ canPaste,
+ onDelete,
+ onUndo,
+ onCopy,
+ onPaste,
+ onRename,
+ onRating
+ ]);
+};
diff --git a/frontend/src/hooks/useImageMove.js b/frontend/src/hooks/useImageMove.js
new file mode 100644
index 0000000..dee8f70
--- /dev/null
+++ b/frontend/src/hooks/useImageMove.js
@@ -0,0 +1,337 @@
+/**
+ * 图片/文件夹移动 Hook
+ */
+
+import { useState, useCallback } from 'react';
+import { useImageStore } from '../stores/useImageStore';
+import { useLibraryStore } from '../stores/useLibraryStore';
+import { fileAPI, imageAPI } from '../api';
+import { createLogger } from '../utils/logger';
+
+const logger = createLogger('useImageMove');
+
+/**
+ * 图片/文件夹移动功能
+ * @param {Function} showConflictDialog - 显示冲突对话框的回调
+ * @returns {Object} 移动相关的状态和方法
+ */
+export const useImageMove = (showConflictDialog) => {
+ const { currentLibraryId } = useLibraryStore();
+ const {
+ images, setImages, selectedImage, selectedImages,
+ clearSelection, folders, setFolders, selectedFolder, setSelectedFolder
+ } = useImageStore();
+
+ const [showFolderSelector, setShowFolderSelector] = useState(false);
+ const [moveItems, setMoveItems] = useState([]);
+ const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈
+ const [undoToast, setUndoToast] = useState({ isVisible: false, message: '', count: 0 });
+
+ /**
+ * 打开文件夹选择器(准备移动)
+ */
+ const handleMoveClick = useCallback((itemsToMove) => {
+ if (!itemsToMove || itemsToMove.length === 0) return;
+
+ setMoveItems(itemsToMove);
+ setShowFolderSelector(true);
+ }, []);
+
+ /**
+ * 检查目标文件夹是否存在冲突
+ */
+ const checkMoveConflicts = useCallback(async (itemsToMove, targetFolder) => {
+ if (!currentLibraryId) return [];
+
+ try {
+ // 从后端获取目标文件夹的图片列表
+ const response = await imageAPI.search(currentLibraryId, { folder: targetFolder });
+ const targetFolderImages = response.images || [];
+ const conflicts = [];
+
+ for (const item of itemsToMove) {
+ 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 === targetFolder
+ });
+ }
+ }
+
+ return conflicts;
+ } catch (error) {
+ logger.error('检查移动冲突失败:', error);
+ return [];
+ }
+ }, [currentLibraryId]);
+
+ /**
+ * 执行移动操作
+ */
+ const executeMove = useCallback(async (items, targetFolder, conflictAction = 'rename') => {
+ if (!currentLibraryId) return;
+
+ logger.debug(`📁 开始移动 ${items.length} 个文件到: ${targetFolder}`);
+
+ // 1. 立即从当前列表中移除这些图片(乐观更新)
+ const movedPaths = new Set(items.map(item => item.path));
+ const remainingImages = images.filter(img => !movedPaths.has(img.path));
+ setImages(remainingImages);
+ clearSelection();
+
+ // 2. 立即更新文件夹计数(乐观更新)
+ const originalFolders = folders; // 保存用于回滚
+
+ if (folders && folders.length > 0) {
+ const movedImages = images.filter(img => movedPaths.has(img.path));
+
+ const updatedFolders = folders.map(folder => {
+ // 减少源文件夹计数
+ const movedFromFolder = movedImages.filter(img =>
+ img.folder === folder.path || img.folder?.startsWith(folder.path + '/')
+ ).length;
+
+ // 增加目标文件夹计数
+ const movedToFolder = (folder.path === targetFolder || targetFolder.startsWith(folder.path + '/'))
+ ? items.length
+ : 0;
+
+ const newCount = (folder.count || 0) - movedFromFolder + movedToFolder;
+
+ if (movedFromFolder > 0 || movedToFolder > 0) {
+ return {
+ ...folder,
+ count: Math.max(0, newCount)
+ };
+ }
+ return folder;
+ });
+ setFolders(updatedFolders);
+ }
+
+ // 3. 保存移动记录(用于撤销)
+ const movedImagesList = images.filter(img => movedPaths.has(img.path));
+ const sourceFolders = new Map();
+ movedImagesList.forEach(img => {
+ sourceFolders.set(img.path, img.folder);
+ });
+
+ // 4. 后台执行API调用
+ try {
+ const result = await fileAPI.move(currentLibraryId, items, targetFolder, conflictAction);
+
+ const successCount = result.success?.length || 0;
+ const failedCount = result.failed?.length || 0;
+
+ // 5. 推入历史栈(用于撤销)
+ if (successCount > 0) {
+ const newHistory = [...undoHistory, {
+ items,
+ targetFolder,
+ sourceFolders: Array.from(sourceFolders.entries()),
+ images: movedImagesList
+ }];
+ setUndoHistory(newHistory);
+
+ // 显示撤销提示
+ setUndoToast({
+ isVisible: true,
+ message: `已移动 ${successCount} 个文件`,
+ count: successCount
+ });
+
+ // 3秒后自动隐藏
+ setTimeout(() => {
+ setUndoToast({ isVisible: false, message: '', count: 0 });
+ }, 3000);
+ }
+
+ // 6. 刷新文件夹列表(确保数据同步)
+ const foldersRes = await imageAPI.getFolders(currentLibraryId);
+ setFolders(foldersRes.folders);
+
+ // 7. 刷新当前文件夹的图片列表(无论是源还是目标)
+ if (selectedFolder) {
+ const params = { folder: selectedFolder };
+ const response = await imageAPI.search(currentLibraryId, params);
+ setImages(response.images);
+ }
+
+ logger.debug(`✅ 移动完成: 成功 ${successCount} 个${failedCount > 0 ? `, 失败 ${failedCount} 个` : ''}`);
+
+ return { success: true, successCount, failedCount };
+ } catch (error) {
+ logger.error('移动失败:', error);
+ // 失败时回滚
+ setImages(images);
+ setFolders(originalFolders);
+ setUndoToast({ isVisible: false, message: '', count: 0 });
+ throw error;
+ }
+ }, [currentLibraryId, images, folders, selectedFolder, setImages, setFolders, clearSelection]);
+
+ /**
+ * 处理移动请求(带冲突检测)
+ */
+ const handleMove = useCallback(async (targetFolder) => {
+ if (!currentLibraryId || moveItems.length === 0) return;
+
+ setShowFolderSelector(false);
+
+ // 检查冲突(异步)
+ const conflicts = await checkMoveConflicts(moveItems, targetFolder);
+
+ if (conflicts.length > 0 && showConflictDialog) {
+ // 有冲突,显示对话框
+ showConflictDialog(conflicts, 'move', {
+ items: moveItems,
+ targetFolder
+ });
+ } else {
+ // 无冲突,直接执行移动
+ try {
+ await executeMove(moveItems, targetFolder, 'rename');
+ setMoveItems([]);
+ } catch (error) {
+ alert('移动失败: ' + (error.message || '未知错误'));
+ }
+ }
+ }, [currentLibraryId, moveItems, checkMoveConflicts, showConflictDialog, executeMove]);
+
+ /**
+ * 取消移动
+ */
+ const handleCancelMove = useCallback(() => {
+ setShowFolderSelector(false);
+ setMoveItems([]);
+ }, []);
+
+ /**
+ * 撤销移动 - 把文件移回原位置
+ */
+ const handleUndoMove = useCallback(async () => {
+ if (undoHistory.length === 0) return;
+
+ // 从历史栈中取出最近的移动记录
+ const lastMove = undoHistory[undoHistory.length - 1];
+ const remainingHistory = undoHistory.slice(0, -1);
+
+ // 1. 立即关闭Toast
+ setUndoToast({ isVisible: false, message: '', count: 0 });
+
+ // 2. 立即更新历史栈
+ setUndoHistory(remainingHistory);
+
+ // 3. 构造撤销移动项(移回每个文件的原文件夹)
+ 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;
+
+ // 4. 按原文件夹分组(可能移到不同的原文件夹)
+ 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() // 只要文件名,会自动加上 targetFolder 前缀
+ });
+ }
+
+ // 5. 获取主要的源文件夹(大多数文件的源文件夹)
+ 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;
+ }
+ }
+ }
+
+ // 6. 乐观更新UI - 如果在目标文件夹,移除这些文件
+ if (selectedFolder === lastMove.targetFolder) {
+ const undoPaths = new Set(undoItems.map(item => item.path.split('/').pop()));
+ const remainingImages = images.filter(img => !undoPaths.has(img.filename));
+ setImages(remainingImages);
+ }
+
+ // 7. 自动切换到主要源文件夹(让用户看到撤销后的文件)
+ if (primarySourceFolder && selectedFolder !== primarySourceFolder) {
+ setSelectedFolder(primarySourceFolder);
+ }
+
+ // 8. 后台执行撤销移动(并行移动到各自的源文件夹)
+ Promise.all(
+ Array.from(groupedBySource.entries()).map(([sourceFolder, items]) => {
+ // 构造完整路径的 items
+ const fullPathItems = items.map(item => ({
+ type: item.type,
+ path: `${lastMove.targetFolder}/${item.path}`
+ }));
+ return fileAPI.move(currentLibraryId, fullPathItems, sourceFolder, 'rename');
+ })
+ ).then(async () => {
+ // 刷新文件夹列表
+ const foldersRes = await imageAPI.getFolders(currentLibraryId);
+ 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);
+ // 失败时回滚
+ setUndoHistory(undoHistory);
+ imageAPI.getFolders(currentLibraryId).then(foldersRes => {
+ setFolders(foldersRes.folders);
+ });
+ if (selectedFolder) {
+ imageAPI.search(currentLibraryId, { folder: selectedFolder }).then(response => {
+ setImages(response.images);
+ });
+ }
+ alert('撤销移动失败: ' + (error.message || '未知错误'));
+ });
+ }, [undoHistory, currentLibraryId, images, selectedFolder, folders, setImages, setFolders, setSelectedFolder]);
+
+ return {
+ showFolderSelector,
+ moveItems,
+ handleMoveClick,
+ handleMove,
+ handleCancelMove,
+ executeMove,
+ undoHistory,
+ undoToast,
+ setUndoToast,
+ handleUndoMove
+ };
+};
diff --git a/frontend/src/hooks/useImageRating.js b/frontend/src/hooks/useImageRating.js
new file mode 100644
index 0000000..9fc7c8a
--- /dev/null
+++ b/frontend/src/hooks/useImageRating.js
@@ -0,0 +1,91 @@
+/**
+ * 图片评分 Hook
+ */
+
+import { useState, useCallback } from 'react';
+import { useImageStore } from '../stores/useImageStore';
+import { useLibraryStore } from '../stores/useLibraryStore';
+import { imageAPI } from '../api';
+import { createLogger } from '../utils/logger';
+
+const logger = createLogger('useImageRating');
+
+/**
+ * 图片评分功能
+ * @returns {Object} 评分相关的状态和方法
+ */
+export const useImageRating = () => {
+ const { currentLibraryId } = useLibraryStore();
+ const { images, setImages, selectedImage, selectedImages, selectedFolder } = useImageStore();
+
+ const [ratingToast, setRatingToast] = useState({ isVisible: false, rating: 0, count: 0 });
+
+ /**
+ * 快速评分(数字键 0-5)
+ */
+ const handleQuickRating = useCallback(async (rating) => {
+ const imagesToRate = selectedImages.length > 0
+ ? selectedImages
+ : selectedImage
+ ? [selectedImage]
+ : [];
+
+ if (imagesToRate.length === 0) return;
+
+ try {
+ const paths = imagesToRate.map(img => img.path);
+ await imageAPI.updateRating(currentLibraryId, paths, rating);
+
+ // 更新本地状态(images)
+ const updatedImages = images.map(img => {
+ if (paths.includes(img.path)) {
+ return { ...img, rating };
+ }
+ return img;
+ });
+ setImages(updatedImages);
+ // 同步更新 originalImages,确保 Header 筛选统计立即生效
+ useImageStore.getState().setOriginalImages(updatedImages);
+
+ // 更新选中状态
+ if (selectedImage && paths.includes(selectedImage.path)) {
+ useImageStore.getState().setSelectedImage({ ...selectedImage, rating });
+ }
+ if (selectedImages.length > 0) {
+ const updatedSelected = selectedImages.map(img => {
+ if (paths.includes(img.path)) {
+ return { ...img, rating };
+ }
+ return img;
+ });
+ useImageStore.getState().setSelectedImages(updatedSelected);
+ }
+
+ // 显示评分提醒
+ setRatingToast({
+ isVisible: true,
+ rating,
+ count: imagesToRate.length
+ });
+
+ // 刷新当前文件夹的图片列表(确保与后端一致)
+ if (selectedFolder) {
+ const params = { folder: selectedFolder };
+ const response = await imageAPI.search(currentLibraryId, params);
+ setImages(response.images);
+ useImageStore.getState().setOriginalImages(response.images);
+ }
+
+ logger.debug(`⭐ 已将 ${imagesToRate.length} 张图片评为 ${rating} 星`);
+ } catch (error) {
+ logger.error('评分失败:', error);
+ alert('评分失败: ' + (error.message || '未知错误'));
+ }
+ }, [selectedImages, selectedImage, images, currentLibraryId, selectedFolder, setImages]);
+
+ return {
+ ratingToast,
+ setRatingToast,
+ handleQuickRating
+ };
+};
diff --git a/frontend/src/hooks/useImageRename.js b/frontend/src/hooks/useImageRename.js
new file mode 100644
index 0000000..00c542b
--- /dev/null
+++ b/frontend/src/hooks/useImageRename.js
@@ -0,0 +1,102 @@
+/**
+ * 图片重命名 Hook
+ */
+
+import { useState, useCallback, useRef } from 'react';
+import { useImageStore } from '../stores/useImageStore';
+import { useLibraryStore } from '../stores/useLibraryStore';
+import { fileAPI } from '../api';
+import { createLogger } from '../utils/logger';
+
+const logger = createLogger('useImageRename');
+
+/**
+ * 图片重命名功能
+ * @returns {Object} 重命名相关的状态和方法
+ */
+export const useImageRename = () => {
+ const { currentLibraryId } = useLibraryStore();
+ const { renamingImage, setRenamingImage, updateImage } = useImageStore();
+
+ const [editingFilename, setEditingFilename] = useState('');
+ const editInputRef = useRef(null);
+
+ /**
+ * 开始重命名
+ */
+ const handleStartRename = useCallback((image) => {
+ if (!image) return;
+ setRenamingImage(image);
+ // 获取不带扩展名的文件名
+ const nameWithoutExt = image.filename.substring(0, image.filename.lastIndexOf('.')) || image.filename;
+ setEditingFilename(nameWithoutExt);
+ // 延迟聚焦,确保输入框已渲染
+ setTimeout(() => {
+ if (editInputRef.current) {
+ editInputRef.current.focus();
+ editInputRef.current.select();
+ }
+ }, 50);
+ }, [setRenamingImage]);
+
+ /**
+ * 完成重命名
+ */
+ const handleFinishRename = useCallback(async () => {
+ if (!renamingImage || !editingFilename.trim()) {
+ setRenamingImage(null);
+ setEditingFilename('');
+ return;
+ }
+
+ const oldFilename = renamingImage.filename;
+ const ext = oldFilename.substring(oldFilename.lastIndexOf('.'));
+ const newFilename = editingFilename.trim() + ext;
+
+ // 如果文件名没有改变,直接退出
+ if (newFilename === oldFilename) {
+ setRenamingImage(null);
+ setEditingFilename('');
+ return;
+ }
+
+ try {
+ // 调用重命名API
+ const result = await fileAPI.rename(currentLibraryId, renamingImage.path, newFilename);
+
+ // 更新图片信息
+ const newPath = result.newPath;
+ const actualNewName = result.newName;
+ updateImage(renamingImage.path, {
+ path: newPath,
+ filename: actualNewName
+ });
+
+ logger.debug(`✅ 重命名成功: ${oldFilename} → ${actualNewName}`);
+ } catch (error) {
+ logger.error('重命名失败:', error);
+ alert('重命名失败: ' + (error.message || '未知错误'));
+ } finally {
+ setRenamingImage(null);
+ setEditingFilename('');
+ }
+ }, [renamingImage, editingFilename, currentLibraryId, updateImage, setRenamingImage]);
+
+ /**
+ * 取消重命名
+ */
+ const handleCancelRename = useCallback(() => {
+ setRenamingImage(null);
+ setEditingFilename('');
+ }, [setRenamingImage]);
+
+ return {
+ renamingImage,
+ editingFilename,
+ editInputRef,
+ setEditingFilename,
+ handleStartRename,
+ handleFinishRename,
+ handleCancelRename
+ };
+};
diff --git a/frontend/src/hooks/useImageUpload.js b/frontend/src/hooks/useImageUpload.js
new file mode 100644
index 0000000..ee11da4
--- /dev/null
+++ b/frontend/src/hooks/useImageUpload.js
@@ -0,0 +1,255 @@
+/**
+ * 图片上传 Hook
+ */
+
+import { useState, useCallback, useRef } from 'react';
+import { useImageStore } from '../stores/useImageStore';
+import { useLibraryStore } from '../stores/useLibraryStore';
+import { fileAPI, imageAPI } from '../api';
+import { createLogger } from '../utils/logger';
+
+const logger = createLogger('useImageUpload');
+
+/**
+ * 图片上传功能(拖拽上传)
+ * @returns {Object} 上传相关的状态和方法
+ */
+export const useImageUpload = () => {
+ const { currentLibraryId } = useLibraryStore();
+ const { selectedFolder, setImages, setFolders } = useImageStore();
+
+ const [isDraggingOver, setIsDraggingOver] = useState(false);
+ const [uploadProgress, setUploadProgress] = useState({
+ isUploading: false,
+ percent: 0,
+ current: 0,
+ total: 0
+ });
+ const containerRef = useRef(null);
+
+ /**
+ * 拖放事件处理 - 拖拽进入
+ */
+ const handleDragEnter = useCallback((e) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ // 只检测外部文件拖入,排除应用内部拖动
+ const types = e.dataTransfer.types;
+ const hasFiles = types.includes('Files');
+ const hasJson = types.includes('application/json');
+
+ if (hasFiles && !hasJson) {
+ setIsDraggingOver(true);
+ }
+ }, []);
+
+ /**
+ * 拖放事件处理 - 拖拽悬停
+ */
+ const handleDragOver = useCallback((e) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ // 检查是否为外部文件
+ const types = e.dataTransfer.types;
+ const hasFiles = types.includes('Files');
+ const hasJson = types.includes('application/json');
+
+ if (hasFiles && !hasJson) {
+ e.dataTransfer.dropEffect = 'copy';
+ } else {
+ e.dataTransfer.dropEffect = 'none';
+ }
+ }, []);
+
+ /**
+ * 拖放事件处理 - 拖拽离开
+ */
+ const handleDragLeave = useCallback((e) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ // 离开容器区域立即取消提示
+ const rect = containerRef.current?.getBoundingClientRect();
+ if (rect) {
+ const x = e.clientX;
+ const y = e.clientY;
+ // 检查鼠标是否离开容器区域
+ if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
+ setIsDraggingOver(false);
+ }
+ }
+ }, []);
+
+ /**
+ * 拖放事件处理 - 文件放下
+ */
+ const handleDrop = useCallback(async (e, onConflict) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDraggingOver(false);
+
+ if (!currentLibraryId) {
+ alert('请先选择素材库');
+ return;
+ }
+
+ const files = Array.from(e.dataTransfer.files);
+ if (files.length === 0) return;
+
+ logger.debug(`📤 准备上传 ${files.length} 个文件到: ${selectedFolder || '根目录'}`);
+
+ // 开始上传
+ setUploadProgress({ isUploading: true, percent: 0, current: 0, total: files.length });
+
+ try {
+ const result = await fileAPI.upload(
+ currentLibraryId,
+ selectedFolder || '',
+ files,
+ (progressEvent) => {
+ const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
+ setUploadProgress(prev => ({ ...prev, percent }));
+ }
+ );
+
+ // 上传完成
+ setUploadProgress({ isUploading: false, percent: 100, current: result.success.length, total: files.length });
+
+ // 检查是否有冲突
+ const conflicts = result.conflicts || [];
+ if (conflicts.length > 0 && onConflict) {
+ // 有冲突,回调处理
+ logger.debug(`⚠️ 检测到 ${conflicts.length} 个文件冲突`);
+ onConflict(conflicts, files, selectedFolder || '');
+ setUploadProgress({ isUploading: false, percent: 0, current: 0, total: 0 });
+ return { hasConflicts: true, conflicts };
+ }
+
+ // 成功后刷新
+ const successCount = result.success?.length || 0;
+ const failedCount = result.failed?.length || 0;
+
+ if (successCount > 0) {
+ // 立即刷新当前文件夹的图片列表
+ const params = { folder: selectedFolder || '' };
+ const response = await imageAPI.search(currentLibraryId, params);
+ setImages(response.images);
+
+ // 刷新文件夹列表
+ const foldersRes = await imageAPI.getFolders(currentLibraryId);
+ setFolders(foldersRes.folders);
+
+ // 2秒后再刷新一次,确保缩略图已生成
+ setTimeout(async () => {
+ try {
+ const response2 = await imageAPI.search(currentLibraryId, params);
+ setImages(response2.images);
+ logger.debug('✅ 缩略图刷新完成');
+ } catch (err) {
+ logger.error('刷新缩略图失败:', err);
+ }
+ }, 2000);
+ }
+
+ setTimeout(() => {
+ setUploadProgress({ isUploading: false, percent: 0, current: 0, total: 0 });
+ }, 3000);
+
+ return {
+ success: true,
+ successCount,
+ failedCount,
+ hasConflicts: false
+ };
+ } catch (error) {
+ logger.error('上传失败:', error);
+ setUploadProgress({ isUploading: false, percent: 0, current: 0, total: 0 });
+ throw error;
+ }
+ }, [currentLibraryId, selectedFolder, setImages, setFolders]);
+
+ /**
+ * 处理冲突后重新上传
+ */
+ const uploadWithConflictAction = useCallback(async (files, targetFolder, conflictAction) => {
+ if (!currentLibraryId) return;
+
+ logger.debug(`处理上传冲突: ${conflictAction}`);
+
+ if (conflictAction === 'skip') {
+ logger.debug('用户选择跳过上传');
+ return { success: true, skipped: true };
+ }
+
+ // 开始上传
+ setUploadProgress({ isUploading: true, percent: 0, current: 0, total: files.length });
+
+ try {
+ const result = await fileAPI.upload(
+ currentLibraryId,
+ targetFolder,
+ files,
+ (progressEvent) => {
+ const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
+ setUploadProgress(prev => ({ ...prev, percent }));
+ },
+ conflictAction
+ );
+
+ // 上传完成
+ setUploadProgress({
+ isUploading: false,
+ percent: 100,
+ current: result.success.length,
+ total: files.length
+ });
+
+ const successCount = result.success?.length || 0;
+ const failedCount = result.failed?.length || 0;
+
+ // 刷新图片列表
+ if (successCount > 0) {
+ const params = { folder: selectedFolder || '' };
+ const response = await imageAPI.search(currentLibraryId, params);
+ setImages(response.images);
+
+ const foldersRes = await imageAPI.getFolders(currentLibraryId);
+ setFolders(foldersRes.folders);
+
+ // 2秒后再刷新一次
+ setTimeout(async () => {
+ try {
+ const response2 = await imageAPI.search(currentLibraryId, params);
+ setImages(response2.images);
+ logger.debug('✅ 缩略图刷新完成');
+ } catch (err) {
+ logger.error('刷新缩略图失败:', err);
+ }
+ }, 2000);
+ }
+
+ setTimeout(() => {
+ setUploadProgress({ isUploading: false, percent: 0, current: 0, total: 0 });
+ }, 3000);
+
+ return { success: true, successCount, failedCount };
+ } catch (error) {
+ logger.error('上传失败:', error);
+ setUploadProgress({ isUploading: false, percent: 0, current: 0, total: 0 });
+ throw error;
+ }
+ }, [currentLibraryId, selectedFolder, setImages, setFolders]);
+
+ return {
+ isDraggingOver,
+ uploadProgress,
+ containerRef,
+ handleDragEnter,
+ handleDragOver,
+ handleDragLeave,
+ handleDrop,
+ uploadWithConflictAction
+ };
+};
diff --git a/frontend/src/hooks/useInfiniteScroll.js b/frontend/src/hooks/useInfiniteScroll.js
new file mode 100644
index 0000000..7358601
--- /dev/null
+++ b/frontend/src/hooks/useInfiniteScroll.js
@@ -0,0 +1,97 @@
+/**
+ * 无限滚动 Hook
+ */
+
+import { useCallback } from 'react';
+import { useImageStore } from '../stores/useImageStore';
+import { useLibraryStore } from '../stores/useLibraryStore';
+import { imageAPI } from '../api';
+import requestManager, { RequestType } from '../services/requestManager';
+import { createLogger } from '../utils/logger';
+
+const logger = createLogger('useInfiniteScroll');
+
+// 加载配置
+const LOAD_CONFIG = {
+ pageSize: 100, // 每次加载 100 张
+ preloadThreshold: 300, // 距离边界 300px 时预加载
+};
+
+/**
+ * 无限滚动加载
+ * @returns {Object} 加载相关的状态和方法
+ */
+export const useInfiniteScroll = () => {
+ const { currentLibraryId } = useLibraryStore();
+ const {
+ images,
+ imageLoadingState,
+ setImageLoadingState,
+ selectedFolder,
+ searchKeywords,
+ filters,
+ appendImages
+ } = useImageStore();
+
+ /**
+ * 加载更多图片
+ */
+ const loadMoreImages = useCallback(async () => {
+ if (!currentLibraryId || !imageLoadingState.hasMore || imageLoadingState.isLoading) {
+ return;
+ }
+
+ const requestContext = requestManager.createRequest(RequestType.IMAGES);
+ setImageLoadingState({ isLoading: true });
+
+ try {
+ const params = {
+ offset: images.length,
+ limit: LOAD_CONFIG.pageSize
+ };
+ if (selectedFolder) params.folder = selectedFolder;
+ if (searchKeywords) params.keywords = searchKeywords;
+ if (filters.formats?.length > 0) params.formats = filters.formats.join(',');
+
+ const response = await imageAPI.search(currentLibraryId, params, {
+ signal: requestContext.signal
+ });
+
+ if (!requestManager.isValid(requestContext.id)) {
+ return;
+ }
+
+ const { images: newImages, total, hasMore } = response;
+ requestManager.complete(requestContext.id);
+
+ appendImages(newImages);
+ setImageLoadingState({
+ isLoading: false,
+ loadedCount: images.length + newImages.length,
+ totalCount: total,
+ hasMore: hasMore || false,
+ });
+ } catch (error) {
+ if (error.name === 'CanceledError' || error.name === 'AbortError') {
+ return;
+ }
+ logger.error('Error loading more images:', error);
+ requestManager.error(requestContext.id);
+ setImageLoadingState({ isLoading: false });
+ }
+ }, [
+ currentLibraryId,
+ imageLoadingState,
+ images.length,
+ selectedFolder,
+ searchKeywords,
+ filters,
+ appendImages,
+ setImageLoadingState
+ ]);
+
+ return {
+ loadMoreImages,
+ preloadThreshold: LOAD_CONFIG.preloadThreshold
+ };
+};
diff --git a/frontend/src/hooks/useWaterfallLayout.js b/frontend/src/hooks/useWaterfallLayout.js
new file mode 100644
index 0000000..26877af
--- /dev/null
+++ b/frontend/src/hooks/useWaterfallLayout.js
@@ -0,0 +1,206 @@
+/**
+ * 瀑布流布局计算 Hook
+ */
+
+import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
+import { useUIStore } from '../stores/useUIStore';
+
+/**
+ * 瀑布流布局计算
+ * @param {Array} images - 图片列表
+ * @param {Object} options - 配置选项
+ * @returns {Object} { rows, containerRef, containerWidth, containerHeight }
+ */
+export const useWaterfallLayout = (images, options = {}) => {
+ const { gap = 16 } = options;
+ const { thumbnailHeight, isResizingPanels } = useUIStore();
+
+ const containerRef = useRef(null);
+ const [containerWidth, setContainerWidth] = useState(0);
+ const [containerHeight, setContainerHeight] = useState(0);
+
+ // 监听容器宽度变化(使用 ResizeObserver + 去抖/阈值抑制)
+ useEffect(() => {
+ let resizeObserver = null;
+ let retryCount = 0;
+ const maxRetries = 10;
+
+ // 使用 ref 记录上次宽度,避免频繁 setState
+ const lastWidthRef = { current: 0 };
+ let debounceTimer = null;
+
+ const emitSize = (width, height) => {
+ // 仅当差异超过阈值时更新,减少重算次数
+ const threshold = 12; // px
+ if (Math.abs(width - lastWidthRef.current) < threshold) return true;
+
+ lastWidthRef.current = width;
+
+ // 去抖:在一小段静止后再更新(拖动时降低重算频率)
+ if (debounceTimer) clearTimeout(debounceTimer);
+ debounceTimer = setTimeout(() => {
+ setContainerWidth(width);
+ setContainerHeight(height);
+ }, 50);
+ return true;
+ };
+
+ const measureAndEmit = () => {
+ if (containerRef.current) {
+ // 预留 padding:与现有布局保持一致
+ const width = containerRef.current.offsetWidth - 32;
+ const height = containerRef.current.offsetHeight;
+ if (width > 0) {
+ return emitSize(width, height);
+ }
+ }
+ return false;
+ };
+
+ const tryInit = () => {
+ if (measureAndEmit()) {
+ // 成功获取宽度,设置 ResizeObserver
+ if (containerRef.current) {
+ resizeObserver = new ResizeObserver(() => {
+ // 拖动时跳过更新,避免频繁重算布局
+ if (useUIStore.getState().isResizingPanels) return;
+ measureAndEmit();
+ });
+ resizeObserver.observe(containerRef.current);
+ }
+ } else if (retryCount < maxRetries) {
+ // 重试
+ retryCount++;
+ requestAnimationFrame(tryInit);
+ }
+ };
+
+ // 使用 requestAnimationFrame 确保 DOM 已渲染
+ requestAnimationFrame(tryInit);
+
+ return () => {
+ if (resizeObserver) {
+ resizeObserver.disconnect();
+ }
+ if (debounceTimer) {
+ clearTimeout(debounceTimer);
+ }
+ };
+ }, []);
+
+ // 拖动结束时(isResizingPanels 从 true -> false)立即测量一次
+ useEffect(() => {
+ if (isResizingPanels) return;
+ if (!containerRef.current) return;
+ const width = containerRef.current.offsetWidth - 32;
+ const height = containerRef.current.offsetHeight;
+ if (width > 0) {
+ setContainerWidth(width);
+ setContainerHeight(height);
+ }
+ }, [isResizingPanels]);
+
+ // 布局计算(始终在主线程同步执行)
+ const rows = useMemo(() => {
+ if (!images.length || !containerWidth) {
+ return [];
+ }
+
+ const targetHeight = thumbnailHeight;
+ const calculatedRows = [];
+ let currentRow = [];
+ let currentRowWidthSum = 0;
+
+ images.forEach((image, index) => {
+ const aspectRatio = image.width / image.height;
+ const imageWidth = targetHeight * aspectRatio;
+
+ currentRow.push({
+ ...image,
+ originalWidth: imageWidth,
+ aspectRatio: aspectRatio
+ });
+ currentRowWidthSum += imageWidth;
+
+ const currentGaps = (currentRow.length - 1) * gap;
+ const totalWidth = currentRowWidthSum + currentGaps;
+ const isLastImage = index === images.length - 1;
+
+ let shouldFinishRow = false;
+
+ if (isLastImage) {
+ shouldFinishRow = true;
+ } else if (totalWidth >= containerWidth * 0.95) {
+ // Row is almost full (95% or more) - finish it
+ shouldFinishRow = true;
+ } else {
+ // Check if adding next image would overflow too much
+ const nextImage = images[index + 1];
+ if (nextImage) {
+ const nextAspectRatio = nextImage.width / nextImage.height;
+ const nextImageWidth = targetHeight * nextAspectRatio;
+ const nextTotalWidth = currentRowWidthSum + nextImageWidth + (currentRow.length * gap);
+
+ // If adding next image would exceed 120% of container width, finish current row
+ if (nextTotalWidth > containerWidth * 1.2) {
+ shouldFinishRow = true;
+ }
+ }
+ }
+
+ if (shouldFinishRow) {
+ const totalGaps = (currentRow.length - 1) * gap;
+ const availableWidth = containerWidth - totalGaps;
+
+ // For last row with few images, limit the scale to avoid over-stretching
+ let scale = availableWidth / currentRowWidthSum;
+
+ if (isLastImage && currentRow.length < 3) {
+ // Last row with 1-2 images: don't stretch too much
+ scale = Math.min(scale, 1.2);
+ }
+
+ const rowHeight = targetHeight * scale;
+
+ currentRow = currentRow.map(img => ({
+ ...img,
+ calculatedWidth: img.originalWidth * scale,
+ calculatedHeight: rowHeight
+ }));
+
+ calculatedRows.push(currentRow);
+
+ // Reset for next row
+ currentRow = [];
+ currentRowWidthSum = 0;
+ }
+ });
+
+ return calculatedRows;
+ }, [images, thumbnailHeight, containerWidth, gap]);
+
+ // 扁平化的图片列表(用于 Shift 多选)
+ const flatImages = useMemo(() => {
+ if (!rows || rows.length === 0) return [];
+ return rows.flat();
+ }, [rows]);
+
+ // 获取行高(用于虚拟滚动)
+ const getRowHeight = useCallback((index) => {
+ if (!rows || !rows[index] || rows[index].length === 0) {
+ return thumbnailHeight + 40;
+ }
+ // 行高 = 图片高度 + 文件名区域 + 行间距
+ const firstImage = rows[index][0];
+ return (firstImage?.calculatedHeight || thumbnailHeight) + 28 + 32;
+ }, [rows, thumbnailHeight]);
+
+ return {
+ rows,
+ flatImages,
+ containerRef,
+ containerWidth,
+ containerHeight,
+ getRowHeight
+ };
+};
diff --git a/frontend/src/stores/useImageStore.js b/frontend/src/stores/useImageStore.js
index 77256bd..ad0dc4c 100644
--- a/frontend/src/stores/useImageStore.js
+++ b/frontend/src/stores/useImageStore.js
@@ -107,11 +107,14 @@ export const useImageStore = create((set, get) => ({
// 重命名操作
setRenamingImage: (image) => set({ renamingImage: image }),
- // 更新图片信息(重命名后)
+ // 更新图片信息(重命名、评分等)
updateImage: (oldPath, newData) => set((state) => ({
images: state.images.map(img =>
img.path === oldPath ? { ...img, ...newData } : img
),
+ originalImages: state.originalImages.map(img =>
+ img.path === oldPath ? { ...img, ...newData } : img
+ ),
selectedImage: state.selectedImage?.path === oldPath
? { ...state.selectedImage, ...newData }
: state.selectedImage
diff --git a/frontend/src/utils/imageCache.js b/frontend/src/utils/imageCache.js
deleted file mode 100644
index ec7920d..0000000
--- a/frontend/src/utils/imageCache.js
+++ /dev/null
@@ -1,202 +0,0 @@
-/**
- * LRU Image Cache
- * Caches loaded image data with LRU eviction and strict size limits
- */
-
-class ImageCache {
- constructor(options = {}) {
- this.maxSize = options.maxSize || 20; // Maximum 20 cached images (只缓存当前可见的)
- this.cache = new Map(); // imageId -> { data, timestamp, blobUrl, accessCount }
- this.accessOrder = []; // LRU tracking: most recently used at the end
-
- // Statistics
- this.stats = {
- hitCount: 0,
- missCount: 0,
- evictionCount: 0,
- totalSets: 0,
- totalGets: 0
- };
- }
-
- /**
- * Get cached image data
- * @param {string} imageId - Unique image identifier
- * @returns {Object|null} Cached image data or null if not found
- */
- get(imageId) {
- this.stats.totalGets++;
-
- const cached = this.cache.get(imageId);
-
- if (cached) {
- // Cache hit: update access order
- this.stats.hitCount++;
- this._updateAccessOrder(imageId);
- cached.accessCount = (cached.accessCount || 0) + 1;
- return cached;
- }
-
- // Cache miss
- this.stats.missCount++;
- return null;
- }
-
- /**
- * Set/update cached image data
- * @param {string} imageId - Unique image identifier
- * @param {Object} data - Image data to cache
- */
- set(imageId, data) {
- this.stats.totalSets++;
-
- // If cache is full and this is a new entry, evict LRU
- if (!this.cache.has(imageId) && this.cache.size >= this.maxSize) {
- this.evictLRU();
- }
-
- // Create blob URL if data contains blob
- let blobUrl = null;
- if (data.blob) {
- blobUrl = URL.createObjectURL(data.blob);
- }
-
- // Store in cache
- this.cache.set(imageId, {
- data,
- blobUrl,
- timestamp: Date.now(),
- accessCount: 1
- });
-
- // Update access order
- this._updateAccessOrder(imageId);
- }
-
- /**
- * Remove image from cache
- * @param {string} imageId - Image identifier to remove
- */
- remove(imageId) {
- const cached = this.cache.get(imageId);
-
- if (cached) {
- // Revoke blob URL to release memory
- if (cached.blobUrl) {
- URL.revokeObjectURL(cached.blobUrl);
- }
-
- this.cache.delete(imageId);
-
- // Remove from access order
- const index = this.accessOrder.indexOf(imageId);
- if (index > -1) {
- this.accessOrder.splice(index, 1);
- }
- }
- }
-
- /**
- * Clear entire cache
- */
- clear() {
- // Revoke all blob URLs
- for (const [imageId, cached] of this.cache.entries()) {
- if (cached.blobUrl) {
- URL.revokeObjectURL(cached.blobUrl);
- }
- }
-
- this.cache.clear();
- this.accessOrder = [];
- }
-
- /**
- * Evict least recently used entry
- */
- evictLRU() {
- if (this.accessOrder.length === 0) {
- return;
- }
-
- // First item in access order is least recently used
- const lruImageId = this.accessOrder[0];
-
- this.remove(lruImageId);
- this.stats.evictionCount++;
- }
-
- /**
- * Get current cache size
- * @returns {number} Number of cached entries
- */
- size() {
- return this.cache.size;
- }
-
- /**
- * Get cache statistics
- * @returns {Object} Cache statistics
- */
- getStats() {
- const hitRate = this.stats.totalGets > 0
- ? (this.stats.hitCount / this.stats.totalGets * 100).toFixed(2)
- : 0;
-
- return {
- size: this.cache.size,
- maxSize: this.maxSize,
- hitCount: this.stats.hitCount,
- missCount: this.stats.missCount,
- evictionCount: this.stats.evictionCount,
- totalSets: this.stats.totalSets,
- totalGets: this.stats.totalGets,
- hitRate: parseFloat(hitRate)
- };
- }
-
- /**
- * Update access order for LRU tracking
- * @private
- */
- _updateAccessOrder(imageId) {
- // Remove from current position
- const index = this.accessOrder.indexOf(imageId);
- if (index > -1) {
- this.accessOrder.splice(index, 1);
- }
-
- // Add to end (most recently used)
- this.accessOrder.push(imageId);
- }
-
- /**
- * Check if image is cached
- * @param {string} imageId - Image identifier
- * @returns {boolean} True if cached
- */
- has(imageId) {
- return this.cache.has(imageId);
- }
-
- /**
- * Get all cached image IDs
- * @returns {Array} Array of cached image IDs
- */
- keys() {
- return Array.from(this.cache.keys());
- }
-
- /**
- * Log cache statistics (for debugging)
- */
- logStats() {
- const stats = this.getStats();
- // 仅在需要时输出统计信息
- }
-}
-
-// Export singleton instance
-const imageCache = new ImageCache();
-
-export default imageCache;
diff --git a/frontend/src/utils/imageFilters.js b/frontend/src/utils/imageFilters.js
new file mode 100644
index 0000000..952f16c
--- /dev/null
+++ b/frontend/src/utils/imageFilters.js
@@ -0,0 +1,113 @@
+/**
+ * 图片筛选相关工具函数
+ */
+
+/**
+ * 解析大小字符串为 KB
+ * @param {string} sizeStr - 大小字符串,如 "1.5MB"
+ * @returns {number} KB 数值
+ */
+export const parseSizeToKB = (sizeStr) => {
+ const match = sizeStr.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB)$/);
+ if (!match) return 0;
+ const value = parseFloat(match[1]);
+ const unit = match[2];
+ switch (unit) {
+ case 'B': return value / 1024;
+ case 'KB': return value;
+ case 'MB': return value * 1024;
+ case 'GB': return value * 1024 * 1024;
+ default: return 0;
+ }
+};
+
+/**
+ * 匹配大小范围
+ * @param {number} sizeKB - 文件大小(KB)
+ * @param {string} range - 范围字符串,如 ">10MB" 或 "1MB - 10MB"
+ * @returns {boolean} 是否匹配
+ */
+export const matchSizeRange = (sizeKB, range) => {
+ if (range.startsWith('>')) {
+ const minStr = range.substring(1).trim();
+ const minKB = parseSizeToKB(minStr);
+ return sizeKB >= minKB;
+ } else if (range.includes(' - ')) {
+ const [minStr, maxStr] = range.split(' - ').map(s => s.trim());
+ const minKB = parseSizeToKB(minStr);
+ const maxKB = parseSizeToKB(maxStr);
+ return sizeKB >= minKB && sizeKB < maxKB;
+ }
+ return false;
+};
+
+/**
+ * 前端筛选图片
+ * @param {Array} images - 图片列表
+ * @param {Object} filters - 筛选条件 { formats, sizes, orientations, ratings }
+ * @returns {Array} 筛选后的图片列表
+ */
+export const filterImages = (images, filters) => {
+ const { formats, sizes, orientations, ratings } = filters;
+
+ // 如果没有任何筛选条件,直接返回原始图片
+ if ((!formats || formats.length === 0) &&
+ (!sizes || sizes.length === 0) &&
+ (!orientations || orientations.length === 0) &&
+ (!ratings || ratings.length === 0)) {
+ return images;
+ }
+
+ return images.filter(img => {
+ // 格式筛选
+ if (formats && formats.length > 0) {
+ if (!formats.includes(img.format?.toLowerCase())) {
+ return false;
+ }
+ }
+
+ // 文件大小筛选
+ if (sizes && sizes.length > 0) {
+ const sizeKB = img.size / 1024;
+ let matchesSize = false;
+
+ for (const range of sizes) {
+ if (matchSizeRange(sizeKB, range)) {
+ matchesSize = true;
+ break;
+ }
+ }
+
+ if (!matchesSize) return false;
+ }
+
+ // 方向筛选(多选)
+ if (orientations && orientations.length > 0) {
+ const aspectRatio = img.width / img.height;
+ let matchesOrientation = false;
+
+ for (const orientation of orientations) {
+ if (orientation === 'horizontal' && aspectRatio > 1.05) {
+ matchesOrientation = true;
+ break;
+ } else if (orientation === 'vertical' && aspectRatio < 0.95) {
+ matchesOrientation = true;
+ break;
+ } else if (orientation === 'square' && aspectRatio >= 0.95 && aspectRatio <= 1.05) {
+ matchesOrientation = true;
+ break;
+ }
+ }
+
+ if (!matchesOrientation) return false;
+ }
+
+ // 评分筛选(多选)
+ if (ratings && ratings.length > 0) {
+ const imgRating = img.rating || 0;
+ if (!ratings.includes(imgRating)) return false;
+ }
+
+ return true;
+ });
+};
diff --git a/frontend/src/utils/logger.js b/frontend/src/utils/logger.js
new file mode 100644
index 0000000..3f17d19
--- /dev/null
+++ b/frontend/src/utils/logger.js
@@ -0,0 +1,125 @@
+/**
+ * 统一日志管理工具
+ * 生产环境自动禁用调试日志
+ */
+
+const isDev = import.meta.env.DEV;
+const isDebugEnabled = isDev || import.meta.env.VITE_ENABLE_DEBUG === 'true';
+
+/**
+ * 日志工具类
+ */
+class Logger {
+ constructor(namespace = '') {
+ this.namespace = namespace;
+ }
+
+ /**
+ * 格式化日志前缀
+ */
+ _getPrefix() {
+ return this.namespace ? `[${this.namespace}]` : '';
+ }
+
+ /**
+ * 调试日志(仅开发环境)
+ */
+ debug(...args) {
+ if (isDebugEnabled) {
+ console.log(this._getPrefix(), ...args);
+ }
+ }
+
+ /**
+ * 信息日志(仅开发环境)
+ */
+ info(...args) {
+ if (isDebugEnabled) {
+ console.info(this._getPrefix(), ...args);
+ }
+ }
+
+ /**
+ * 警告日志(所有环境)
+ */
+ warn(...args) {
+ console.warn(this._getPrefix(), ...args);
+ }
+
+ /**
+ * 错误日志(所有环境)
+ */
+ error(...args) {
+ console.error(this._getPrefix(), ...args);
+ }
+
+ /**
+ * 表格日志(仅开发环境)
+ */
+ table(data) {
+ if (isDebugEnabled) {
+ console.table(data);
+ }
+ }
+
+ /**
+ * 分组日志(仅开发环境)
+ */
+ group(label, collapsed = false) {
+ if (isDebugEnabled) {
+ if (collapsed) {
+ console.groupCollapsed(this._getPrefix(), label);
+ } else {
+ console.group(this._getPrefix(), label);
+ }
+ }
+ }
+
+ groupEnd() {
+ if (isDebugEnabled) {
+ console.groupEnd();
+ }
+ }
+
+ /**
+ * 性能计时开始
+ */
+ time(label) {
+ if (isDebugEnabled) {
+ console.time(this._getPrefix() + ' ' + label);
+ }
+ }
+
+ /**
+ * 性能计时结束
+ */
+ timeEnd(label) {
+ if (isDebugEnabled) {
+ console.timeEnd(this._getPrefix() + ' ' + label);
+ }
+ }
+}
+
+/**
+ * 创建带命名空间的日志器
+ * @param {string} namespace - 日志命名空间
+ * @returns {Logger} 日志器实例
+ */
+export function createLogger(namespace) {
+ return new Logger(namespace);
+}
+
+/**
+ * 默认日志器(无命名空间)
+ */
+export const logger = new Logger();
+
+/**
+ * 快捷方法(无命名空间)
+ */
+export const log = (...args) => logger.debug(...args);
+export const info = (...args) => logger.info(...args);
+export const warn = (...args) => logger.warn(...args);
+export const error = (...args) => logger.error(...args);
+
+export default logger;