基础优化

This commit is contained in:
Chen committed 2025-12-07 11:37:00 +08:00
1 parent b606190e0c
commit 6394ac16a2
14 files changed
+457 -177

No files matched your search

+10 -7
View File
@@ -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);
}
/**
-1
View File
@@ -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",
+39 -6
View File
@@ -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 // 是否检查离线变化
}
};
+15 -33
View File
@@ -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);
}
}
}
/**
* 获取数据库实例
*/
+15 -10
View File
@@ -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);
}
+25 -21
View File
@@ -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
};
+12 -2
View File
@@ -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 = {
+1 -4
View File
@@ -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 });
},
/**
+7 -4
View File
@@ -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);
}
};
+8 -4
View File
@@ -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 });
+268 -62
View File
@@ -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() {
<div className="space-y-2 text-sm">
<div>
<span className="text-gray-500 dark:text-gray-400">文件夹名:</span>
<p className="text-gray-900 dark:text-gray-100 break-all">{folderName}</p>
{isEditingFolderName ? (
<input
ref={folderNameInputRef}
type="text"
value={editingFolderName}
onChange={(e) => 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="输入文件夹名"
/>
) : (
<p
className="text-gray-900 dark:text-gray-100 break-all cursor-pointer hover:text-blue-500 transition-colors"
onClick={handleStartRenameFolderName}
title="点击重命名"
>
{folderName}
</p>
)}
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">包含图片:</span>
@@ -1083,30 +1228,118 @@ function RightPanel() {
{/* Progressive Image Preview */}
<div className="p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
<div className="w-full aspect-square bg-transparent border border-gray-200 dark:border-gray-600 rounded-lg overflow-hidden relative">
<img
src={imageUrl}
alt={displayImage.filename}
decoding="async"
className={`w-full h-full object-contain transition-opacity duration-300 ${
isLoadingOriginal ? 'opacity-75' : 'opacity-100'
}`}
/>
{isLoadingOriginal && (
<div className="absolute top-2 right-2 bg-blue-500 text-white text-xs px-2 py-1 rounded">
加载原图中...
</div>
)}
</div>
{isMultiSelect ? (
// 多选模式:显示堆叠效果(前5张)
<div
className="w-full aspect-square bg-transparent rounded-lg relative flex items-center justify-center cursor-pointer"
onDoubleClick={() => {
// 双击打开第一张图片原文件(交给浏览器原生处理)
const firstImage = getImagesToProcess()[0];
if (firstImage && currentLibraryId) {
const originalUrl = imageAPI.getOriginalUrl(currentLibraryId, firstImage.path);
if (originalUrl) {
window.open(originalUrl, '_blank');
}
}
}}
title="双击查看第一张图片"
>
{(() => {
const imagesToShow = getImagesToProcess().slice(0, 5);
const stackCount = imagesToShow.length;
return imagesToShow.map((img, index) => {
// 从前往后堆叠,第一张在最上面
const reverseIndex = stackCount - 1 - index;
// 计算偏移,让堆叠整体居中(减去一半的最大偏移量)
const maxOffset = (stackCount - 1) * 6;
const offsetX = reverseIndex * 6 - maxOffset / 2;
const offsetY = reverseIndex * 6 - maxOffset / 2;
const rotation = (reverseIndex - (stackCount - 1) / 2) * 5; // 旋转效果(增大角度)
const zIndex = stackCount - 1 - index; // 第一张图 zIndex 最大
// 提取缩略图文件名
const thumbnailPath = img.thumbnailPath || img.thumbnail_path;
const filename = thumbnailPath ? thumbnailPath.replace(/\\/g, '/').split('/').pop() : '';
const imgUrl = filename ? imageAPI.getThumbnailUrl(currentLibraryId, filename) : '';
return (
<div
key={img.id}
className="absolute border-[3px] border-white dark:border-gray-600 rounded-lg overflow-hidden transition-all bg-white dark:bg-gray-800"
style={{
width: '85%',
height: '85%',
transform: `translate(${offsetX}px, ${offsetY}px) rotate(${rotation}deg)`,
zIndex: zIndex,
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.1)'
}}
>
<img
src={imgUrl}
alt={img.filename}
decoding="async"
className="w-full h-full object-cover"
/>
</div>
);
});
})()}
{actualSelectedCount > 5 && (
<div className="absolute bottom-2 right-2 bg-blue-500 text-white text-xs px-3 py-1.5 rounded-full shadow-lg font-semibold" style={{ zIndex: 100 }}>
+{actualSelectedCount - 5}
</div>
)}
</div>
) : (
// 单选模式:显示单张图片
<div
className="w-full aspect-square bg-transparent border border-gray-200 dark:border-gray-600 rounded-lg overflow-hidden relative cursor-pointer"
onDoubleClick={() => {
// 双击始终打开原始文件 URL(交给浏览器原生处理)
const originalUrl = getOriginalUrl();
if (originalUrl) {
window.open(originalUrl, '_blank');
}
}}
title="双击查看原文件"
>
{imageUrl ? (
<img
src={imageUrl}
alt={displayImage.filename}
decoding="async"
className={`w-full h-full object-contain transition-opacity duration-300 ${
isLoadingOriginal ? 'opacity-75' : 'opacity-100'
}`}
onError={(e) => {
console.error('图片加载失败:', imageUrl);
e.target.style.display = 'none';
}}
/>
) : (
<div className="w-full h-full flex flex-col items-center justify-center bg-gray-50 dark:bg-gray-900">
<FileQuestion className="w-20 h-20 text-gray-400 dark:text-gray-600 mb-2" />
<p className="text-sm text-gray-500 dark:text-gray-400">缩略图不可用</p>
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1">{displayImage?.format?.toUpperCase() || '未知格式'}</p>
<p className="text-xs text-blue-500 dark:text-blue-400 mt-2">双击查看原文件</p>
</div>
)}
{isLoadingOriginal && imageUrl && (
<div className="absolute top-2 right-2 bg-blue-500 text-white text-xs px-2 py-1 rounded">
加载原图中...
</div>
)}
</div>
)}
</div>
{/* Image Info - 可滚动区域 */}
<div className="flex-1 overflow-y-auto p-4 space-y-4 min-h-0">
<div>
<h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
<h3 className="text-xs font-semibold text-gray-700 dark:text-gray-300 mb-2">
{isMultiSelect ? `已选择 ${actualSelectedCount} 张图片` : '基本信息'}
</h3>
<div className="space-y-2 text-sm">
<div className="space-y-2 text-xs">
{isMultiSelect ? (
// 多选模式
(() => {
@@ -1117,7 +1350,7 @@ function RightPanel() {
<>
<div>
<span className="text-gray-500 dark:text-gray-400">数量:</span>
<p className="text-gray-900 dark:text-gray-100">{stats.count} 张图片</p>
<p className="text-gray-900 dark:text-gray-100 text-xs">{stats.count} 张图片</p>
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">评分:</span>
@@ -1150,7 +1383,7 @@ function RightPanel() {
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">尺寸范围:</span>
<p className="text-gray-900 dark:text-gray-100">
<p className="text-gray-900 dark:text-gray-100 text-xs">
{stats.dimensionRange.minWidth === stats.dimensionRange.maxWidth &&
stats.dimensionRange.minHeight === stats.dimensionRange.maxHeight ? (
// 所有图片尺寸相同
@@ -1163,11 +1396,11 @@ function RightPanel() {
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">总大小:</span>
<p className="text-gray-900 dark:text-gray-100">{formatFileSize(stats.totalSize)}</p>
<p className="text-gray-900 dark:text-gray-100 text-xs">{formatFileSize(stats.totalSize)}</p>
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">格式:</span>
<p className="text-gray-900 dark:text-gray-100 uppercase">
<p className="text-gray-900 dark:text-gray-100 text-xs uppercase">
{stats.formats.join(', ')}
</p>
</div>
@@ -1223,12 +1456,12 @@ function RightPanel() {
}
}}
onBlur={handleFinishRename}
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"
className="w-full text-gray-900 dark:text-gray-100 text-xs 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 }}
/>
) : (
<p
className="text-gray-900 dark:text-gray-100 break-all cursor-pointer hover:text-blue-500 transition-colors"
className="text-gray-900 dark:text-gray-100 text-xs break-all cursor-pointer hover:text-blue-500 transition-colors"
onClick={handleStartRename}
title="点击编辑文件名"
>
@@ -1248,24 +1481,24 @@ function RightPanel() {
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">尺寸:</span>
<p className="text-gray-900 dark:text-gray-100">{selectedImage.width} × {selectedImage.height}</p>
<p className="text-gray-900 dark:text-gray-100 text-xs">{selectedImage.width} × {selectedImage.height}</p>
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">文件大小:</span>
<p className="text-gray-900 dark:text-gray-100">{formatFileSize(selectedImage.size)}</p>
<p className="text-gray-900 dark:text-gray-100 text-xs">{formatFileSize(selectedImage.size)}</p>
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">格式:</span>
<p className="text-gray-900 dark:text-gray-100 uppercase">{selectedImage.format}</p>
<p className="text-gray-900 dark:text-gray-100 text-xs uppercase">{selectedImage.format}</p>
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">创建时间:</span>
<p className="text-gray-900 dark:text-gray-100">{formatDate(selectedImage.createdAt || selectedImage.created_at)}</p>
<p className="text-gray-900 dark:text-gray-100 text-xs">{formatDate(selectedImage.createdAt || selectedImage.created_at)}</p>
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">修改时间:</span>
<p className="text-gray-900 dark:text-gray-100">{formatDate(selectedImage.modifiedAt || selectedImage.modified_at)}</p>
<p className="text-gray-900 dark:text-gray-100 text-xs">{formatDate(selectedImage.modifiedAt || selectedImage.modified_at)}</p>
</div>
</>
)}
@@ -1367,33 +1600,6 @@ function RightPanel() {
</div>
)}
</button>
{/* 导出文件夹按钮 */}
{selectedFolder && (
<button
onClick={exportCurrentFolder}
disabled={isExportingFolder}
className="w-full flex flex-col items-center justify-center gap-2 px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="flex items-center gap-2">
<FolderDown className="w-4 h-4" />
<span>
{isExportingFolder
? `打包文件夹... ${folderExportProgress}%`
: '导出当前文件夹'
}
</span>
</div>
{isExportingFolder && (
<div className="w-full bg-gray-300 dark:bg-gray-600 rounded-full h-1.5 mt-1">
<div
className="bg-gray-700 dark:bg-gray-300 h-1.5 rounded-full transition-all duration-300"
style={{ width: `${folderExportProgress}%` }}
/>
</div>
)}
</button>
)}
</div>
)}
</div>
+13 -21
View File
@@ -527,28 +527,20 @@ function Sidebar() {
console.log(`✅ 文件夹重命名成功: ${oldName} → ${newName}, 路径: ${oldPath} → ${newPath}`);
// 1. 立即清空图片列表(避免显示旧路径的无效图片)
const { setImages, setFolders, setSelectedFolder: setSelectedFolderGlobal } = useImageStore.getState();
setImages([]);
const { setFolders, setSelectedFolder: setSelectedFolderGlobal } = useImageStore.getState();
// 2. 重新加载文件夹列表(关键:确保浏览器重新渲染)
const foldersRes = await imageAPI.getFolders(currentLibraryId);
console.log('📁 重命名后最新文件夹列表:', foldersRes.folders);
setFolders(foldersRes.folders);
// 3. 如果重命名的是当前选中的文件夹,强制触发重新加载
// 1. 如果重命名的是当前选中的文件夹,立即切换到新路径
// 这样可以避免先显示全部图片的闪烁
if (isRenamingCurrentFolder) {
console.log(`📂 重命名当前文件夹: ${oldPath} → ${newPath}`);
// 先切换到 null,再切换到新路径,强制触发 useEffect
setSelectedFolderGlobal(null);
// 使用 setTimeout 确保状态更新被 React 检测到
setTimeout(() => {
setSelectedFolderGlobal(newPath);
console.log('✅ 已切换到新文件夹, selectedFolder =', newPath);
}, 50);
setSelectedFolderGlobal(newPath);
}
// 2. 后台刷新文件夹列表(不阻塞UI)
imageAPI.getFolders(currentLibraryId).then(foldersRes => {
console.log('📁 重命名后最新文件夹列表:', foldersRes.folders);
setFolders(foldersRes.folders);
});
} catch (error) {
console.error('文件夹重命名失败:', error);
alert('重命名失败: ' + (error.message || '未知错误'));
@@ -1404,15 +1396,15 @@ function Sidebar() {
className={`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${selectedFolder === null
? 'bg-blue-50 dark:bg-blue-900'
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
}`}
onClick={() => setSelectedFolder(null)}
>
<div className="w-5 mr-1" />
<Folder className="w-4 h-4 mr-2 text-blue-500 flex-shrink-0" />
<span className="text-sm text-gray-700 dark:text-gray-300 font-medium flex-1">
<span className="text-sm text-gray-700 dark:text-gray-200 font-medium flex-1">
全部图片
</span>
<span className="text-xs text-gray-500 dark:text-gray-400 ml-2">
<span className="text-xs text-gray-500 dark:text-gray-300 ml-2">
{totalImageCount}
</span>
</div>
+40
View File
@@ -0,0 +1,40 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// 备用配置:禁用代码分割(如果有问题可以使用此配置)
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
'/api': {
target: process.env.VITE_API_URL || 'http://localhost:15002',
changeOrigin: true
}
}
},
build: {
outDir: 'dist',
assetsDir: 'assets',
emptyOutDir: true,
// 提高 chunk 大小警告阈值
chunkSizeWarningLimit: 1000,
rollupOptions: {
output: {
// 使用简单的代码分割
manualChunks: {
'vendor-react': ['react', 'react-dom'],
'vendor-ui': ['lucide-react', 'react-photo-view'],
}
}
}
},
worker: {
// 确保 Worker 使用 ES 模块格式
format: 'es',
plugins: () => []
},
optimizeDeps: {
exclude: ['layoutWorker.js']
}
})
+4 -2
View File
@@ -16,10 +16,12 @@ export default defineConfig({
outDir: 'dist',
assetsDir: 'assets',
emptyOutDir: true,
// 提高 chunk 大小警告阈值(可选)
chunkSizeWarningLimit: 600,
rollupOptions: {
output: {
// 确保 Worker 文件正确打包
manualChunks: undefined
// 暂时禁用代码分割,避免依赖问题
// manualChunks: undefined
}
}
},