diff --git a/backend/database/dbPool.js b/backend/database/dbPool.js index 3749f62..90bcf20 100644 --- a/backend/database/dbPool.js +++ b/backend/database/dbPool.js @@ -1,4 +1,6 @@ const LibraryDatabase = require('./db'); +const { constants } = require('../src/config'); +const logger = require('../src/utils/logger'); /** * 数据库连接池管理器 @@ -13,7 +15,7 @@ class DatabasePool { DatabasePool.instance = this; this.connections = new Map(); // libraryPath -> { db, lastUsed, refCount } - this.maxIdleTime = 60000; // 60秒未使用则关闭 + this.maxIdleTime = constants.MEMORY.DB_IDLE_TIMEOUT_MS; this.cleanupInterval = null; // 启动定期清理 @@ -71,14 +73,14 @@ class DatabasePool { try { conn.db.db.pragma('wal_checkpoint(TRUNCATE)'); } catch (e) { - console.warn(`[DBPool] WAL checkpoint warning:`, e.message); + logger.warn(`[DBPool] WAL checkpoint warning:`, e.message); } } conn.db.close(); this.connections.delete(libraryPath); } catch (error) { - console.error(`❌ 关闭数据库连接失败:`, error.message); + logger.error(`关闭数据库连接失败:`, error.message); // 即使出错也删除引用 this.connections.delete(libraryPath); } @@ -102,12 +104,12 @@ class DatabasePool { try { conn.db.db.pragma('wal_checkpoint(TRUNCATE)'); } catch (e) { - console.warn(`[DBPool] WAL checkpoint warning:`, e.message); + logger.warn(`[DBPool] WAL checkpoint warning:`, e.message); } } conn.db.close(); } catch (error) { - console.error(`❌ 关闭数据库连接失败:`, error.message); + logger.error(`关闭数据库连接失败:`, error.message); } } this.connections.clear(); @@ -125,7 +127,8 @@ class DatabasePool { * 启动定期清理空闲连接 */ startCleanup() { - // 更频繁的检查(每10秒) + const checkInterval = constants.MEMORY.DB_CLEANUP_CHECK_INTERVAL; + this.cleanupInterval = setInterval(() => { const now = Date.now(); const toClose = []; @@ -147,7 +150,7 @@ class DatabasePool { } } } - }, 10000); // 每10秒检查一次(更频繁) + }, checkInterval); } /** diff --git a/backend/package.json b/backend/package.json index 76a9ff5..c5ad74b 100644 --- a/backend/package.json +++ b/backend/package.json @@ -12,7 +12,6 @@ "better-sqlite3": "^9.2.2", "chokidar": "^3.6.0", "cors": "^2.8.5", - "crypto": "^1.0.1", "express": "^4.18.2", "glob": "^10.3.10", "jsonwebtoken": "^9.0.2", diff --git a/backend/src/config/constants.js b/backend/src/config/constants.js index b3fd70c..1325a97 100644 --- a/backend/src/config/constants.js +++ b/backend/src/config/constants.js @@ -26,9 +26,13 @@ module.exports = { // 扫描配置 SCAN: { - BATCH_SIZE: 50, - CONCURRENT_LIMIT: 10, - PROGRESS_UPDATE_INTERVAL: 100 + BATCH_SIZE: 50, // 扫描时每批处理的文件数 + WRITE_BATCH_SIZE: 50, // 数据库批量写入大小 + STREAM_BATCH_SIZE: 200, // 流式处理批次大小 + CONCURRENT_LIMIT: 10, // 并发处理限制 + PROGRESS_UPDATE_INTERVAL: 100, + PROGRESS_LOG_INTERVAL: 1000, // 每处理1000个文件输出一次进度 + GC_TRIGGER_INTERVAL: 1000 // 每处理1000个文件触发一次GC }, // 内存配置 @@ -36,8 +40,9 @@ module.exports = { WARNING_THRESHOLD_MB: 200, DANGER_THRESHOLD_MB: 300, CACHE_SIZE_KB: 4096, - CLEANUP_INTERVAL_MS: 60000, - DB_IDLE_TIMEOUT_MS: 300000 + CLEANUP_INTERVAL_MS: 60000, // 清理间隔:1分钟 + DB_IDLE_TIMEOUT_MS: 60000, // 数据库空闲超时:60秒 + DB_CLEANUP_CHECK_INTERVAL: 10000 // 数据库清理检查间隔:10秒 }, // 数据库配置 @@ -57,6 +62,34 @@ module.exports = { FLYPIC_DIR: '.flypic', THUMBNAILS_DIR: 'thumbnails', DATABASE_FILE: 'metadata.db', - CONFIG_FILE: 'config.json' + CONFIG_FILE: 'config.json', + TEMP_BACKUP_DIR: '.flypic/temp_backup' + }, + + // 文件操作配置 + FILE_OPERATIONS: { + TEMP_FILE_EXPIRY_MS: 5 * 60 * 1000, // 临时文件过期时间:5分钟 + COPY_FOLDER_BATCH_SIZE: 10, // 复制文件夹时每批处理的图片数 + COPY_FOLDER_BATCH_LOG_INTERVAL: 50 // 每处理50张输出进度 + }, + + // 缩略图生成配置 + THUMBNAIL_GENERATION: { + TARGET_HEIGHT: 480, // 目标高度 + MAX_QUALITY: 95, // 最高质量 + DEFAULT_QUALITY: 92, // 默认质量 + EFFORT: 4, // WebP编码努力程度 + SHARP_CACHE_MEMORY_MB: 20, // Sharp缓存内存限制 + SHARP_CACHE_ITEMS: 10, // Sharp缓存项数 + SHARP_CONCURRENCY: 1, // Sharp并发数 + GC_PROBABILITY: 0.1, // GC触发概率 + PLACEHOLDER_WIDTH: 640, // 占位图宽度 + PLACEHOLDER_HEIGHT: 480 // 占位图高度 + }, + + // 文件监控配置 + FILE_WATCHER: { + POLL_INTERVAL_MS: 5000, // 轮询间隔:5秒 + OFFLINE_CHECK_ENABLED: true // 是否检查离线变化 } }; diff --git a/backend/src/services/FileService.js b/backend/src/services/FileService.js index 33bf705..5984f49 100644 --- a/backend/src/services/FileService.js +++ b/backend/src/services/FileService.js @@ -6,9 +6,11 @@ const fs = require('fs'); const path = require('path'); const { processImage } = require('../../utils/scanner'); +const { constants } = require('../config'); +const logger = require('../utils/logger'); -// 临时备份目录(用于撤销恢复)- 放在 .flypic 内部 -const TEMP_BACKUP_DIR = '.flypic/temp_backup'; +// 临时备份目录(用于撤销恢复) +const TEMP_BACKUP_DIR = constants.PATHS.TEMP_BACKUP_DIR; class FileService { constructor(dbPool, configManager) { @@ -175,7 +177,7 @@ class FileService { return { cleaned: 0, failed: 0, thumbnailsCleaned: 0 }; } - const FIVE_MINUTES = 5 * 60 * 1000; // 5分钟 + const EXPIRY_TIME = constants.FILE_OPERATIONS.TEMP_FILE_EXPIRY_MS; const now = Date.now(); let cleaned = 0; let failed = 0; @@ -199,8 +201,8 @@ class FileService { const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8')); const age = now - meta.deletedAt; - // 超过5分钟,移入系统回收站 - if (age > FIVE_MINUTES) { + // 超过配置的过期时间,移入系统回收站 + if (age > EXPIRY_TIME) { try { // 1. 清理缩略图(在移入回收站前) if (meta.imageRecords) { @@ -212,10 +214,10 @@ class FileService { if (fs.existsSync(thumbnailFullPath)) { fs.unlinkSync(thumbnailFullPath); thumbnailsCleaned++; - console.log(`🧹 已清理缩略图: ${record.thumbnail_path}`); + logger.debug(`已清理缩略图: ${record.thumbnail_path}`); } } catch (thumbError) { - console.warn(`清理缩略图失败 ${record.thumbnail_path}:`, thumbError.message); + logger.warn(`清理缩略图失败 ${record.thumbnail_path}:`, thumbError.message); } } } @@ -227,14 +229,14 @@ class FileService { await trash([fullPath]); fs.unlinkSync(metaPath); // 删除 meta 文件 cleaned++; - console.log(`🗑️ 已将过期文件移入回收站: ${meta.originalPath}`); + logger.info(`已将过期文件移入回收站: ${meta.originalPath}`); } catch (error) { - console.error(`清理失败 ${meta.originalPath}:`, error); + logger.error(`清理失败 ${meta.originalPath}:`, error); failed++; } } } catch (error) { - console.error(`读取 meta 失败 ${metaPath}:`, error); + logger.error(`读取 meta 失败 ${metaPath}:`, error); } } else if (fs.statSync(fullPath).isDirectory()) { // 递归处理子目录 @@ -291,7 +293,7 @@ class FileService { // 根目录也删除(如果完全为空) try { fs.rmdirSync(dir); - console.log(`🧹 已删除空的备份目录: ${TEMP_BACKUP_DIR}`); + logger.debug(`已删除空的备份目录: ${TEMP_BACKUP_DIR}`); } catch (error) { // 忽略根目录删除失败 } @@ -300,7 +302,7 @@ class FileService { try { fs.rmdirSync(dir); const relativePath = path.relative(backupDir, dir); - console.log(`🧹 已删除空文件夹: ${relativePath}`); + logger.debug(`已删除空文件夹: ${relativePath}`); } catch (error) { // 忽略删除失败(可能权限问题) } @@ -315,32 +317,12 @@ class FileService { try { removeEmptyDirs(backupDir); } catch (error) { - console.warn('[cleanExpiredTempFiles] 清理空文件夹时出错:', error.message); + logger.warn('[cleanExpiredTempFiles] 清理空文件夹时出错:', error.message); } return { cleaned, failed, thumbnailsCleaned }; } - /** - * 递归复制目录 - */ - _copyDirSync(src, dest) { - fs.mkdirSync(dest, { recursive: true }); - const files = fs.readdirSync(src); - - for (const file of files) { - const srcPath = path.join(src, file); - const destPath = path.join(dest, file); - const stat = fs.statSync(srcPath); - - if (stat.isDirectory()) { - this._copyDirSync(srcPath, destPath); - } else { - fs.copyFileSync(srcPath, destPath); - } - } - } - /** * 获取数据库实例 */ diff --git a/backend/utils/scanner.js b/backend/utils/scanner.js index c360ba9..689e561 100644 --- a/backend/utils/scanner.js +++ b/backend/utils/scanner.js @@ -10,6 +10,8 @@ const { clearSharpCache } = require('./thumbnail'); const scanManager = require('./scanManager'); +const { constants } = require('../src/config'); +const logger = require('../src/utils/logger'); /** * Get all image files in a directory @@ -379,8 +381,8 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume // 批量写入缓冲区 let writeBuffer = []; - const WRITE_BATCH_SIZE = 50; // 每 50 条写入一次数据库(降低内存峰值) - const STREAM_BATCH_SIZE = 200; // 每批处理 200 个文件(流式处理) + const WRITE_BATCH_SIZE = constants.SCAN.WRITE_BATCH_SIZE; + const STREAM_BATCH_SIZE = constants.SCAN.STREAM_BATCH_SIZE; // 批量写入函数(事务) const batchWrite = db.db.transaction((items) => { @@ -464,16 +466,19 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume writeBuffer = []; } - // 每1000个文件输出一次进度(减少日志) - if (processedCount % 1000 === 0) { + // 定期输出进度 + const logInterval = constants.SCAN.PROGRESS_LOG_INTERVAL; + const gcInterval = constants.SCAN.GC_TRIGGER_INTERVAL; + + if (processedCount % logInterval === 0) { const elapsed = (Date.now() - startTime) / 1000; const speed = processedCount / elapsed; const percent = ((processedCount / total) * 100).toFixed(1); - console.log(`⚡ ${processedCount}/${total} (${percent}%) | ${speed.toFixed(1)} 张/秒`); + logger.info(`扫描进度: ${processedCount}/${total} (${percent}%) | ${speed.toFixed(1)} 张/秒`); } - // 每 1000 个文件触发一次 GC - if (processedCount > 0 && processedCount % 1000 === 0 && global.gc) { + // 定期触发 GC + if (processedCount > 0 && processedCount % gcInterval === 0 && global.gc) { global.gc(); } } @@ -485,7 +490,7 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume } const totalTime = (Date.now() - startTime) / 1000; - console.log(`✅ 扫描完成: ${total} 个文件 (${totalTime.toFixed(1)}秒, ${(total / totalTime).toFixed(1)} 张/秒)`); + logger.info(`扫描完成: ${total} 个文件 (${totalTime.toFixed(1)}秒, ${(total / totalTime).toFixed(1)} 张/秒)`); // Update folder image counts db.updateAllFolderCounts(); @@ -496,7 +501,7 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume // 强制 GC(如果可用) if (global.gc) { global.gc(); - console.log('🧹 内存已清理'); + logger.debug('内存已清理'); } // 标记扫描完成 @@ -505,7 +510,7 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume } return results; } catch (error) { - console.error('❌ 扫描失败:', error.message); + logger.error('扫描失败:', error.message); if (libraryId) { scanManager.completeScan(libraryId); } diff --git a/backend/utils/thumbnail.js b/backend/utils/thumbnail.js index 530f49e..093a12a 100644 --- a/backend/utils/thumbnail.js +++ b/backend/utils/thumbnail.js @@ -2,25 +2,25 @@ const sharp = require('sharp'); const path = require('path'); const fs = require('fs'); const crypto = require('crypto'); +const { constants } = require('../src/config'); +const logger = require('../src/utils/logger'); // 配置 Sharp 内存限制(防止内存泄漏) -sharp.cache({ - memory: 20, // 最大缓存 20MB(更激进) - files: 0, // 禁用文件缓存 - items: 10 // 最多缓存 10 个操作 -}); +const SHARP_CONFIG = { + memory: constants.THUMBNAIL_GENERATION.SHARP_CACHE_MEMORY_MB, + files: 0, + items: constants.THUMBNAIL_GENERATION.SHARP_CACHE_ITEMS +}; + +sharp.cache(SHARP_CONFIG); // 设置并发限制 -sharp.concurrency(1); // 一次只处理 1 张图片 +sharp.concurrency(constants.THUMBNAIL_GENERATION.SHARP_CONCURRENCY); // 清理 Sharp 缓存的函数(扫描完成后调用) function clearSharpCache() { sharp.cache(false); // 完全禁用缓存 - sharp.cache({ // 重新启用最小缓存 - memory: 20, - files: 0, - items: 10 - }); + sharp.cache(SHARP_CONFIG); // 重新启用最小缓存 } // 支持的文件格式(确定可以生成缩略图的) @@ -215,8 +215,9 @@ async function generateThumbnail(inputPath, outputPath, targetHeight = 200) { sharpJagged = 1.0; } - // 固定高质量 92(平衡清晰度和体积) - const quality = 92; + // 使用配置的质量 + const quality = constants.THUMBNAIL_GENERATION.DEFAULT_QUALITY; + const effort = constants.THUMBNAIL_GENERATION.EFFORT; // 生成缩略图(使用 buffer,不锁定原文件) await sharp(inputBuffer) @@ -239,7 +240,7 @@ async function generateThumbnail(inputPath, outputPath, targetHeight = 200) { }) .webp({ quality: quality, - effort: 4, // 降低 effort,减少编码损失 + effort: effort, smartSubsample: false, // 关键!禁用色度子采样,保持边缘清晰 nearLossless: false, // 禁用近无损(会增加体积但不增加清晰度) preset: 'photo', @@ -251,7 +252,8 @@ async function generateThumbnail(inputPath, outputPath, targetHeight = 200) { inputBuffer = null; // 强制 GC(如果可用) - if (global.gc && Math.random() < 0.1) { // 10% 概率执行 GC + const gcProbability = constants.THUMBNAIL_GENERATION.GC_PROBABILITY; + if (global.gc && Math.random() < gcProbability) { global.gc(); } @@ -330,6 +332,8 @@ async function generateImageThumbnails(imagePath, libraryPath) { // Sharding: use first 2 chars of hash for subdirectories (e.g. /ab/) const shard1 = hash.slice(0, 2); + const targetHeight = constants.THUMBNAIL_GENERATION.TARGET_HEIGHT; + // 1-level sharding: .flypic/thumbnails/ab/hash.webp const out480 = path.join(flypicDir, 'thumbnails', shard1, `${hash}.webp`); fs.mkdirSync(path.dirname(out480), { recursive: true }); @@ -341,7 +345,7 @@ async function generateImageThumbnails(imagePath, libraryPath) { if (fileType === 'image' && canGenerateThumbnail(imagePath)) { // 图片:使用 Sharp 生成真实缩略图 - thumbnailResult = await generateThumbnail(imagePath, out480, 480); + thumbnailResult = await generateThumbnail(imagePath, out480, targetHeight); } else if (fileType === 'video') { // 视频:尝试提取封面 thumbnailResult = await extractVideoThumbnail(imagePath, out480); @@ -555,8 +559,8 @@ async function extractVideoThumbnail(videoPath, outputPath) { */ async function generatePlaceholderThumbnail(outputPath, type, label) { // 使用 Sharp 生成简单的占位图 - const width = 640; - const height = 480; + const width = constants.THUMBNAIL_GENERATION.PLACEHOLDER_WIDTH; + const height = constants.THUMBNAIL_GENERATION.PLACEHOLDER_HEIGHT; // 不同类型的背景色和图标 const typeConfig = { @@ -622,14 +626,14 @@ async function generatePlaceholderThumbnail(outputPath, type, label) { `; await sharp(Buffer.from(svg)) - .resize(640, 480) + .resize(width, height) .webp({ quality: 85 }) .toFile(outputPath); const stats = fs.statSync(outputPath); return { - width: 640, - height: 480, + width, + height, size: stats.size, path: outputPath }; diff --git a/frontend/src/api/client.js b/frontend/src/api/client.js index dec97ed..fc3303b 100644 --- a/frontend/src/api/client.js +++ b/frontend/src/api/client.js @@ -137,9 +137,19 @@ function patch(url, body, options = {}) { /** * DELETE 请求 + * 支持带 body 的 DELETE 请求(用于批量删除等操作) */ -function del(url, options = {}) { - return request(url, { method: 'DELETE', ...options }); +function del(url, body, options = {}) { + // 如果 body 是对象(非 options),则作为请求体发送 + if (body && typeof body === 'object' && !body.method) { + return request(url, { + method: 'DELETE', + body: JSON.stringify(body), + ...options + }); + } + // 否则,body 实际上是 options + return request(url, { method: 'DELETE', ...body }); } export const api = { diff --git a/frontend/src/api/file.js b/frontend/src/api/file.js index 9cedca3..3f5e190 100644 --- a/frontend/src/api/file.js +++ b/frontend/src/api/file.js @@ -14,10 +14,7 @@ export const fileAPI = { * @param {Array} items - 待删除项 [{type: 'file'|'folder', path: 'path'}] */ async delete(libraryId, items) { - return api.delete('/file/delete', { - body: JSON.stringify({ libraryId, items }), - headers: { 'Content-Type': 'application/json' } - }); + return api.delete('/file/delete', { libraryId, items }); }, /** diff --git a/frontend/src/components/FileViewer.jsx b/frontend/src/components/FileViewer.jsx index 6af0127..abfc365 100644 --- a/frontend/src/components/FileViewer.jsx +++ b/frontend/src/components/FileViewer.jsx @@ -8,15 +8,18 @@ import { imageAPI } from '../api'; function FileViewer({ file, libraryId, onClose }) { if (!file) return null; - const fileType = file.file_type || 'image'; + // 兼容前端的 fileType 字段和旧的 file_type 字段 + const fileType = file.fileType || file.file_type || 'image'; const originalUrl = imageAPI.getOriginalUrl(libraryId, file.path); - // 在系统默认应用中打开 + // 在浏览器中打开原始文件(交给浏览器/系统处理) const openInSystem = async () => { try { - await imageAPI.openInExplorer(libraryId, file.path); + if (originalUrl) { + window.open(originalUrl, '_blank'); + } } catch (error) { - console.error('Failed to open file:', error); + console.error('Failed to open file in browser:', error); } }; diff --git a/frontend/src/components/ImageWaterfall.jsx b/frontend/src/components/ImageWaterfall.jsx index 78cbcdd..ea515dc 100644 --- a/frontend/src/components/ImageWaterfall.jsx +++ b/frontend/src/components/ImageWaterfall.jsx @@ -1399,6 +1399,14 @@ function ImageWaterfall() { const isMultiSelection = selectedImages.length > 0; const menuOptions = []; + // 复制选项放在第一位 + menuOptions.push( + menuItems.copy(() => { + setContextMenu({ isOpen: false, position: null, image: null }); + handleCopy(); + }) + ); + // 只在单选时显示重命名选项 if (!isMultiSelection) { menuOptions.push( @@ -1410,10 +1418,6 @@ function ImageWaterfall() { } menuOptions.push( - menuItems.copy(() => { - setContextMenu({ isOpen: false, position: null, image: null }); - handleCopy(); - }), menuItems.move(handleMoveClick), menuItems.delete(async () => { setContextMenu({ isOpen: false, position: null, image: null }); diff --git a/frontend/src/components/RightPanel.jsx b/frontend/src/components/RightPanel.jsx index b230011..94f6a28 100644 --- a/frontend/src/components/RightPanel.jsx +++ b/frontend/src/components/RightPanel.jsx @@ -1,5 +1,5 @@ import { useState, useEffect, useRef } from 'react'; -import { Copy, Download, Check, FolderDown, ArrowLeft, Folder } from 'lucide-react'; +import { Copy, Download, Check, FolderDown, ArrowLeft, Folder, FileQuestion } from 'lucide-react'; import { useLibraryStore } from '../stores/useLibraryStore'; import { useImageStore } from '../stores/useImageStore'; import { useUIStore } from '../stores/useUIStore'; @@ -27,6 +27,10 @@ function RightPanel() { const [editingFilename, setEditingFilename] = useState(''); const filenameInputRef = useRef(null); const [isUpdatingRating, setIsUpdatingRating] = useState(false); + // 文件夹重命名相关 + const [isEditingFolderName, setIsEditingFolderName] = useState(false); + const [editingFolderName, setEditingFolderName] = useState(''); + const folderNameInputRef = useRef(null); // 计算实际选中的图片数量(合并 selectedImage 和 selectedImages) const actualSelectedCount = (() => { @@ -158,8 +162,9 @@ function RightPanel() { try { const result = await fileAPI.rename(currentLibraryId, selectedImage.path, newFilename); - const newPath = result.data.newPath; - const actualNewName = result.data.newName; + // client.js 已自动解包 data,直接访问属性 + const newPath = result.newPath; + const actualNewName = result.newName; updateImage(selectedImage.path, { path: newPath, @@ -182,6 +187,101 @@ function RightPanel() { setEditingFilename(''); }; + // ===== 文件夹重命名功能 ===== + + // 开始重命名文件夹 + const handleStartRenameFolderName = () => { + if (!selectedFolderItem) return; + setIsEditingFolderName(true); + setEditingFolderName(selectedFolderItem.name); + // 聚焦输入框 + setTimeout(() => { + folderNameInputRef.current?.focus(); + folderNameInputRef.current?.select(); + }, 50); + }; + + // 完成文件夹重命名 + const handleFinishRenameFolderName = async () => { + if (!selectedFolderItem || !editingFolderName.trim()) { + setIsEditingFolderName(false); + setEditingFolderName(''); + return; + } + + const oldName = selectedFolderItem.name; + const newName = editingFolderName.trim(); + + // 如果名称没有改变,直接退出 + if (newName === oldName) { + setIsEditingFolderName(false); + setEditingFolderName(''); + return; + } + + const oldPath = selectedFolderItem.path; + const isRenamingCurrentFolder = selectedFolder === oldPath; + + try { + // 调用重命名API + const result = await fileAPI.rename(currentLibraryId, oldPath, newName); + const newPath = result.newPath; + + console.log(`✅ 文件夹重命名成功: ${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}`); + setSelectedFolderGlobal(newPath); + } + + // 3. 后台刷新文件夹列表(确保数据一致性) + imageAPI.getFolders(currentLibraryId).then(foldersRes => { + console.log('📁 重命名后最新文件夹列表:', foldersRes.folders); + setFolders(foldersRes.folders); + + // 用最新数据更新选中的文件夹项 + const newFolderItem = foldersRes.folders.find(f => f.path === newPath); + if (newFolderItem) { + setSelectedFolderItem(newFolderItem); + } + }); + } catch (error) { + console.error('文件夹重命名失败:', error); + alert('重命名失败: ' + (error.message || '未知错误')); + } finally { + setIsEditingFolderName(false); + setEditingFolderName(''); + } + }; + + // 取消文件夹重命名 + const handleCancelRenameFolderName = () => { + setIsEditingFolderName(false); + setEditingFolderName(''); + }; + + // 文件夹名称键盘事件处理 + const handleFolderNameKeyDown = (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + handleFinishRenameFolderName(); + } else if (e.key === 'Escape') { + e.preventDefault(); + handleCancelRenameFolderName(); + } + }; + // 更新评分(支持单选和多选) const handleRatingChange = async (newRating) => { const imagesToRate = getImagesToProcess(); @@ -230,6 +330,13 @@ function RightPanel() { return () => window.removeEventListener('resize', checkMobile); }, []); + // 判断是否为可以直接显示原图的格式 + const canShowOriginal = (format) => { + if (!format) return false; + const supportedFormats = ['jpg', 'jpeg', 'png', 'webp']; + return supportedFormats.includes(format.toLowerCase()); + }; + // 图片加载策略:先显示缩略图,后台加载原图;拖动右侧面板时只显示缩略图 useEffect(() => { if (!selectedImage || !currentLibraryId) { @@ -240,6 +347,18 @@ function RightPanel() { // 1. 立即显示缩略图 const thumbnailUrl = getThumbnailUrl(); setImageUrl(thumbnailUrl); + + // 检查图片格式 + const imageFormat = selectedImage.format; + const shouldLoadOriginal = canShowOriginal(imageFormat); + + // 对于不支持的格式,只显示缩略图 + if (!shouldLoadOriginal) { + setIsLoadingOriginal(false); + console.log(`格式 ${imageFormat} 不支持直接显示原图,使用缩略图`); + return; + } + setIsLoadingOriginal(true); // 如果正在拖动任一面板,则先不加载原图,降低主线程和解码压力 @@ -248,7 +367,7 @@ function RightPanel() { return; } - // 2. 后台预加载原图 + // 2. 后台预加载原图(仅支持的格式) const originalUrl = getOriginalUrl(); const img = new Image(); @@ -286,9 +405,15 @@ function RightPanel() { } const getThumbnailUrl = () => { - if (!currentLibraryId || !selectedImage?.thumbnail_path) return ''; + if (!currentLibraryId) return ''; + // 支持两种字段名 + const thumbnailPath = selectedImage?.thumbnailPath || selectedImage?.thumbnail_path; + if (!thumbnailPath) { + console.warn('缩略图路径不存在:', selectedImage); + return ''; + } // Handle both forward and backslash - const filename = selectedImage.thumbnail_path.replace(/\\/g, '/').split('/').pop(); + const filename = thumbnailPath.replace(/\\/g, '/').split('/').pop(); return imageAPI.getThumbnailUrl(currentLibraryId, filename); }; @@ -991,7 +1116,27 @@ function RightPanel() {
{folderName}
+ {isEditingFolderName ? ( + setEditingFolderName(e.target.value)} + onBlur={handleFinishRenameFolderName} + onKeyDown={handleFolderNameKeyDown} + className="w-full text-gray-900 dark:text-gray-100 bg-transparent border-none outline-none focus:outline-none break-all underline decoration-2 decoration-blue-500 underline-offset-2" + style={{ padding: 0, margin: 0 }} + placeholder="输入文件夹名" + /> + ) : ( ++ {folderName} +
+ )}缩略图不可用
+{displayImage?.format?.toUpperCase() || '未知格式'}
+双击查看原文件
+{stats.count} 张图片
+{stats.count} 张图片
+
{stats.dimensionRange.minWidth === stats.dimensionRange.maxWidth && stats.dimensionRange.minHeight === stats.dimensionRange.maxHeight ? ( // 所有图片尺寸相同 @@ -1163,11 +1396,11 @@ function RightPanel() {
{formatFileSize(stats.totalSize)}
+{formatFileSize(stats.totalSize)}
+
{stats.formats.join(', ')}
@@ -1248,24 +1481,24 @@ function RightPanel() {
{selectedImage.width} × {selectedImage.height}
+{selectedImage.width} × {selectedImage.height}
{formatFileSize(selectedImage.size)}
+{formatFileSize(selectedImage.size)}
{selectedImage.format}
+{selectedImage.format}
{formatDate(selectedImage.createdAt || selectedImage.created_at)}
+{formatDate(selectedImage.createdAt || selectedImage.created_at)}
{formatDate(selectedImage.modifiedAt || selectedImage.modified_at)}
+{formatDate(selectedImage.modifiedAt || selectedImage.modified_at)}